text
stringlengths
11
4.05M
package sorting type MergeSort struct { } func (sort *MergeSort) separate(a *[]int32, buf *[]int32, start int, end int) { if start >= end { return } mid := int((start + end) / 2) sort.separate(a, buf, start, mid) sort.separate(a, buf, mid + 1, end) sort.merge(a, buf, start, mid, end) } func (sort *MergeSort) merge(a *[]int32, buf *[]int32, start int, mid int, end int) { j := 0 lowerPtr := start higherPtr := mid + 1 for ; lowerPtr <= mid && higherPtr <= end; j++ { (*buf)[j] = func() (int32) { if (*a)[lowerPtr] < (*a)[higherPtr] { lowerPtr++ return (*a)[lowerPtr - 1] } else { higherPtr++ return (*a)[higherPtr - 1] } }() } for ; lowerPtr <= mid; j++ { (*buf)[j] = (*a)[lowerPtr] lowerPtr++ } for ; higherPtr <= end; j++ { (*buf)[j] = (*a)[higherPtr] higherPtr++ } for i := 0; i <= end - start; i++ { (*a)[start + i] = (*buf)[i] } } func (sort *MergeSort) Sort(a *[]int32) { buf := make([]int32, len(*a)) sort.separate(a, &buf, 0, len(*a) - 1) }
package hookexecutor import ( "os" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" fakekubeclientset "k8s.io/client-go/kubernetes/fake" testcore "k8s.io/client-go/testing" ) var _ = PDescribe("Sanity", func() { var e Executor var kubeClient *fakekubeclientset.Clientset var pvc *v1.PersistentVolumeClaim var pod *v1.Pod var testNamespace = "test" BeforeEach(func() { os.Setenv("STORAGE_CLASS", "gold") os.Setenv("NAMESPACE", testNamespace) pvc, pod = getSanityPvcAndPod() kubeClient = fakekubeclientset.NewSimpleClientset() e = SanityExecutor(kubeClient) }) AfterEach(func() { os.Setenv("STORAGE_CLASS", "") os.Setenv("NAMESPACE", "") }) Describe("test Execute", func() { Context("update namespace", func() { BeforeEach(func() { os.Setenv("NAMESPACE", testNamespace) Expect(pvc.Namespace).NotTo(Equal(testNamespace)) Expect(pod.Namespace).NotTo(Equal(testNamespace)) err := updateNamespace([]runtime.Object{pvc, pod}) Ω(err).ShouldNot(HaveOccurred()) }) It("should update the namespace to the specified one", func() { Expect(pvc.Namespace).To(Equal(testNamespace)) Expect(pod.Namespace).To(Equal(testNamespace)) }) }) Context("create sanity resources", func() { BeforeEach(func() { pvc.SetNamespace(testNamespace) pod.SetNamespace(testNamespace) // pvc and pod are not existing on API Server at first. _, err := kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) Expect(apierrors.IsNotFound(err)).To(BeTrue()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{}) Expect(apierrors.IsNotFound(err)).To(BeTrue()) go func() { pvcWatcher := watch.NewFake() kubeClient.PrependWatchReactor("persistentvolumeclaims", testcore.DefaultWatchReactor(pvcWatcher, nil)) // sleep and set the phase of the pvc to "Bound" time.Sleep(50 * time.Millisecond) newPvc := pvc.DeepCopy() newPvc.Status.Phase = v1.ClaimBound pvcWatcher.Modify(newPvc) }() go func() { podWatcher := watch.NewFake() kubeClient.PrependWatchReactor("pods", testcore.DefaultWatchReactor(podWatcher, nil)) // sleep and set the phase of the pvc to "Running", should sleep longer that pvc time.Sleep(100 * time.Millisecond) newPod := pod.DeepCopy() newPod.Status.Phase = v1.PodRunning podWatcher.Modify(newPod) }() }) It("should create pod and pvc successfully", func(done Done) { err := e.(*sanityExecutor).createSanityResources() Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) close(done) }) }) Context("keep resources if creating sanity resources is failed", func() { BeforeEach(func() { pvc.SetNamespace(testNamespace) pod.SetNamespace(testNamespace) go func() { pvcWatcher := watch.NewFake() kubeClient.PrependWatchReactor("persistentvolumeclaims", testcore.DefaultWatchReactor(pvcWatcher, nil)) // sleep and set the phase of the pvc to "Bound" time.Sleep(50 * time.Millisecond) newPvc := pvc.DeepCopy() newPvc.Status.Phase = v1.ClaimBound pvcWatcher.Modify(newPvc) }() // create the pod in advance to generate a "pod already exists" error kubeClient.CoreV1().Pods(pod.Namespace).Create(pod) }) It("should leave the pvc and pod as it is", func(done Done) { err := e.(*sanityExecutor).createSanityResources() Ω(err).Should(HaveOccurred()) Expect(apierrors.IsAlreadyExists(err)).To(BeTrue()) _, err = kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) close(done) }) }) Context("delete sanity resources", func() { BeforeEach(func() { pvc.SetNamespace(testNamespace) pod.SetNamespace(testNamespace) // create the pod and pvc _, err := kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Create(pvc) Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Create(pod) Ω(err).ShouldNot(HaveOccurred()) // check pod and pvc are existing on API Server _, err = kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{}) Ω(err).ShouldNot(HaveOccurred()) go func() { pvcWatcher := watch.NewFake() kubeClient.PrependWatchReactor("persistentvolumeclaims", testcore.DefaultWatchReactor(pvcWatcher, nil)) // should sleep longer than pod time.Sleep(100 * time.Millisecond) pvcWatcher.Delete(pvc) }() go func() { podWatcher := watch.NewFake() kubeClient.PrependWatchReactor("pods", testcore.DefaultWatchReactor(podWatcher, nil)) time.Sleep(50 * time.Millisecond) podWatcher.Delete(pod) }() }) It("should delete pod and pvc successfully", func(done Done) { err := e.(*sanityExecutor).deleteSanityResources() Ω(err).ShouldNot(HaveOccurred()) _, err = kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) Expect(apierrors.IsNotFound(err)).To(BeTrue()) _, err = kubeClient.CoreV1().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{}) Expect(apierrors.IsNotFound(err)).To(BeTrue()) close(done) }) }) }) })
// This file was generated for SObject SecureAgent, API Version v43.0 at 2018-07-30 03:47:25.074501777 -0400 EDT m=+11.417536634 package sobjects import ( "fmt" "strings" ) type SecureAgent struct { BaseSObject AgentKey string `force:",omitempty"` CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` DeveloperName string `force:",omitempty"` Id string `force:",omitempty"` IsDeleted bool `force:",omitempty"` Language string `force:",omitempty"` LastModifiedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` MasterLabel string `force:",omitempty"` Priority int `force:",omitempty"` ProxyUserId string `force:",omitempty"` SecureAgentsClusterId string `force:",omitempty"` SystemModstamp string `force:",omitempty"` } func (t *SecureAgent) ApiName() string { return "SecureAgent" } func (t *SecureAgent) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("SecureAgent #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tAgentKey: %v\n", t.AgentKey)) builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById)) builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate)) builder.WriteString(fmt.Sprintf("\tDeveloperName: %v\n", t.DeveloperName)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted)) builder.WriteString(fmt.Sprintf("\tLanguage: %v\n", t.Language)) builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById)) builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate)) builder.WriteString(fmt.Sprintf("\tMasterLabel: %v\n", t.MasterLabel)) builder.WriteString(fmt.Sprintf("\tPriority: %v\n", t.Priority)) builder.WriteString(fmt.Sprintf("\tProxyUserId: %v\n", t.ProxyUserId)) builder.WriteString(fmt.Sprintf("\tSecureAgentsClusterId: %v\n", t.SecureAgentsClusterId)) builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp)) return builder.String() } type SecureAgentQueryResponse struct { BaseQuery Records []SecureAgent `json:"Records" force:"records"` }
package main import ( "bufio" "flag" "log" "os" "strconv" "strings" "sync" ) var ( totalProxies []string urls []string timeout int = 5 input string = "urls.txt" output string = "proxies.txt" ) func main() { flag.StringVar(&input, "input", input, "File to input urls") flag.StringVar(&output, "output", output, "File to output scraped proxies") flag.IntVar(&timeout, "timeout", timeout, "Timeout to proxy list websites.") flag.Parse() file, err := os.Open(input) if err != nil { log.Println("Error reading " + input) return } scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { urls = append(urls, scanner.Text()) } file.Close() var wg sync.WaitGroup for i, url := range urls { wg.Add(1) go worker(i, &wg, url) } wg.Wait() totalProxies = uniqueArray(totalProxies) log.Println("[Main] Scraped " + strconv.Itoa(len(totalProxies)) + " unique proxies") if len(totalProxies) == 0 { return } file, err = os.Create(output) if err != nil { log.Println(err) return } _, err = file.WriteString(strings.Join(totalProxies, "\n")) if err != nil { log.Println(err) file.Close() return } err = file.Close() if err != nil { log.Println(err) return } log.Println("[Main] Wrote proxies to " + output) } func worker(id int, wg *sync.WaitGroup, url string) { log.Println("[" + strconv.Itoa(id+1) + "] Scraping @ " + url) proxies, err := scrape(url, timeout) if err != nil { log.Println("[" + strconv.Itoa(id+1) + "] " + err.Error() + " @ " + url) wg.Done() return } log.Println("[" + strconv.Itoa(id+1) + "] Scraped " + strconv.Itoa(len(proxies)) + " proxies @ " + url) for _, proxy := range proxies { totalProxies = append(totalProxies, proxy) } wg.Done() } func uniqueArray(array []string) []string { m := make(map[string]bool) for _, item := range array { _, ok := m[item] if ok == false { m[item] = true } } var unique []string for item := range m { unique = append(unique, item) } return unique }
package main import "fmt" func main() { var x interface{} x = 10 switch x.(type) { case int: v := x.(int) fmt.Printf("type=%T, value=%d\n", x, x) // error //x += 10 fmt.Printf("type=%T, value=%d\n", v, v) v += 10 fmt.Printf("type=%T, value=%d\n", v, v) default: fmt.Println("don't know") } }
// Copyright 2021 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 bindinfo import ( "github.com/pingcap/tidb/sessionctx/variable" ) var ( lastPlanBindingUpdateTime = "last_plan_binding_update_time" ) // GetScope gets the status variables scope. func (*BindHandle) GetScope(_ string) variable.ScopeFlag { return variable.ScopeSession } // Stats returns the server statistics. func (h *BindHandle) Stats(_ *variable.SessionVars) (map[string]interface{}, error) { h.bindInfo.Lock() defer func() { h.bindInfo.Unlock() }() m := make(map[string]interface{}) m[lastPlanBindingUpdateTime] = h.bindInfo.lastUpdateTime.String() return m, nil }
package server import ( "database/sql" "encoding/json" "fmt" "github.com/golang/glog" "io/ioutil" "net/http" "strconv" "strings" ) type reqConfigFilePagesNew1 struct{ Token string CompanyName string } func ConfigFilePagesNew1(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("ConfigFilePagesNew1 recv body:", string(result)) var m reqConfigFilePagesNew1 err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } //检查token过期情况 var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ glog.Info(err_token) retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = err_token.Error() bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) //查询公司名称 companyName_slice := make([](map[string]string), 0) { var Queryconfig *sql.Rows if len(m.CompanyName) > 0{ var err error sql :=`SELECT id, companyName FROM proxypro.company where estatus = 1 and companyName like "%` + m.CompanyName + `%";` Queryconfig, err = Db.Query(sql) if err != nil { glog.Info(err) } }else{ var err error sql :=`SELECT id, companyName FROM proxypro.company where estatus = 1;` Queryconfig, err = Db.Query(sql) if err != nil { glog.Info(err) } } for Queryconfig.Next(){ var id string var companyName string err := Queryconfig.Scan(&id, &companyName) if err!=nil{ glog.Info(err) } tmp_map := make(map[string]string,0) tmp_map["id"] = id tmp_map["companyName"] = companyName companyName_slice = append(companyName_slice, tmp_map) } Queryconfig.Close() } glog.Info(companyName_slice) /* tmp_map_slice := make([](map[string]string),0) { Queryconfig, err := Db.Query(`SELECT companyNameID, subcompany, redirectUrl, DNS, platform, createTime FROM proxypro.webConfig where estatus = 1;`) if err != nil { glog.Info(err) } for Queryconfig.Next(){ var companyNameID string var subcompany string var redirectUrl string var DNS string var platform string var createTime string err := Queryconfig.Scan(&companyNameID, &subcompany, &redirectUrl, &DNS, &platform, &createTime) if err!=nil{ glog.Info(err) } tmp_map := make(map[string]string,0) tmp_map["companyNameID"] = companyNameID tmp_map["subcompany"] = subcompany tmp_map["redirectUrl"] = redirectUrl tmp_map["DNS"] = DNS tmp_map["platform"] = platform tmp_map["createTime"] = createTime tmp_map_slice = append(tmp_map_slice, tmp_map) } Queryconfig.Close() } */ type webcount struct { CompanyNameID int CompanyName string SubCompanyCount int64 DomainNameCount int64 } mutex.Lock() defer mutex.Unlock() //data_slice := make([](map[string]*webcount), 0) data_map := make(map[string]*webcount) //公司名称作为key for _,value := range WebConfig_tmp_map_slice { for _,v := range companyName_slice{ if v["id"] == value["companyNameID"]{ tmp := &webcount{} if _,ok:= data_map[v["companyName"]]; ok { tmp_name := v["companyName"] data_map[v["companyName"]].SubCompanyCount ++ slice := strings.Split(value["redirectUrl"], "|") if len(slice) ==1 && slice[0] == "0"{ }else{ data_map[tmp_name].DomainNameCount = data_map[tmp_name].DomainNameCount + int64(len(slice)) } }else{ tmp_name := v["companyName"] tmp.CompanyName = tmp_name tmp.CompanyNameID,_ = strconv.Atoi(v["id"]) tmp.SubCompanyCount = 1 slice := strings.Split(value["redirectUrl"], "|") if len(slice) ==1 && slice[0] == "0"{ tmp.DomainNameCount = 0 }else{ tmp.DomainNameCount = int64(len(slice)) } data_map[tmp_name] = tmp } } } } for _,v := range companyName_slice{ if _,ok := data_map[v["companyName"]]; ok{ }else{ tmp := &webcount{} tmp.CompanyName = v["companyName"] tmp.CompanyNameID,_ = strconv.Atoi(v["id"]) data_map[v["companyName"]] = tmp } } data_slice := make([]interface{},0) if len(data_map) > 0 { /*if len(m.CompanyName)> 0 { if _,ok := data_map[m.CompanyName]; ok{ data_slice = append(data_slice, data_map[m.CompanyName]) } }else{ for _,value := range data_map { data_slice = append(data_slice, value) } }*/ for _, value := range data_map { data_slice = append(data_slice, value) } retValue := &ResponseData{} retValue.Success = true retValue.Code = 0 retValue.Message = "Success" retValue.Data = data_slice bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqConfigEidt struct { Id int //companyNameID Token string SubcompanyName string } func ConfigEidt(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("ConfigEidt recv body:", string(result)) var m reqConfigEidt err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) //查询公司名称 var id string var companyName string companyName_slice := make([](map[string]string), 0) { Queryconfig, err := Db.Query(`SELECT id, companyName FROM proxypro.company where estatus = 1;`) if err != nil { glog.Info(err) } for Queryconfig.Next(){ err := Queryconfig.Scan(&id, &companyName) if err!=nil{ glog.Info(err) } tmp_map := make(map[string]string,0) tmp_map["id"] = id tmp_map["companyName"] = companyName companyName_slice = append(companyName_slice, tmp_map) } Queryconfig.Close() } glog.Info(companyName_slice) tmp_map_slice := make([](map[string]string),0) { var Queryconfig *sql.Rows var err error if len(m.SubcompanyName) > 0{ sql := `SELECT id, companyNameID, subcompany, platform, createTime, URL, redirectUrl, DNS FROM proxypro.webConfig where companyNameID = ? and estatus = 1 and subcompany like "%` + m.SubcompanyName + `%" order by createTime desc;` glog.Info("sql:", sql) Queryconfig, err = Db.Query(sql, m.Id) }else{ Queryconfig, err = Db.Query(`SELECT id, companyNameID, subcompany, platform, createTime, URL, redirectUrl, DNS FROM proxypro.webConfig where companyNameID = ? and estatus = 1 order by createTime desc ;`, m.Id) } if err != nil { glog.Info(err) } for Queryconfig.Next(){ var id int64 var companyNameID string var subcompany string var redirectUrl string var DNS string var platform string var createTime string var URL string err3 := Queryconfig.Scan(&id, &companyNameID, &subcompany, &platform, &createTime, &URL,&redirectUrl,&DNS) if err!=nil{ glog.Info(err3) }else{ } tmp_map := make(map[string]string,0) tmp_map["id"] = strconv.FormatInt(id,10) tmp_map["companyNameID"] = companyNameID tmp_map["subcompanyName"] = subcompany tmp_map["redirectUrl"] = redirectUrl tmp_map["DNS"] = DNS tmp_map["platform"] = platform tmp_map["createTime"] = createTime tmp_map["URL"] = URL tmp_map_slice = append(tmp_map_slice, tmp_map) } Queryconfig.Close() } //if len(tmp_map_slice) > 0 data_slice := make([]interface{},0) for _,value := range tmp_map_slice{ slice := strings.Split(value["redirectUrl"], "|") if len(slice) ==1 && slice[0] == "0"{ value["DomainNameCount"] = strconv.Itoa(0) value["redirectUrl"] = "" }else{ count := strconv.Itoa(len(slice)) value["DomainNameCount"] = count } data_slice = append(data_slice, value) } retValue := &ResponseData{} retValue.Success = true retValue.Code = 0 retValue.Message = "Success" retValue.Data = data_slice bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqCompanyName struct { CompanyNameID int CompanyName string Token string } func SetCompanyName(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("SetRedirectUrl recv body:", string(result)) var m reqCompanyName err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) //查询公司名称重复 { Queryconfig, err := Db.Query(`SELECT companyName FROM proxypro.company where companyName=? ;`, m.CompanyName) if err != nil { glog.Info(err) } defer Queryconfig.Close() if Queryconfig.Next(){ retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "公司名称重复" retValue.Data = "公司名称重复" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } { stmt, err1 := Db.Prepare(`update proxypro.company set companyName=? where id=?`) glog.Info(err1) res, err2 := stmt.Exec(m.CompanyName, m.CompanyNameID) glog.Info(err2) defer stmt.Close() ret , err3 := res.RowsAffected() glog.Info("RowsAffected: ",ret," ",err3) } //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqSetRedirectUrl struct { RedirectUrl string CompanyNameID int SubcompanyName string Platform int Token string } func SetRedirectUrl(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("SetRedirectUrl recv body:", string(result)) var m reqSetRedirectUrl err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) { stmt, err1 := Db.Prepare(`update proxypro.webConfig set redirectUrl=? where companyNameID=? and subcompany = ?;`) glog.Info(err1) res, err2 := stmt.Exec(m.RedirectUrl, m.CompanyNameID,m.SubcompanyName) glog.Info(err2) defer stmt.Close() ret , err3 := res.RowsAffected() glog.Info("RowsAffected: ",ret," ",err3) } AddVsersion(m.Platform) //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqSetDNS struct { DNS string CompanyNameID int SubcompanyName string Platform int Token string } func SetDNS(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("SetDNS recv body:", string(result)) var m reqSetDNS err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) { stmt, err1 := Db.Prepare(`update proxypro.webConfig set DNS=? where companyNameID=? and subcompany = ?;`) glog.Info(err1) res, err2 := stmt.Exec(m.DNS, m.CompanyNameID,m.SubcompanyName) glog.Info(err2) defer stmt.Close() ret , err3 := res.RowsAffected() glog.Info("RowsAffected: ",ret," ",err3) } AddVsersion(m.Platform) //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } //------------------------------------------------------------------------------------------------- //编辑站点 type reqSetSubcompany struct { Id int64 CompanyNameID int SubcompanyName string SetSubcompanyName string URL string Platform int Token string } func SetSubcompany(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("reqSetSubcompany recv body:", string(result)) var m reqSetSubcompany err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) if m.Id <= 0{ } if m.SubcompanyName == m.SetSubcompanyName{ glog.Info("SetSubcompany: 此时未修改子站点名称") }else{ glog.Info("SetSubcompany: 此时修改子站点名称") } //查询子站点名称重复 var subcompany string var flag bool = false { Queryconfig, err := Db.Query(`SELECT subcompany FROM proxypro.webConfig where companyNameID=? and id != ?;`, m.CompanyNameID, m.Id) if err != nil { glog.Info(err) } defer Queryconfig.Close() for Queryconfig.Next(){ err := Queryconfig.Scan(&subcompany) glog.Info(err) if subcompany == m.SetSubcompanyName{ flag = true break } } } if flag == true{ glog.Info("SetSubcompany: 子站点名称与本公司其他子站点 重复") retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "子站点名称重复" retValue.Data = "子站点名称重复" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return }else{ glog.Info("SetSubcompany: 子站点名称与本公司其他子站点 不重复") } //如果url变了version + 1 { var companyNameID string var subcompany string var URL string { Queryconfig, err := Db.Query(`SELECT companyNameID, subcompany, URL FROM proxypro.webConfig where companyNameID=? and id = ?;`, m.CompanyNameID, m.Id) if err != nil { glog.Info(err) } defer Queryconfig.Close() if Queryconfig.Next(){ err := Queryconfig.Scan(&companyNameID, &subcompany, &URL) glog.Info(err) } } { if URL == m.URL{ }else{ go AddVsersion(m.Platform) } } } //更新缓存 { go SaveWebConfig() go CacheConfigJM() } { stmt, err1 := Db.Prepare(`update proxypro.webConfig set URL=?, subcompany = ? where companyNameID=? and subcompany = ?;`) glog.Info(err1) res, err2 := stmt.Exec(m.URL, m.SetSubcompanyName, m.CompanyNameID,m.SubcompanyName) glog.Info(err2) defer stmt.Close() ret , err3 := res.RowsAffected() glog.Info("RowsAffected: ",ret," ",err3) } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqDelelteCompany struct { CompanyNameID int Token string } func DelelteCompany(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("DelelteSubcompany recv body:", string(result)) var m reqDelelteCompany err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err.Error(), w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) { stmt, err1 := Db.Prepare(`update proxypro.company set estatus=? where id=? ;`) glog.Info(err1) res, err2 := stmt.Exec(0, m.CompanyNameID) glog.Info(err2) defer stmt.Close() ret, err3 := res.RowsAffected() glog.Info("RowsAffected: ", ret, " ", err3) } { stmt, err1 := Db.Prepare(`update proxypro.webConfig set estatus=? where companyNameID=? ;`) glog.Info(err1) res, err2 := stmt.Exec(0, m.CompanyNameID) glog.Info(err2) defer stmt.Close() ret, err3 := res.RowsAffected() glog.Info("RowsAffected: ", ret, " ", err3) } // version_code 需要加1  { AddVsersion(-1) } //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqDelelteSubcompany struct { CompanyNameID int SubcompanyName string Token string } func DelelteSubcompany(w http.ResponseWriter, req *http.Request) { fmt.Println("--------DelelteSubcompany start----------") if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("DelelteSubcompany recv body:", string(result)) var m reqDelelteSubcompany err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) var flag bool = false { Queryconfig, err := Db.Query(`SELECT redirectUrl,DNS FROM proxypro.webConfig where companyNameID=? and subcompany=?;`, m.CompanyNameID, m.SubcompanyName) if err != nil { glog.Info(err) } defer Queryconfig.Close() for Queryconfig.Next(){ var redirectUrl string var DNS string err := Queryconfig.Scan(&redirectUrl,&DNS) fmt.Println("redirectUrl,DNS:",redirectUrl,DNS) glog.Info(err) if redirectUrl == "0" && DNS==""{ flag = true //break } // version_code 需要加1  如果 redirectUrl =0 和 DNS 是都空的,则不用 version+1,其他情况 +1 if flag==false { fmt.Println("------DelelteSubcompany----AddVsersion(-1)-----------") go AddVsersion(-1) } } } { stmt, err1 := Db.Prepare(`update proxypro.webConfig set estatus= ? where companyNameID=? and subcompany=?;`) glog.Info(err1) res, err2 := stmt.Exec(0, m.CompanyNameID, m.SubcompanyName) glog.Info(err2) defer stmt.Close() ret, err3 := res.RowsAffected() glog.Info("RowsAffected: ", ret, " ", err3) } //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqAddCompany struct { CompanyName string Token string } func AddCompany(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("reqAddCompany recv body:", string(result)) var m reqAddCompany err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid, err_token = CheckToken(m.Token, w, req) if err_token != nil { retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) if len(m.CompanyName) == 0 { retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "CompanyName null" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } //查询公司名称重复 { Queryconfig, err := Db.Query(`SELECT companyName FROM proxypro.company where companyName=? and estatus=1;`, m.CompanyName) if err != nil { glog.Info(err) } defer Queryconfig.Close() if Queryconfig.Next(){ retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "公司名称重复" retValue.Data = "公司名称重复" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } { stmt, err := Db.Prepare(`INSERT INTO proxypro.company (companyName) values (?)`) res, err := stmt.Exec(m.CompanyName) glog.Info("res", res) if err != nil { glog.Info(res) glog.Info(err) return } stmt.Close() } //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } } type reqAddSubCompany struct { CompanyNameID int Subcompany string URL string Token string } func AddSubCompany(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { result, _ := ioutil.ReadAll(req.Body) req.Body.Close() glog.Info("reqAddSubCompany recv body:", string(result)) var m reqAddSubCompany err := json.Unmarshal([]byte(result), &m) if err != nil { glog.Info(err) retError(err, w) return } var user_uuid string var err_token error { user_uuid,err_token = CheckToken(m.Token,w, req) if err_token != nil{ retValue := NewBaseJsonData() retValue.Code = 1000 retValue.Message = err_token.Error() retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } glog.Info("user_uuid: ", user_uuid) if m.CompanyNameID == 0 || len(m.Subcompany) == 0 || len(m.URL) == 0{ retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "Subcompany or URL null" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } //查询子站点名称重复 { Queryconfig, err := Db.Query(`SELECT companyNameID, subcompany FROM proxypro.webConfig where companyNameID=? and subcompany = ? and estatus=1;`, m.CompanyNameID, m.Subcompany) if err != nil { glog.Info(err) } defer Queryconfig.Close() if Queryconfig.Next(){ retValue := &ResponseData{} retValue.Success = false retValue.Code = 300 retValue.Message = "子站点名称重复" retValue.Data = "子站点名称重复" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) return } } { stmt, err := Db.Prepare(`INSERT INTO proxypro.webConfig (companyNameID,subcompany,URL,redirectUrl) values (?,?,?,?)`) res, err := stmt.Exec(m.CompanyNameID, m.Subcompany, m.URL,0) glog.Info("res",res) if err!=nil { glog.Info(res) glog.Info(err) return } stmt.Close() } //取消version+1 //// version_code 需要加1  //{ // AddVsersion(-1) // //} //更新缓存 { go SaveWebConfig() go CacheConfigJM() } retValue := &ResponseData{} retValue.Success = true retValue.Code = 200 retValue.Message = "Success" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) }else { retValue := &ResponseData{} retValue.Success = false retValue.Code = 0 retValue.Message = "Request Method error: POST" retValue.Data = "" bytes, _ := json.Marshal(retValue) w.Write([]byte(bytes)) } }
package main import ( "fmt" "net" "os" ) var ErrorCode = 1 //监听的端口 && 地址 var ServerPort = ":1212" var LocalHost = "127.0.0.1" var op = map[string]string{ "登录": "add", "显示在线人数": "show", } func CheckError(err error) { if err != nil { fmt.Println(err) os.Exit(ErrorCode) } } func getMessage(udpListener *net.UDPConn) { for { var buff = make([]byte, 128) readLen, _, err := udpListener.ReadFromUDP(buff) CheckError(err) if readLen > 0 { fmt.Println(string(buff[:readLen])) } } } func main() { udpAddr, err := net.ResolveUDPAddr("udp", LocalHost+ServerPort) CheckError(err) udpConn, err := net.DialUDP("udp", nil, udpAddr) CheckError(err) udpListener, err := net.ListenUDP("udp", udpAddr) CheckError(err) defer udpConn.Close() defer udpListener.Close() name := "" fmt.Println("please enter your name") fmt.Scanf("%s", &name) udpConn.Write([]byte(op["登录"] + name)) go getMessage(udpListener) for { opp := "" fmt.Scanf("%s", &opp) if opp == "show" { udpConn.Write([]byte(op["显示在线人数"])) } else { request := "" fmt.Scan(request) udpConn.Write([]byte(request)) } } }
package main import "testing" func TestP19(t *testing.T) { v := countWeekday(1901, 2000, 0) out := 171 if v != out { t.Errorf("P19: %v\tExpected: %v", v, out) } }
package web import ( "ChangeInspector/logservice" "ChangeInspector/sorter" "encoding/json" "net/http" "net/url" "strconv" "github.com/gorilla/mux" ) /*SortHandler ...*/ type SortHandler struct { logService *logservice.LogService } func getResult(query url.Values, result sorter.GoogleChartBarResult) sorter.GoogleChartBarResult { takeParam, ok := query["take"] if ok { take, _ := strconv.Atoi(takeParam[0]) length := len(result) if length < take { take = length } return result[:take] } return result } func (handler SortHandler) register(router *mux.Router) { router.HandleFunc("/sort/commits", func(w http.ResponseWriter, r *http.Request) { result := handler.logService.SortableLogs.SortBy(sorter.ByCommits{}) query := r.URL.Query() json.NewEncoder(w).Encode(getResult(query, result)) }) router.HandleFunc("/sort/changes", func(w http.ResponseWriter, r *http.Request) { result := handler.logService.SortableLogs.SortBy(sorter.ByChanges{}) query := r.URL.Query() json.NewEncoder(w).Encode(getResult(query, result)) }) }
package entities import "github.com/jinzhu/gorm" // Project entity type Project struct { gorm.Model UserID uint User User `json:"user"` Description string `json:"description"` Tasks []Task `json:"tasks"` }
/* * @lc app=leetcode.cn id=16 lang=golang * * [16] 最接近的三数之和 */ // @lc code=start package main import "fmt" import "math" func main() { var a []int var target int // a = []int{-1,2,1,-4} // target = 1 // fmt.Printf("%v, %d, %d\n", a, target, threeSumClosest(a, target)) a = []int{1,2,4,8,16,32,64,128} target = 82 fmt.Printf("%v, %d, %d\n", a, target, threeSumClosest(a, target)) } func threeSumClosest(nums []int, target int) int { n := len(nums) min := math.MaxInt64 var mostApproach int for first := 0 ; first < n - 2 ; first++ { for second := first + 1 ; second < n - 1; second++ { third := n - 1 fmt.Printf("11111: %d, %d, %d\n", first, second, third) for third > second { sum := nums[third] + nums[first] + nums[second] distance := getDistance(sum, target) fmt.Printf("%d, %d, %d, sum is %d, target is %d, distance is %d \n", first, second ,third, sum, target, distance) if distance == 0 { fmt.Printf("1: %d, %d, %d\n", first, second, third) return sum } else if distance < min { fmt.Printf("2: %d, %d, %d, min is %d\n", first, second, third, distance) min = distance mostApproach = sum } third-- } } } return mostApproach } // @lc code=end func getDistance(a, b int) int { return abs(a - b ) } func abs(a int) int { if a < 0 { return (-1) * a } else { return a } }
package pipe import ( "bytes" "crypto/sha256" "errors" "fmt" "io" "math" "net" "strings" "sync/atomic" "syscall" "time" "github.com/iberryful/sproxy/pkg/log" "github.com/iberryful/sproxy/pkg/socks" ) const bufSize int = 16 * 1024 const HeaderLen int = 4 const MagicLen int = 4 const MaxLen = bufSize - HeaderLen - MagicLen var Magic = []byte{0xff, 0x86, 0x13, 0x85} const ( CmdClose = iota //0 CmdConn //1 CmdTrans //2 CmdPing //3 CmdErr //4 ) const ( Idle = iota // 0 InUse // 1 Interrupted // 2 Closed // 3 ) var ErrInterrupted = errors.New("pipe interrupted") var ErrPipe = errors.New("pipe closed") var scn uint32 = 0 type Pipe struct { conn net.Conn state int64 readBuf []byte writeBuf []byte n int lastActive time.Time timeout time.Duration id uint32 term uint8 } func New(conn net.Conn, timeout time.Duration) *Pipe { p := &Pipe{ conn: conn, state: Idle, readBuf: make([]byte, bufSize), writeBuf: make([]byte, bufSize), timeout: timeout, lastActive: time.Now(), id: atomic.AddUint32(&scn, 1), } copy(p.writeBuf, Magic) return p } func (p *Pipe) checkMagic() error { _, err := io.ReadFull(p.conn, p.readBuf[:len(Magic)]) if err != nil { return err } if !bytes.Equal(Magic, p.readBuf[:len(Magic)]) { return fmt.Errorf("invalid magic, %x", p.readBuf[:len(Magic)]) } return nil } func (p *Pipe) interruptLocal() bool { return atomic.CompareAndSwapInt64(&p.state, InUse, Interrupted) } func (p *Pipe) setDeadLine() { t := time.Time{} if p.timeout != time.Duration(0) { t = time.Now().Add(p.timeout) } //log.Printf("%s set deadline %s", p, t) p.conn.SetDeadline(t) } func (p *Pipe) String() string { return fmt.Sprintf("pid %04x, T%d", p.id&0xffff, p.term) } func (p *Pipe) Close() error { if p.state == Closed { return nil } p.setState(Closed) return p.conn.Close() } func (p *Pipe) setState(state int64) { atomic.StoreInt64(&p.state, state) } func (p *Pipe) reset() error { p.setDeadLine() p.term += 1 p.setState(Idle) return nil } func (p *Pipe) Read(b []byte) (n int, err error) { // not in progress p.setDeadLine() for p.n == 0 { err := p.checkMagic() if err != nil { return 0, err } _, err = io.ReadFull(p.conn, p.readBuf[:4]) if err != nil { return 0, err } cmd, term, length := p.readBuf[0], p.readBuf[1], int(p.readBuf[2])*256+int(p.readBuf[3]) if cmd < CmdErr && term != p.term { if length > 0 { _, err = io.ReadFull(p.conn, p.readBuf[4:]) if err != nil { return 0, err } } log.Warnf("[%s] ignore frame, term: %d, cmd: %d", p, term, cmd) continue } switch cmd { case CmdClose: return 0, ErrInterrupted case CmdConn: _, err = io.ReadFull(p.conn, p.readBuf[4:4+length]) if err != nil { return 0, err } copy(b, p.readBuf[:4+length]) return 4 + length, nil case CmdTrans: p.n = length case CmdPing: continue default: err := fmt.Errorf("[%s] unknown cmd: %d", p, cmd) log.Error(err) return 0, err } } nBytes := min(len(b), p.n) n, err = p.conn.Read(b[:nBytes]) p.n -= n return n, err } func (p *Pipe) Write(b []byte) (n int, err error) { p.setDeadLine() n = len(b) m := len(Magic) pos := 0 for n > 0 { nBytes := min(n, MaxLen) copy(p.writeBuf[m:], []byte{CmdTrans, p.term, byte(nBytes >> 8), byte(nBytes % 256)}) copy(p.writeBuf[m+4:], b[pos:pos+nBytes]) if _, err = p.conn.Write(p.writeBuf[:m+4+nBytes]); err != nil { return 0, err } pos += nBytes n -= nBytes } return len(b), nil } // reading from p to conn func (p *Pipe) readLoop(conn net.Conn) error { _, err := io.Copy(conn, p) // p read closed, should close p if !IsInterrupted(err) { log.Debugf("[%s] [readLoop] [pipe close] %s", p, err) conn.Close() return ErrPipe } // no new data from p, won't write any data to conn log.Debugf("[%s] [readLoop] interrupted by remote", p) conn.SetDeadline(time.Now()) conn.(*net.TCPConn).CloseWrite() //log.Printf("%s read loop error: %s", p, err) return nil } // reading from conn to pipe func (p *Pipe) writeLoop(conn net.Conn) error { _, err := io.Copy(p, conn) if p.IsPipeErr(err) { conn.Close() return err } if p.interruptLocal() { if err := p.TryInterruptRemote(); err != nil { return err } } // no new data for p, sent interrupt to remote, won't read from conn if err == nil || IsReadError(err) { log.Debugf("[%s] [writeLoop] interrupted by local", p) // Normally, remote should send FIN signal, setting deadline here is just to make sure the read loop can exit. p.conn.SetDeadline(time.Now().Add(1 * time.Second)) conn.(*net.TCPConn).CloseRead() return nil } return err } func (p *Pipe) Bind(conn net.Conn) error { var readLoopErr, writeLoopErr error ch := make(chan error, 1) defer close(ch) defer conn.Close() go func() { err := p.readLoop(conn) log.Debugf("[%s] [readLoop] exited, %v", p, err) ch <- err }() writeLoopErr = p.writeLoop(conn) log.Debugf("[%s] [writeLoop] exited, %v", p, writeLoopErr) readLoopErr = <-ch if p.IsPipeErr(readLoopErr) || p.IsPipeErr(writeLoopErr) { return ErrPipe } return p.reset() } func (p *Pipe) HandShake(addr socks.Addr, secret string) error { p.setState(InUse) buf := make([]byte, 1024) addrLen := len(addr) headerLen := addrLen + 32 n := 4 + addrLen buf[0] = CmdConn buf[1] = p.term buf[2] = uint8(headerLen >> 8) buf[3] = uint8(headerLen % 256) copy(buf[4:], addr) hmac := sha256.Sum256(append(buf[:n], []byte(secret)...)) copy(buf[n:], hmac[:]) return p.writeCmd(buf[:n+32]) } func (p *Pipe) WaitForHandShake(secret string) (socks.Addr, error) { p.setState(InUse) buf := make([]byte, 1024) var err error n, err := p.Read(buf) if err != nil || n < 4 { return socks.Addr{}, err } if buf[0] != CmdConn { return socks.Addr{}, fmt.Errorf("invalid handshake cmd: %d", buf[0]) } length := 256*int(buf[2]) + int(buf[3]) // n is the frame header without hmac n = 4 + length - 32 msg := make([]byte, n+len(secret)) copy(msg[:n], buf[:n]) copy(msg[n:n+len(secret)], secret) hmac := sha256.Sum256(msg) if !bytes.Equal(hmac[:], buf[n:n+32]) { return socks.Addr{}, fmt.Errorf("invalid handshake hmac, expect %x, got %x", hmac, buf[n:n+32]) } return buf[4:n], nil } func (p *Pipe) TryInterruptRemote() error { err := p.writeCmd([]byte{CmdClose, p.term, 0, 0}) if err != nil { return err } log.Debugf("[%s] interrupt sent to remote", p) return nil } func (p *Pipe) TryPing() error { return p.writeCmd([]byte{CmdPing, p.term, 0, 0}) } func (p *Pipe) writeCmd(b []byte) error { m := len(Magic) buf := make([]byte, m+len(b)) copy(buf[:m], Magic) copy(buf[m:], b) _, err := p.conn.Write(buf) return err } func min(nums ...int) int { n := math.MaxInt64 for _, num := range nums { if num < n { n = num } } return n } func max(nums ...int) int { n := math.MinInt64 for _, num := range nums { if num > n { n = num } } return n } func (p *Pipe) IsPipeErr(err error) bool { if err == nil { return false } if e, ok := err.(*net.OpError); ok { addr := p.conn.LocalAddr().String() return e != nil && (addr == e.Source.String() || addr == e.Addr.String()) } return strings.ContainsAny(err.Error(), ErrPipe.Error()) } func IsWriteError(err error) bool { if e, ok := err.(*net.OpError); ok { if e.Op != "write" { return false } } return errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) } func IsReadError(err error) bool { if e, ok := err.(*net.OpError); ok { return e.Op == "read" } return false } func IsTimeoutError(err error) bool { if e, ok := err.(net.Error); ok { return e.Timeout() } return false } func IsReadFinish(err error) bool { return err == nil || err == io.EOF } func IsInterrupted(err error) bool { if e, ok := err.(*net.OpError); ok { return e.Err.Error() == ErrInterrupted.Error() } return false }
package handler import ( "context" "path/filepath" "testing" "github.com/jinmukeji/jiujiantang-services/service/auth" corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // UserSigninTestSuite 是用户登录的单元测试的 Test Suite type UserSigninTestSuite struct { suite.Suite jinmuHealth *JinmuHealth Account *Account } // SetupSuite 设置测试环境 func (suite *UserSigninTestSuite) SetupSuite() { envFilepath := filepath.Join("testdata", "local.svc-biz-core.env") db, _ := newTestingDbClientFromEnvFile(envFilepath) suite.Account = newTestingAccountFromEnvFile(envFilepath) suite.jinmuHealth = NewJinmuHealth(db, nil, nil, nil, nil, nil, nil, "") } // TestUserSiginin 测试用户登录 func (suite *UserSigninTestSuite) TestUserSignin() { t := suite.T() ctx := context.Background() ctx = mockAuth(ctx, suite.Account.clientID, suite.Account.name, suite.Account.zone) const registerType = "username" _, errMockSignin := mockSignin(ctx, suite.jinmuHealth, suite.Account.userName, suite.Account.passwordHash, registerType, corepb.SignInMethod_SIGN_IN_METHOD_GENERAL) assert.NoError(t, errMockSignin) } // TestUserSigninTestSuite 运行测试 func TestUserSigninTestSuite(t *testing.T) { suite.Run(t, new(UserSigninTestSuite)) } // mockSignin 模拟登录 func mockSignin(ctx context.Context, j *JinmuHealth, username string, passwordHash string, registerType string, signInMethod corepb.SignInMethod) (context.Context, error) { resp, err := j.jinmuidSvc.UserSignInByUsernamePassword(ctx, &jinmuidpb.UserSignInByUsernamePasswordRequest{ Username: username, HashedPassword: passwordHash, Seed: "", SignInMachine: "", }) if err != nil { return nil, err } return auth.AddContextToken(ctx, resp.AccessToken), nil }
package game_map import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/tilepix" "log" "sort" ) type ExploreState struct { Stack *gui.StateStack MapDef *tilepix.Map Map *GameMap Hero *Character win *pixelgl.Window startPos pixel.Vec heroVisible bool FollowCam bool FollowChar *Character ManualCamX, ManualCamY float64 } func ExploreStateCreate(stack *gui.StateStack, mapInfo MapInfo, win *pixelgl.Window) ExploreState { es := ExploreState{ win: win, Stack: stack, MapDef: mapInfo.Tilemap, heroVisible: true, } es.Map = MapCreate(mapInfo) es.Hero = Characters["hero"](es.Map) es.Map.NPCbyId[es.Hero.Id] = es.Hero es.FollowCam = true es.FollowChar = es.Hero es.startPos = pixel.V(es.Hero.Entity.TileX, es.Hero.Entity.TileY) es.Map.GoToTile(es.startPos.X, es.startPos.Y) return es } func (es *ExploreState) SetManualCam(tileX, tileY float64) { es.ManualCamX, es.ManualCamY = tileX, tileY es.FollowCam = false } func (es *ExploreState) UpdateCamera(gMap *GameMap) { var tileX, tileY float64 if es.FollowCam { tileX, tileY = es.FollowChar.Entity.TileX, es.FollowChar.Entity.TileY } else { tileX, tileY = es.ManualCamX, es.ManualCamY } gMap.GoToTile(tileX, tileY) } func (es *ExploreState) SetFollowCam(shouldFollow bool, char *Character) { es.FollowCam = shouldFollow es.FollowChar = char if !es.FollowCam { x, y := es.FollowChar.Entity.TileX, es.FollowChar.Entity.TileY es.ManualCamX = x es.ManualCamY = y } } func (es *ExploreState) HideHero() { es.heroVisible = false es.Hero.Entity.TileX = 0 es.Hero.Entity.TileY = 0 } func (es *ExploreState) ShowHero(tileX, tileY float64) { es.heroVisible = true es.Hero.Entity.TileX = tileX es.Hero.Entity.TileY = tileY es.Map.GoToTile(es.Hero.Entity.TileX, es.Hero.Entity.TileY) } func (es ExploreState) Enter() { } func (es ExploreState) Exit() { } func (es *ExploreState) Update(dt float64) bool { // Update the camera according to player position es.UpdateCamera(es.Map) gameCharacters := append([]*Character{es.Hero}, es.Map.NPCs...) for _, gCharacter := range gameCharacters { gCharacter.Controller.Update(dt) } return true } func (es ExploreState) Render(win *pixelgl.Window) { //Map & Characters err := es.Map.DrawAfter(win, func(canvas *pixelgl.Canvas, layer int) { var gameCharacters []*Character gameCharacters = append(gameCharacters, es.Map.NPCs...) if es.heroVisible { gameCharacters = append([]*Character{es.Hero}, gameCharacters...) } //sort players as per visible to screen Y position sort.Slice(gameCharacters[:], func(i, j int) bool { return gameCharacters[i].Entity.TileY < gameCharacters[j].Entity.TileY }) if layer == es.Map.MapInfo.CollisionLayer { for _, gCharacter := range gameCharacters { //gCharacter.Entity.TeleportAndDraw(es.Map, canvas) //probably can remove now gCharacter.Entity.Render(es.Map, canvas, pixel.ZV) } } }) if err != nil { log.Fatal(err) } //Camera camPos := pixel.V(es.Map.CamX, es.Map.CamY) cam := pixel.IM.Scaled(camPos, 1.0).Moved(es.win.Bounds().Center().Sub(camPos)) win.SetMatrix(cam) } func (es ExploreState) HandleInput(win *pixelgl.Window) { //use key KeyE if win.JustPressed(pixelgl.KeySpace) { // which way is the player facing? //tileX, tileY := es.Map.GetTileIndex(es.Hero.GetFacedTileCoords()) tileX, tileY := es.Hero.GetFacedTileCoords() trigger := es.Map.GetTrigger(tileX, tileY) if trigger.OnUse != nil { trigger.OnUse(es.Map, es.Hero.Entity, tileX, tileY) } } if win.JustPressed(pixelgl.KeyLeftAlt) { menu := InGameMenuStateCreate(es.Stack, win) es.Stack.Push(menu) } } func (es *ExploreState) AddNPC(NPC *Character) { es.Map.AddNPC(NPC) }
package models import "time" type Comment struct { CommentID int `json:"comment_id"` ArticleID int `json:"article_id"` Message string `json:"message"` CreatedAt time.Time `json:"created_at"` } type Article struct { ID int `json:"article_id"` Title string `json:"title"` Contents string `json:"contents"` UserName string `json:"user_name"` NiceNum int `json:"nice"` CommentList []Comment `json:"comments"` CreatedAt time.Time `json:"created_at"` }
package veriserviceserver import ( "fmt" "io/ioutil" "log" "os" "os/signal" "strings" "syscall" "github.com/bgokden/veri/node" "github.com/bgokden/veri/state" ) func RunServer(configMap map[string]interface{}) { state.Health = true state.Ready = false services := configMap["services"].(string) log.Printf("Services: %v\n", services) port := configMap["port"].(int) // evictable := configMap["evictable"].(bool) // tls := configMap["tls"].(bool) // certFile := configMap["cert"].(string) // keyFile := configMap["key"].(string) // // memory := configMap["memory"].(uint64) // lis, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)) // if err != nil { // log.Printf("failed to listen: %v", err) // return // } // var opts []grpc.ServerOption // if tls { // if certFile == "" { // certFile = testdata.Path("server1.pem") // } // if keyFile == "" { // keyFile = testdata.Path("server1.key") // } // creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) // if err != nil { // log.Printf("Failed to generate credentials %v", err) // return // } // opts = []grpc.ServerOption{grpc.Creds(creds)} // } // grpcServer := grpc.NewServer(opts...) directory := configMap["directory"].(string) if len(directory) == 0 { var err error directory, err = ioutil.TempDir("", "node") if err != nil { log.Fatal(err) } } os.MkdirAll(directory, os.ModePerm) defer os.RemoveAll(directory) broadcast := configMap["broadcast"].(string) broadcastAddresses := make([]string, 0) if len(broadcast) > 0 { broadcastAddresses = append(broadcastAddresses, strings.Split(broadcast, ",")...) } for i, address := range broadcastAddresses { if !strings.Contains(address, ":") { broadcastAddresses[i] = fmt.Sprintf("%v:%v", address, port) } } serviceList := make([]string, 0) if len(services) > 0 { serviceList = append(serviceList, strings.Split(services, ",")...) } nodeConfig := &node.NodeConfig{ Port: uint32(port), Folder: directory, AdvertisedIds: broadcastAddresses, ServiceList: serviceList, } s := node.NewNode(nodeConfig) // pb.RegisterVeriServiceServer(grpcServer, s) go RestApi() go func() { sigint := make(chan os.Signal, 1) // interrupt signal sent from terminal signal.Notify(sigint, os.Interrupt) // sigterm signal sent from orchastrator signal.Notify(sigint, syscall.SIGTERM) <-sigint log.Printf("Closing services started.") // Cleap up here s.Close() os.Exit(0) }() log.Printf("Server started.") // grpcServer.Serve(lis) s.Listen() }
package inc import ( "testing" "time" ) func Test_Caller_1(t *testing.T) { // single args today := Caller("date", "+%F_%T") if today != "" { t.Log(today) } else { t.Error("Single_Args: calller return empty") return } // multi args with space temp := "/etc/passwd /etc/services" ls := Caller("/bin/ls", temp) if ls != "" { t.Log(ls) } else { t.Error("Space_Args: caller return empty") return } } // test run by go func Test_Caller_2(t *testing.T) { c := make(chan string) tmout := make(chan bool, 1) go func() { time.Sleep(3 * time.Second) tmout <- true }() go runCallerbyGo(c, "date", "+%F_%T") select { case output := <-c: t.Log("goroutine return:", output) if output == "" { t.Error("goroutine return empty") return } case <-tmout: t.Error("timeout") return } } func runCallerbyGo(c chan string, cmd, args string) { output := Caller(cmd, args) c <- output } func Test_Caller_3(t *testing.T) { for k, v := range Checker { t.Log(k, v) } }
package main import "fmt" func main() { a := [5]string{"1", "2", "3", "4", "5"} slice_a := a[1:3] b := [5]string{"one", "two", "three", "four", "five"} slice_b := b[1:3] fmt.Println("Slice_a:", slice_a) fmt.Println("Slice_b:", slice_b) fmt.Println("Length of slice_a:", len(slice_a)) fmt.Println("Length of slice_b:", len(slice_b)) slice_a = append(slice_a, slice_b...) // appending slice fmt.Println("New Slice_a after appending slice_b :", slice_a) slice_a = append(slice_a, "text1") // appending value fmt.Println("New Slice_a after appending text1 :", slice_a) }
package controllers import ( "encoding/json" "github.com/go-errors/errors" "github.com/revel/revel" "gopkg.in/mgo.v2/bson" "topazdev/stocks-game-api/app/models" ) type LobbyController struct { BaseController } func (c LobbyController) Index() revel.Result { var ( lobbys []models.Lobby err error ) lobbys, err = models.GetLobbys() if err != nil { errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } c.Response.Status = 200 return c.RenderJSON(lobbys) } func (c LobbyController) Show(id string) revel.Result { var ( lobby models.Lobby err error lobbyID bson.ObjectId ) if id == "" { errResp := BuildErrResponse(errors.New("Invalid lobby id format"), "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobbyID, err = ConvertToObjectIDHex(id) if err != nil { errResp := BuildErrResponse(errors.New("Invalid lobby id format"), "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobby, err = models.GetLobby(lobbyID) if err != nil { errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } c.Response.Status = 200 return c.RenderJSON(lobby) } func (c LobbyController) Create() revel.Result { var ( lobby models.Lobby err error ) err = json.NewDecoder(c.Request.Body).Decode(&lobby) if err != nil { err = errors.New(err) errResp := BuildErrResponse(err, "403") c.Response.Status = 403 return c.RenderJSON(errResp) } currentUser := c.CurrentUser() lobby.UserID = currentUser.ID lobby.UserIDs = append(lobby.UserIDs, currentUser.ID) lobby, err = models.AddLobby(lobby) if err != nil { err = errors.New(err) errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } c.Response.Status = 201 return c.RenderJSON(lobby) } func (c LobbyController) Update() revel.Result { var ( lobby models.Lobby err error ) err = json.NewDecoder(c.Request.Body).Decode(&lobby) if err != nil { errResp := BuildErrResponse(err, "400") c.Response.Status = 400 return c.RenderJSON(errResp) } err = lobby.UpdateLobby() if err != nil { errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } return c.RenderJSON(lobby) } func (c LobbyController) Delete(id string) revel.Result { var ( err error lobby models.Lobby lobbyID bson.ObjectId ) if id == "" { errResp := BuildErrResponse(errors.New("Invalid lobby id format"), "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobbyID, err = ConvertToObjectIDHex(id) if err != nil { errResp := BuildErrResponse(errors.New("Invalid lobby id format"), "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobby, err = models.GetLobby(lobbyID) if err != nil { errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } err = lobby.DeleteLobby() if err != nil { errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } c.Response.Status = 204 return c.RenderJSON(nil) } func (c LobbyController) Start(id string) revel.Result { var ( lobby models.Lobby err error ) lobbyID, err := ConvertToObjectIDHex(id) if err != nil { err = errors.New(err) errResp := BuildErrResponse(err, "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobby, err = models.GetLobby(lobbyID) if err != nil { err = errors.New(err) errResp := BuildErrResponse(err, "400") c.Response.Status = 400 return c.RenderJSON(errResp) } lobby.Closed = true err = lobby.UpdateLobby() if err != nil { err = errors.New(err) errResp := BuildErrResponse(err, "500") c.Response.Status = 500 return c.RenderJSON(errResp) } game := models.StartNewGame(c.CurrentUser(), lobby) return c.RenderJSON(lobby) }
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package version import "runtime" // IsMobile reports whether this is a mobile client build. func IsMobile() bool { // Good enough heuristic for now, at least until Apple makes // ARM laptops... return runtime.GOOS == "android" || (runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) } // OS returns runtime.GOOS, except instead of returning "darwin" it // returns "iOS" or "macOS". func OS() string { if runtime.GOOS == "darwin" { if IsMobile() { return "iOS" } return "macOS" } return runtime.GOOS }
package shell import ( "testing" "github.com/stretchr/testify/assert" ) func TestVersionNameShouldReturnVersion(t *testing.T) { assert.Equal(t, "version", version(0).name()) } func TestVersionsDescriptionShouldNotBeEmpty(t *testing.T) { assert.NotEqual(t, "", version(0).description()) } func TestVersionUsageShouldNotBeEmpty(t *testing.T) { assert.NotEqual(t, "", version(0).usage()) } func TestVersionRunShouldReturnNil(t *testing.T) { assert.Nil(t, version(0).run(nil, nil)) } func TestVersionShouldRegisterItself(t *testing.T) { _, ok := allCommands[version(0).name()] assert.True(t, ok) }
package controllers import "github.com/revel/revel" //questions type QuestionController struct { *revel.Controller } func(c *QuestionController) Index() revel.Result{ return c.RenderText("Hello") }
package mutexcache_test import ( "github.com/jalavosus/mutexcache-go" "testing" "time" ) var ( defaultExpiration = 30 * time.Second testKeyA = "test_key_a" testKeyB = "test_key_b" ) // Test creation and retrieval of a single *sync.Mutex func TestSingle(t *testing.T) { mutexCache := mutexcache.New(defaultExpiration) mut := mutexCache.Get(testKeyA) if mut == nil { t.Fail() } // Ensure that the mutex pointer is actually being stored, // and not recreated on subsequent calls. sameMut := mutexCache.Get(testKeyA) if sameMut == nil { t.Fail() } if sameMut != mut { t.Fail() } } // Tests storage and retrieval of multiple *sync.Mutexes func TestMulti(t *testing.T) { mutexCache := mutexcache.New(defaultExpiration) mutA := mutexCache.Get(testKeyA) if mutA == nil { t.Fail() } mutB := mutexCache.Get(testKeyB) if mutB == nil { t.Fail() } // Ensure that the cache isn't returning // the same mutex for some reason. if mutA == mutB { t.Fail() } } // Tests cache expiration. func TestExpiration(t *testing.T) { mutexCache := mutexcache.New(defaultExpiration) mut := mutexCache.Get(testKeyA) // wait for the mutex to expire and the // internal cache to prune it time.Sleep(31 * time.Second) newMut := mutexCache.Get(testKeyA) if newMut == mut { t.Fail() } }
package client import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "net/url" "sync" "time" "github.com/dkorittki/loago/pkg/api/v1" "github.com/dkorittki/loago/pkg/instructor/config" "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils" "github.com/rs/zerolog" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) // AuthSchemeBasic is used as the authentication method description. const AuthSchemeBasic = "basic" type Result struct { URL *url.URL HttpStatusCode int HttpStatusMessage string Ttfb time.Duration Cached bool } // Worker represents the configuration and connection of a Worker. type Worker struct { Adress string Port int Certificate *tls.Certificate Secret string dialer func(context.Context, string) (net.Conn, error) connection *grpc.ClientConn } func (w *Worker) String() string { return fmt.Sprintf("%s:%d", w.Adress, w.Port) } // Client is a instructor client. type Client struct { Workers []*Worker certPool *x509.CertPool activeRequests uint } // NewClient returns a new client. func NewClient() *Client { var client Client client.certPool = x509.NewCertPool() return &client } // AddWorker adds a new worker to the client. // A worker is defined by it's connection attributes, // which are it's ip address, port, a token secret, // a TLS certificate, and an optional dialer function, which mainly serves // for testing purposes. func (c *Client) AddWorker( adress string, port int, secret string, cert *tls.Certificate, dialer func(context.Context, string) (net.Conn, error)) error { var w Worker w.Adress = adress w.Port = port w.Secret = secret w.Certificate = cert w.dialer = dialer if cert != nil { for _, byteCert := range w.Certificate.Certificate { if !c.certPool.AppendCertsFromPEM(byteCert) { return &CertificateDecodeError{} } } } c.Workers = append(c.Workers, &w) return nil } // Connect opens a connection to every worker added to this client. // It closes existing connections first, then creates a new one. func (c *Client) Connect(ctx context.Context, logger *zerolog.Logger) error { err := c.Disconnect() if err != nil { return err } for _, w := range c.Workers { w.connection, err = connect(ctx, w, c.certPool) if err != nil { _ = c.Disconnect() return &ConnectError{err} } } return nil } // Disconnect closes connections to all workers belonging to this client. func (c *Client) Disconnect() error { for _, w := range c.Workers { if w.connection != nil { err := w.connection.Close() w.connection = nil if err != nil { return &DisconnectError{err} } } } return nil } // Ping serially pings every Worker. func (c *Client) Ping(ctx context.Context, logger *zerolog.Logger) error { for _, w := range c.Workers { if w.connection == nil { return &InvalidConnectionError{Err: errors.New("no connection present to worker")} } ctx = ctxWithSecret(ctx, AuthSchemeBasic, w.Secret) client := api.NewWorkerClient(w.connection) res, err := client.Ping(ctx, &api.PingRequest{}) if err != nil { return err } logger.Info(). Str("response", res.Message). Str("worker", w.String()). Msg("ping succeeded") } return nil } // Run requests every worker to perform a loadtest. // It returns an error on failure to initialize the // requests, otherwise it returns a channel in which // the results will be written, but returns immediately. // // logger will be used to log messages mid-process, // endpoints are the endpoints which workers will target to, // amount specifies the amount of users each worker simulates, // minWaitTime and maxWaitTime specify the time to wait between // requests in milliseconds. // // To cancel requesting the workers, ctx has to be canceled. func (c *Client) Run( ctx context.Context, logger *zerolog.Logger, endpoints []*config.InstructorEndpoint, amount, minWaitTime, maxWaitTime int) (chan Result, error) { results := make(chan Result, 1024) wg := &sync.WaitGroup{} // wait in a seperate go-routine for // every request go-routine and close the result channel, // once there is no more request go-routine left wg.Add(len(c.Workers)) go func() { wg.Wait() logger.Debug().Msg("subroutines finished requesting, closing result channel") close(results) }() for _, w := range c.Workers { ctx = ctxWithSecret(ctx, AuthSchemeBasic, w.Secret) client := api.NewWorkerClient(w.connection) req := createRunRequest(endpoints, amount, minWaitTime, maxWaitTime) workerName := w.String() // starting a new request go-routine go func() { stream, err := client.Run(ctx, req) if err != nil { logger.Error(). Err(err). Str("worker", workerName). Msg("error while awaiting response from worker") wg.Done() return } for { resp, err := stream.Recv() if err != nil { var msg string if err == io.EOF { msg = "connection closed by worker" } else { msg = "unexpected error by worker" } logger.Error(). Err(err). Str("worker", workerName). Msg(msg) wg.Done() return } r, err := createResult(resp) if err != nil { logger.Error(). Err(err). Str("worker", workerName). Msg("cannot decode response from worker") wg.Done() return } results <- *r } }() } return results, nil } func createRunRequest(e []*config.InstructorEndpoint, amount, minWait, maxWait int) *api.RunRequest { req := api.RunRequest{ Amount: uint32(amount), MinWaitTime: uint32(minWait), MaxWaitTime: uint32(maxWait), Type: api.RunRequest_CHROME, } for _, v := range e { req.Endpoints = append(req.Endpoints, &api.RunRequest_Endpoint{Url: v.Url, Weight: uint32(v.Weight)}) } return &req } func createResult(res *api.EndpointResult) (*Result, error) { r := Result{ Cached: res.Cached, HttpStatusCode: int(res.HttpStatusCode), HttpStatusMessage: res.HttpStatusMessage, Ttfb: time.Duration(res.Ttfb), } url, err := url.Parse(res.Url) if err != nil { return nil, err } r.URL = url return &r, nil } // connect establishes a gRPC connection to a worker and returns the // connection and a cancelation func for ending the connection. func connect(ctx context.Context, w *Worker, certPool *x509.CertPool) (*grpc.ClientConn, error) { opts := []grpc.DialOption{grpc.WithBlock()} if w.Certificate != nil { creds := credentials.NewClientTLSFromCert(certPool, "") opts = append(opts, grpc.WithTransportCredentials(creds)) } else { opts = append(opts, grpc.WithInsecure()) } if w.dialer != nil { opts = append(opts, grpc.WithContextDialer(w.dialer)) } return grpc.DialContext(ctx, fmt.Sprintf("%s:%d", w.Adress, w.Port), opts...) } // ctxWithSecret sets authorization metadata on // the returned context using a token. func ctxWithSecret( ctx context.Context, scheme string, token string) context.Context { if token == "" { return ctx } md := metadata.Pairs("authorization", fmt.Sprintf("%s %v", scheme, token)) nCtx := metautils.NiceMD(md).ToOutgoing(ctx) return nCtx }
package cmd import ( "bufio" "context" "errors" "fmt" "github.com/kobtea/go-todoist/cmd/util" "github.com/kobtea/go-todoist/todoist" "github.com/spf13/cobra" "os" "strconv" "strings" ) // labelCmd represents the label command var labelCmd = &cobra.Command{ Use: "label", Short: "subcommand for label", } var labelListCmd = &cobra.Command{ Use: "list", Short: "list label", RunE: func(cmd *cobra.Command, args []string) error { client, err := util.NewClient() if err != nil { return err } labels := client.Label.GetAll() fmt.Println(util.LabelTableString(labels)) return nil }, } var labelAddCmd = &cobra.Command{ Use: "add", Short: "add label", RunE: func(cmd *cobra.Command, args []string) error { client, err := util.NewClient() if err != nil { return err } name := strings.Join(args, " ") label := todoist.Label{ Name: name, } colorStr, err := cmd.Flags().GetString("color") if err != nil { return errors.New("Invalid label color") } if len(colorStr) > 0 { color, err := strconv.Atoi(colorStr) if err != nil { return fmt.Errorf("Invalid label color: %s", colorStr) } label.Color = color } if _, err = client.Label.Add(label); err != nil { return err } ctx := context.Background() if err = client.Commit(ctx); err != nil { return err } if err = client.FullSync(ctx, []todoist.Command{}); err != nil { return err } labels := client.Label.FindByName(name) if len(labels) == 0 { return errors.New("Failed to add this label. It may be failed to sync.") } // it may not be new label syncedLabel := labels[len(labels)-1] fmt.Println("Successful addition of a label.") fmt.Println(util.LabelTableString([]todoist.Label{syncedLabel})) return nil }, } var labelUpdateCmd = &cobra.Command{ Use: "update id [new_name]", Short: "update label", RunE: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("Require label ID to update") } id, err := todoist.NewID(args[0]) if err != nil { return fmt.Errorf("Invalid ID: %s", args[0]) } client, err := util.NewClient() if err != nil { return err } label := client.Label.Resolve(id) if label == nil { return fmt.Errorf("No such label id: %s", id) } if len(args) > 1 { label.Name = strings.Join(args[1:], " ") } colorStr, err := cmd.Flags().GetString("color") if err != nil { return errors.New("Invalid label color") } if len(colorStr) > 0 { color, err := strconv.Atoi(colorStr) if err != nil { return fmt.Errorf("Invalid label color: %s", colorStr) } label.Color = color } if _, err = client.Label.Update(*label); err != nil { return err } ctx := context.Background() if err = client.Commit(ctx); err != nil { return err } if err = client.FullSync(ctx, []todoist.Command{}); err != nil { return err } syncedLabel := client.Label.Resolve(id) if syncedLabel == nil { return errors.New("Failed to add this label. It may be failed to sync.") } fmt.Println("Successful updating label.") fmt.Println(util.LabelTableString([]todoist.Label{*syncedLabel})) return nil }, } var labelDeleteCmd = &cobra.Command{ Use: "delete id [...]", Short: "delete labels", RunE: func(cmd *cobra.Command, args []string) error { if err := util.AutoCommit(func(client todoist.Client, ctx context.Context) error { return util.ProcessIDs( args, func(ids []todoist.ID) error { var labels []todoist.Label for _, id := range ids { label := client.Label.Resolve(id) if label == nil { return fmt.Errorf("invalid id: %s", id) } labels = append(labels, *label) } fmt.Println(util.LabelTableString(labels)) reader := bufio.NewReader(os.Stdin) fmt.Print("are you sure to delete above label(s)? (y/[n]): ") ans, err := reader.ReadString('\n') if ans != "y\n" || err != nil { fmt.Println("abort") return errors.New("abort") } for _, id := range ids { if err := client.Label.Delete(id); err != nil { return err } } return nil }) }); err != nil { if err.Error() == "abort" { return nil } return err } fmt.Println("Successful deleting of label(s).") return nil }, } func init() { RootCmd.AddCommand(labelCmd) labelCmd.AddCommand(labelListCmd) labelAddCmd.Flags().StringP("color", "c", "7", "color") labelCmd.AddCommand(labelAddCmd) labelUpdateCmd.Flags().StringP("color", "c", "", "color") labelCmd.AddCommand(labelUpdateCmd) labelCmd.AddCommand(labelDeleteCmd) }
package isEmpty import ( "testing" "github.com/sirupsen/logrus" ) func TestIsEmpty(t *testing.T) { var ( logger logrus.FieldLogger = logrus.New() str interface{} = "asdsd" integer interface{} = 1234 sliceStr interface{} = []string{"a", "b"} sliceByte interface{} = []byte{1, 2, 3, 4} sliceInt interface{} = []int{1, 2, 3, 4} emptyLogger logrus.FieldLogger ) tests := []struct { name string values []interface{} want bool }{ {"Not empty logger", []interface{}{logger}, false}, {"Not empty string", []interface{}{str}, false}, {"Not empty int", []interface{}{integer}, false}, {"Not empty []string", []interface{}{sliceStr}, false}, {"Not empty []byte", []interface{}{sliceByte}, false}, {"Not empty []int", []interface{}{sliceInt}, false}, {"Not empty all", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer}, false}, {"Empty logger", []interface{}{emptyLogger}, true}, {"Empty string", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, ""}, true}, {"Empty int", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, 0}, true}, {"Empty interface{}", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, nil}, true}, {"Empty []string", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, []string{}}, true}, {"Empty []int", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, []int{}}, true}, {"Empty []byte", []interface{}{logger, str, sliceByte, sliceInt, sliceStr, integer, []byte{}}, true}, {"All empty", []interface{}{emptyLogger, "", []byte{}, []int{}, []string{}, 0}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() if got := Values(tt.values...); got != tt.want { t.Errorf("IsEmpty() = %v, want %v", got, tt.want) } }) } }
// Copyright 2022-present Open Networking Foundation. // // 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 rbac import ( "context" "encoding/json" "github.com/onosproject/onos-lib-go/pkg/errors" "github.com/prometheus/common/log" "golang.org/x/oauth2" "google.golang.org/grpc/metadata" "net/http" "net/url" "strings" ) // FetchATokenViaKeyCloak Get the token via keycloak using curl func FetchATokenViaKeyCloak(openIDIssuer string, user string, passwd string) (string, error) { data := url.Values{} data.Set("username", user) data.Set("password", passwd) data.Set("grant_type", "password") data.Set("client_id", "onos-config-test") data.Set("scope", "openid profile email groups") req, err := http.NewRequest("POST", openIDIssuer+"/protocol/openid-connect/token", strings.NewReader(data.Encode())) if err != nil { return "", err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } log.Debug("Response Code : ", resp.StatusCode) defer resp.Body.Close() if resp.StatusCode == http.StatusOK { target := new(oauth2.Token) err = json.NewDecoder(resp.Body).Decode(target) if err != nil { return "", err } return target.AccessToken, nil } return "", errors.NewInvalid("Error HTTP response code : ", resp.StatusCode) } // GetBearerContext gets a context that usesthe given token as the Bearer in the Authorization header func GetBearerContext(ctx context.Context, token string) context.Context { const ( authorization = "Authorization" ) token = "Bearer " + token md := make(metadata.MD) md.Set(authorization, token) ctx = metadata.NewOutgoingContext(ctx, md) return ctx }
package main import ( "log" "time" "strconv" "fmt" "errors" dcli "github.com/fsouza/go-dockerclient" "io" "io/ioutil" "os" "path" ) type Runner struct { ContainerId string CodeDir string Language string Code string OutStream io.Writer ErrStream io.Writer Uid int UidPool *UidPool client *dcli.Client } const ( STATUS_SUCCESS = 0 STATUS_TIMED_OUT = -1 ) func NewRunner(client *dcli.Client, lang string, code string) *Runner { return &Runner{Language: lang, Code: code, client: client, Uid: 10000} } func (r *Runner) Run(timeout time.Duration) (int, error) { log.Println("Creating code directory") if err := r.createCodeDir(); err != nil { return 0, err } log.Println("Creating source file") srcFile, err := r.createSrcFile() if err != nil { return 0, err } if r.UidPool != nil { log.Println("Reserving uid") uid, err := r.UidPool.Reserve() if err != nil { return 0, err } log.Printf("Got uid %d\n", uid) r.Uid = uid } log.Println("Creating container") if err := r.createContainer(srcFile); err != nil { return 0, err } log.Println("Starting container") if err := r.startContainer(); err != nil { return 0, err } defer r.cleanup() log.Println("Streaming container logs") go func() { if err := r.streamLogs(); err != nil { log.Println(err) } }() log.Println("Waiting for container to finish") killed, status := r.waitForExit(timeout) if killed { log.Printf("Container exited with status %d\n", status) return STATUS_TIMED_OUT, nil } return STATUS_SUCCESS, nil } func (r *Runner) createCodeDir() error { dir, err := ioutil.TempDir("", "code-") r.CodeDir = dir return err } func (r *Runner) createSrcFile() (string, error) { ext, err := extForLanguage(r.Language) if err != nil { return "", err } fileName := fmt.Sprintf("prog.%s", ext) filePath := path.Join(r.CodeDir, fileName) f, err := os.Create(filePath) if err != nil { return "", err } defer f.Close() if _, err := f.WriteString(r.Code); err != nil { return "", err } return fileName, nil } func (r *Runner) createContainer(srcFile string) error { volPathOpts := make(map[string]struct{}) volPathOpts["/code"] = struct{}{} uidStr := strconv.Itoa(r.Uid) config := &dcli.Config{ CpuShares: 1, Memory: 50e6, // Tty: true, OpenStdin: false, Volumes: volPathOpts, Cmd: []string{path.Join("/code", srcFile), uidStr}, Image: "runner", NetworkDisabled: true, } container, err := r.client.CreateContainer(dcli.CreateContainerOptions{Config:config}) if err != nil { return err } r.ContainerId = container.ID return nil } func (r *Runner) startContainer() error { if r.ContainerId == "" { return errors.New("Can't start a container before it is created") } hostConfig := &dcli.HostConfig{ Binds: []string{fmt.Sprintf("%s:/code", r.CodeDir)}, } if err := r.client.StartContainer(r.ContainerId, hostConfig); err != nil { return err } return nil } func (r *Runner) waitForExit(timeoutMs time.Duration) (bool, int) { statusChan := make(chan int) go func() { if status, err := r.client.WaitContainer(r.ContainerId); err != nil { log.Println(err) } else { statusChan <- status } }() killed := false for { select { case status := <-statusChan: log.Println("Container exited by itself") return killed, status case <-time.After(time.Millisecond * timeoutMs): log.Println("Container timed out, killing") if err := r.client.StopContainer(r.ContainerId, 0); err != nil { log.Println(err) } killed = true } } } func (r *Runner) cleanup() { log.Println("Removing container") if err := r.client.RemoveContainer(dcli.RemoveContainerOptions{ID:r.ContainerId}); err != nil { log.Printf("Couldn't remove container %s (%v)\n", r.ContainerId, err) } if r.UidPool != nil { log.Println("Releasing uid") if err := r.UidPool.Release(r.Uid); err != nil { log.Printf("Couldn't release uid %d (%v)\n", r.Uid, err) } r.Uid = 0 } log.Println("Removing code dir") if err := os.RemoveAll(r.CodeDir); err != nil { log.Printf("Couldn't remove temp dir %s (%v)\n", r.CodeDir, err) } } func (r *Runner) streamLogs() error { if r.ContainerId == "" { return errors.New("Can't attach to a container before it is created") } attachOpts := dcli.AttachToContainerOptions{ Container: r.ContainerId, OutputStream: r.OutStream, ErrorStream: r.ErrStream, Logs: true, Stream: true, Stdout: true, Stderr: true, } if err := r.client.AttachToContainer(attachOpts); err != nil { return err } return nil } func extForLanguage(lang string) (string, error) { switch lang { case "c": return "c", nil case "golang": return "go", nil case "perl": return "pl", nil case "python": return "py", nil case "ruby": return "rb", nil } return "", fmt.Errorf("Invalid language %v", lang) }
package main import ( "os" "github.com/kafka-async/promise" ) func main() { promise.From(nil) os.Exit(1) }
package main import "fmt" func main() { //Arrays can only store types of the same value //Arrays are fixed in length, their length has to be specified when it is initialized var array [5]int array[0] = 100 array[4] = 300 fmt.Println(array) //Explicitly defining elements in the array arr := [5]int{2, 3, 4} fmt.Println(arr) //len(array) returns the length of the array fmt.Println(len(arr)) sum := 0 for i := 0; i < len(arr); i++ { sum += arr[i] } fmt.Println(sum) //A multidimensional array arr2D := [2][3]int{{1, 2, 0}, {1, 2, 5}} fmt.Println(arr2D) fmt.Println(arr2D[1][0]) }
package crawl_test import ( "testing" "github.com/l-vitaly/golang-test-task/pkg/crawl" ) func TestCrawl(t *testing.T) { c := crawl.New() result, err := c.Do("http://ya.ru") if err != nil { t.Fatalf("unexpected error: %s", err) } if want, have := "http://ya.ru", result.URL; want != have { t.Errorf("want %s, have %s", want, have) } if want, have := "text/html", result.Meta.ContentType; want != have { t.Errorf("want %s, have %s", want, have) } if len(result.Elements) == 0 { t.Errorf("want > 0, have 0") } }
package types import ( "strings" "sync" "time" "github.com/bwmarrin/discordgo" ) type ServerDataType int type PollType int type PageSwitchType int type PageSwitchGetter func(PageSwitcher) (string, int, int, error) // text, newPage, maxPages, err type Empty struct{} const ( PlayChannel = 0 VotingChannel = 1 NewsChannel = 2 VoteCount = 3 PollCount = 4 ModRole = 5 UserColor = 6 PollCombo = 0 PollCategorize = 1 PollSign = 2 PollImage = 3 PollUnCategorize = 4 PollCatImage = 5 PollColor = 6 PollCatColor = 7 PageSwitchLdb = 0 PageSwitchInv = 1 ) type ComponentMsg interface { Handler(s *discordgo.Session, i *discordgo.InteractionCreate) } type ServerData struct { PlayChannels Container // channelID UserColors map[string]int VotingChannel string NewsChannel string VoteCount int PollCount int ModRole string // role ID LastCombs map[string]Comb // map[userID]comb Inventories map[string]Inventory // map[userID]map[elementName]types.Empty Elements map[string]Element //map[elementName]element Combos map[string]string // map[elems]elem3 Categories map[string]Category // map[catName]category Polls map[string]Poll // map[messageid]poll PageSwitchers map[string]PageSwitcher // map[messageid]pageswitcher ComponentMsgs map[string]ComponentMsg // map[messageid]componentMsg ElementMsgs map[string]string // map[messageid]elemname Lock *sync.RWMutex } type PageSwitcher struct { Kind PageSwitchType Title string PageGetter PageSwitchGetter Thumbnail string Footer string PageLength int Color int // Inv Items []string // Ldb Users []string Cnts []int UserPos int User string // Element sorting Query string Length int // Don't need to set these Guild string Page int } type Comb struct { Elems []string Elem3 string } type Element struct { ID int Name string Image string Color int Guild string Comment string Creator string CreatedOn time.Time Parents []string Complexity int Difficulty int UsedIn int TreeSize int } type Poll struct { Channel string Message string Guild string Kind PollType Value1 string Value2 string Value3 string Value4 string Data map[string]interface{} Upvotes int Downvotes int } type Category struct { Name string Guild string Elements map[string]Empty Image string Color int } type Msg struct { Author *discordgo.User ChannelID string GuildID string } type Inventory struct { Elements Container MadeCnt int User string } type Rsp interface { Error(err error) bool ErrorMessage(msg string) string Message(msg string, components ...discordgo.MessageComponent) string Embed(emb *discordgo.MessageEmbed, components ...discordgo.MessageComponent) string RawEmbed(emb *discordgo.MessageEmbed) string Resp(msg string, components ...discordgo.MessageComponent) Acknowledge() DM(msg string) } func NewServerData() ServerData { return ServerData{ Lock: &sync.RWMutex{}, ComponentMsgs: make(map[string]ComponentMsg), UserColors: make(map[string]int), Polls: make(map[string]Poll), PageSwitchers: make(map[string]PageSwitcher), Elements: make(map[string]Element), Combos: make(map[string]string), Categories: make(map[string]Category), Inventories: make(map[string]Inventory), LastCombs: make(map[string]Comb), } } type Container map[string]Empty func (c Container) Contains(elem string) bool { _, exists := c[strings.ToLower(elem)] return exists } func (c Container) Add(elem string) { c[strings.ToLower(elem)] = Empty{} } func NewInventory(user string) Inventory { return Inventory{ Elements: make(map[string]Empty), User: user, } }
/** * Copyright (c) 2018 ZTE Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * ZTE - initial Project */ package util import ( "os" "strings" "testing" ) func TestGetCfgPath(t *testing.T) { got := GetCfgPath() if !strings.Contains(got, "conf") { t.Errorf("GetCfgPath() => got %v, should contains `ocnf`", got) } } func TestGetGoPath(t *testing.T) { oldPaths := os.Getenv("GOPATH") cases := []struct { in string want []string }{ { // window in: `path1;path2;path3`, want: []string{ `path1`, `path2`, `path3`, }, }, { // linux in: `path1:path2:path3`, want: []string{ `path1`, `path2`, `path3`, }, }, { // single Path in: `path1`, want: []string{ `path1`, }, }, { // single Path in: `;`, want: []string{ ``, ``, }, }, } for _, cas := range cases { os.Setenv("GOPATH", cas.in) got := GetGoPath() if len(cas.want) != len(got) { t.Errorf("GetGoPath() => different size, got %d, want %d, %v, %v", len(got), len(cas.want), got, cas.want) } for i, item := range cas.want { if item != got[i] { t.Errorf("GetGoPath() => got %v, want %v", got, cas.want) break } } } // unset test os.Unsetenv("GOPATH") got := GetGoPath() if len(got) != 0 { t.Errorf("GetGoPath() => unset env test got len %d, want 0", len(got)) } os.Setenv("GOPATH", oldPaths) } func TestFileExists(t *testing.T) { existFile := `common_test.go` notExistFile := `common_test.go_11` exist := FileExists(existFile) if !exist { t.Errorf("FileExists(%s) => got false, want true", existFile) } exist = FileExists(notExistFile) if exist { t.Errorf("FileExists(%s) => got true, want false", notExistFile) } }
package minedive import "fmt" type Cell struct { Type string `json:"type"` D0 string `json:"d0"` D1 string `json:"d1"` D2 string `json:"d2"` D3 string `json:"d3"` } func (a *Cell) String() string { return fmt.Sprintf("%v (%v %v %v %v)", a.Type, a.D0, a.D1, a.D2, a.D3) } // type p1Users struct { // Name string `json:"name"` // Alias string `json:"alias"` // } // type dataMsg struct { // Type string `json:"type"` // Data string `json:"data"` // } // type userlistMsg struct { // Type string `json:"type"` // Contact int `json:"contact"` // Users []p1Users `json:"users"` // } // type idMsg struct { // Type string `json:"type"` // ID uint64 `json:"id"` // } // type usernameMsg struct { // Type string `json:"type"` // ID uint64 `json:"id"` // Name string `json:"name"` // PK string `json:"pk"` // } // type webrtcMsg struct { // Type string `json:"type"` // Name string `json:"name"` // Target string `json:"target"` // SDP string `json:"sdp"` // } // type keyReq struct { // Type string `json:"type"` // Alias string `json:"alias"` // GW string `json:"gw"` // } // type keyMsg struct { // Type string `json:"type"` // Alias string `json:"alias"` // Key string `json:"key"` // }
package bo type SelectMenuBo struct { CreateBy int `json:"createBy"` UpdatedBy int `json:"updatedBy"` SubCount int `json:"subCount"` MenuSort int `json:"menuSort"` ID int `json:"id"` Pid int `json:"pid"` Type int `json:"type"` Cache bool `json:"cache"` Hidden bool `json:"hidden"` Leaf bool `json:"leaf"` Iframe bool `json:"iframe"` HasChildren bool `json:"hasChildren"` CreateTime string `json:"createTime"` UpdateTime string `json:"updateTime"` Label string `json:"label"` Icon string `json:"icon"` Component string `json:"component"` Name string `json:"name"` Path string `json:"path"` Permission string `json:"permission"` Title string `json:"title"` Children []*Children `json:"children"` } type Meta struct { Icon string `json:"icon"` NoCache bool `json:"noCache"` Title string `json:"title"` } type Children struct { Component string `json:"component"` Name string `json:"name"` Path string `json:"path"` Hidden bool `json:"hidden"` Meta *Meta `json:"meta"` Child []*Children `json:"children,omitempty"` } type SelectForeNeedMenuBo struct { AlwaysShow bool `json:"alwaysShow"` Hidden bool `json:"hidden"` Component string `json:"component"` Name string `json:"name"` Path string `json:"path"` Redirect string `json:"redirect"` Meta *Meta `json:"meta"` Children []*Children `json:"children,omitempty"` } type ReturnToAllMenusBo struct { Cache bool `json:"cache"` Children interface{} `json:"children"` Component string `json:"component"` CreateBy int `json:"createBy"` CreateTime int64 `json:"createTime"` HasChildren bool `json:"hasChildren"` Hidden bool `json:"hidden"` Icon string `json:"icon"` ID int `json:"id"` Iframe bool `json:"iframe"` Label string `json:"label"` Leaf bool `json:"leaf"` MenuSort int `json:"menuSort"` Name string `json:"name"` Path string `json:"path"` Permission string `json:"permission"` Pid int `json:"pid"` SubCount int `json:"subCount"` Title string `json:"title"` Type int `json:"type"` UpdatedBy int `json:"updatedBy"` UpdateTime int64 `json:"updateTime"` } type DownloadMenuInfoBo struct { Title string `json:"title"` Type string `json:"type"` Permission string `json:"permission"` IFrame string `json:"i_frame"` Hidden string `json:"hidden"` Cache string `json:"cache"` CreateTime string `json:"create_time"` } type SelectSuperMenuBo struct { CreateBy int `json:"createBy"` UpdatedBy int `json:"updatedBy"` SubCount int `json:"subCount"` MenuSort int `json:"menuSort"` ID int `json:"id"` Pid int `json:"pid"` Type int `json:"type"` Cache bool `json:"cache"` Hidden bool `json:"hidden"` Leaf bool `json:"leaf"` Iframe bool `json:"iframe"` CreateTime int64 `json:"createTime"` UpdateTime int64 `json:"updateTime"` Label string `json:"label"` Children []*SelectSuperMenuBo `json:"children"` Icon string `json:"icon"` Component string `json:"component"` Name string `json:"name"` Path string `json:"path"` Permission string `json:"permission"` Title string `json:"title"` HasChildren bool `json:"hasChildren"` }
package common import ( "time" "gopkg.in/mgo.v2/bson" ) //////////////////////聊天房间信息<<<<<<<<<<<<<<<<<<< // 聊天房间类型 const ( CHAT_TYPE_ROOM int32 = 1 // 临时房间 CHAT_TYPE_TEAM int32 = 2 // 临时队伍 CHAT_TYPE_GROUP int32 = 3 // 群聊 CHAT_TYPE_MATCHTEAM int32 = 4 // 比赛组队 CHAT_TYPE_RADAR int32 = 6 // 雷达 CHAT_TYPE_SYSTEM int32 = 7 // 系统群 CHAT_TALK_0 uint32 = 0 // 互关私聊 CHAT_TALK_1 uint32 = 1 // 快捷私聊 CHAT_TALK_2 uint32 = 2 // 互关推送 CHAT_TALK_3 uint32 = 3 // 未读接收消息 CHAT_TALK_4 uint32 = 4 // 粉丝私聊 //群设置 CHAT_SET_TOP int32 = 1 // 置顶 CHAT_SET_DISTURB int32 = 2 // 消息免打扰 CHAT_MATCHTEAM_TIME uint32 = 3 * 24 * 60 * 60 //比赛结束组队群组时效 CHAT_ROOM_TIME uint32 = 30 * 60 //比赛结束临时群组时效 CHAT_RED_TYPE_1 uint32 = 1 //彩豆包 CHAT_RED_MAX uint32 = 1000 //最大爱心数量 CHAT_EXCHANGE_1 uint32 = 1 //彩豆兑换爱心比 CHAT_EXCHANGE_2 uint32 = 2 //蘑菇兑换爱心比 CHAT_RED_END_TIME uint32 = 24 * 60 * 60 //红包过期时间 CHAT_ROOM_ADD uint32 = 1 // 增加 CHAT_ROOM_DEL uint32 = 2 // 删除 CHAT_ACTIVE_TIME uint32 = 5 * 60 //群组活跃时间 CHAT_TIME int64 = 500 //聊天频率 毫秒 ) type ChatRoom struct { Id bson.ObjectId `bson:"_id"` RoomId uint64 `bson:"roomid"` //进程房间ID Owner uint64 `bson:"owner"` //房主ID Name string `bson:"name"` //群名称 Type int32 `bson:"type"` //房间类型 UserList []uint64 `bson:"userlist"` //成员ID列表 EndTime uint32 `bson:"endtime"` //房间结束时间 TalkId uint64 `bson:"talkid"` //聊天内容id } type UserShow struct { Id uint64 Account string // 帐号 Sex uint8 // 性别 PassIcon string // 已审核头像 Icon uint32 // 图标 } type ChatSynTalk struct { RoomId uint64 //房间ID UserId uint64 //玩家ID StartId uint64 //开始ID } type ChatSynSet struct { RoomId uint64 //房间ID UserId uint64 //玩家ID Top bool //置顶 Disturb bool //消息免打扰 } type ChatSynPersonalSet struct { FriendTalk bool `bson:"friendtalk"` //是否开启互关好友才能聊天 QuickTalk bool `bson:"quicktalk"` //是否开启快捷聊天 BatchPush bool `bson:"batchpush"` //是否开启批量互关推送 UnReadTalk bool `bson:"unreadtalk"` //是否开启未读接收消息 } type ChatSyn struct { Id bson.ObjectId `bson:"_id"` UserId uint64 `bson:"userid"` // 用户ID Rooms []uint64 `bson:"rooms"` // 拥有群列表 Talks []*ChatSynTalk `bson:"talks"` // 聊天游标 Sets []*ChatSynSet `bson:"sets"` // 群设置 PersonalSet *ChatSynPersonalSet `bson:"personalsets"` // 个人设置 FansTalk []uint64 `bson:"fanstalk"` // 粉丝聊天 } //房间离线消息 type ChatTalkRoom struct { Id bson.ObjectId `bson:"_id"` RoomId uint64 `bson:"roomid"` // 房间ID TalkId uint64 `bson:"talkid"` // 聊天ID UserId uint64 `bson:"userid"` // 说话玩家ID Text string `bson:"text"` // 内容 Time uint32 `bson:"time"` // 时间 Date time.Time `bson:"date"` // 日期 } //玩家离线消息 type ChatTalkUser struct { Id uint64 `bson:"_id"` SelfId uint64 `bson:"selfid"` // 玩家自身ID UserId uint64 `bson:"userid"` // 说话玩家ID Text string `bson:"text"` // 内容 Time uint32 `bson:"time"` // 时间 Date time.Time `bson:"date"` // 日期 } type RetTalk struct { RoomId string //房间ID UserId uint64 //玩家ID Talks []*RetTalkTalk //内容 } type RetTalkTalk struct { UserId uint64 //玩家ID Text string //内容 Time uint32 //时间 TalkId uint64 //聊天ID } type ChatRed struct { TalkId uint64 //聊天ID SendId uint64 //发送者ID RoomId uint64 //房间ID TypeId uint32 //爱心包类型 1彩豆包 2蘑菇包 Nums uint32 //数量 Total uint32 //总额 Less uint32 //剩余额度 SendTime uint32 //发送时间 UserList map[uint64]*ChatRedReceive //已领取红包列表 EndTime uint32 //领完时间 } type ChatRedMongo struct { Id bson.ObjectId `bson:"_id"` TalkId uint64 `bson:"talkid"` //聊天ID SendId uint64 `bson:"sendid"` //发送者ID RoomId uint64 `bson:"roomid"` //房间ID TypeId uint32 `bson:"typeid"` //爱心包类型 1彩豆包 2蘑菇包 Nums uint32 `bson:"nums"` //数量 Total uint32 `bson:"total"` //总额 Less uint32 `bson:"less"` //剩余额度 SendTime uint32 `bson:"sendtime"` //发送时间 UserList []*ChatRedReceive `bson:"userlist"` //已领取红包列表 EndTime uint32 `bson:"endtime"` //领完时间 } type ChatRedReceive struct { UserId uint64 `json:"userid"` //玩家ID Loves uint32 `json:"loves"` //爱心数 Time uint32 `json:"time"` //时间 } type ChatRedEnd struct { RoomId uint64 //群组ID TalkId uint64 //聊天ID EndTime uint32 //过期时间 } const ( NOTICE_TYPE_1 uint32 = 1 //滚屏公告 NOTICE_TYPE_2 uint32 = 2 //系统消息 NOTICE_TYPE_3 uint32 = 3 //弹出公告 ) type NoticeInfo struct { Id uint64 `redis:"Id"` TypeId uint32 `redis:"TypeId"` //类型1滚屏公告 2系统消息 Text string `redis:"Text"` //内容 SysType string `redis:"SysType"` //系统类型 android ios ClientVer string `redis:"ClientVer"` //客户端版本 BetUserid string `redis:"BetUserid"` //玩家ID区间 Awards string `redis:"Awards"` //奖励 STime uint32 `redis:"STime"` //开始时间 ETime uint32 `redis:"ETime"` //结束时间 RTime uint32 `redis:"RTime"` //间隔频率 CanSend bool `redis:"CanSend"` //是否可以发送 }
package main import ( "net/http" "time" "appengine/datastore" "github.com/crhym3/go-endpoints/endpoints" ) type Greeting struct { Key *datastore.Key `json:"id" datastore:"-"` Author string `json:"author"` Content string `json:"content" datastore:",noindex" endpoint:"req"` Date time.Time `json:"date"` } type GreetingsList struct { Items []*Greeting `json:"items"` } type GreetingsListReq struct { Limit int `json:"limit" endpoint:"d=10"` } type GreetingService struct { } func (gs *GreetingService) List(r *http.Request, req *GreetingsListReq, resp *GreetingsList) error { if req.Limit <= 0 { req.Limit = 10 } c := endpoints.NewContext(r) q := datastore.NewQuery("Greeting").Order("-Date").Limit(req.Limit) greets := make([]*Greeting, 0, req.Limit) keys, err := q.GetAll(c, &greets) if err != nil { return err } for i, k := range keys { greets[i].Key = k } resp.Items = greets return nil } type GreetingReq struct { Author string Content string } func (gs *GreetingService) Create(r *http.Request, req *GreetingReq, resp *Greeting) error { c := endpoints.NewContext(r) resp.Author = req.Author resp.Content = req.Content resp.Date = time.Now() key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Greeting", nil), resp) if err != nil { return err } resp.Key = key return nil } func init() { greetService := &GreetingService{} api, err := endpoints.RegisterService(greetService, "greeting", "v1", "Greetings API", true) if err != nil { panic(err.Error()) } info := api.MethodByName("List").Info() info.Name, info.HTTPMethod, info.Path, info.Desc = "greets.list", "GET", "greetings", "List most recent greetings." info = api.MethodByName("Create").Info() info.Name, info.HTTPMethod, info.Path, info.Desc = "greets.create", "POST", "greetings", "List most recent greetings." endpoints.HandleHTTP() }
// +build !NO_CUDA package runner import ( "testing" ) // This file contains an integration test implementation that submits a studio runner // task across an SQS queue and then validates is has completed successfully by // the go runner this test is running within func TestCUDA(t *testing.T) { logger := NewLogger("cuda_test") if !*UseGPU { logger.Warn("TestCUDA not run") t.Skip("no GPUs present for testing") } logger.Warn("TestCUDA completed") }
package main import ( "fmt" "math/rand" "sort" ) type Students struct { Name string Id string Age int } type Book struct { Name string Author string } //实现sort接口 type StudentArray []Students func (p StudentArray) Len() int { return len(p) } func (p StudentArray) Swap(i, j int){ p[i], p[j] = p[j], p[i] } func (p StudentArray) Less(i, j int) bool { return p[i].Name < p[j].Name } func main() { var stus StudentArray for i := 0; i < 10; i++ { stu := Students{ Name:fmt.Sprintf("stu%d", rand.Intn(100)), Id:fmt.Sprintf("110%d", rand.Int()), Age:rand.Intn(100), } stus = append(stus, stu) } for _, v := range stus{ fmt.Println(v) } fmt.Println("________________________") sort.Sort(stus) for _, v := range stus{ fmt.Println(v) } }
package main import "fmt" // https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/ // Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } func removeNthFromEnd(head *ListNode, n int) *ListNode { if head == nil { return nil } p := head for i := 0; i < n; i++ { p = p.Next } if p == nil { head = head.Next return head } pre := head for ; p.Next != nil; p = p.Next { pre = pre.Next } pre.Next = pre.Next.Next return head } func main() { cases := [][]int{ {}, {}, } realCase := cases[0:] for i, c := range realCase { fmt.Println("## case", i) // solve fmt.Println(c) } }
package workqueue func (w *WriteBackerConfig) CopyFrom(other *WriteBackerConfig) { w.Batcher.MaxItems = other.Batcher.MaxItems w.Batcher.MaxWaitTime = other.Batcher.MaxWaitTime w.Batcher.BatchBufferSize = other.Batcher.BatchBufferSize w.Transactioner.DB = other.Transactioner.DB w.Transactioner.MaxTransactionSize = other.Transactioner.MaxTransactionSize w.Transactioner.MaxTransactionLifetime = other.Transactioner.MaxTransactionLifetime w.FileSystemName = other.FileSystemName w.Namespace = other.Namespace w.RunID = other.RunID w.SnapshotName = other.SnapshotName w.Pool = other.Pool w.DB = other.DB w.Logger = other.Logger } func (w *WriteBackerConfig) Merge(other *WriteBackerConfig) *WriteBackerConfig { if other.Batcher.MaxItems != 0 { w.Batcher.MaxItems = other.Batcher.MaxItems } if other.Batcher.MaxWaitTime != 0 { w.Batcher.MaxWaitTime = other.Batcher.MaxWaitTime } if other.Batcher.BatchBufferSize != 0 { w.Batcher.BatchBufferSize = other.Batcher.BatchBufferSize } if other.Transactioner.DB != nil { w.Transactioner.DB = other.Transactioner.DB } if other.Transactioner.MaxTransactionSize != 0 { w.Transactioner.MaxTransactionSize = other.Transactioner.MaxTransactionSize } if other.Transactioner.MaxTransactionLifetime != 0 { w.Transactioner.MaxTransactionLifetime = other.Transactioner.MaxTransactionLifetime } if len(other.FileSystemName) > 0 { w.FileSystemName = other.FileSystemName } if len(other.Namespace) > 0 { w.Namespace = other.Namespace } if other.RunID != 0 { w.RunID = other.RunID } if len(other.SnapshotName) > 0 { w.SnapshotName = other.SnapshotName } if other.Pool != nil { w.Pool = other.Pool } if other.DB != nil { w.DB = other.DB } if other.Logger != nil { w.Logger = other.Logger } return w } func (w *WriteBackerConfig) Clone() *WriteBackerConfig { config := &WriteBackerConfig{} config.CopyFrom(w) return config }
package types import ( "bytes" "encoding/json" "fmt" "html" "html/template" "net/http" "strconv" "strings" "time" "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/constant" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/modules/errors" "github.com/GoAdminGroup/go-admin/modules/file" "github.com/GoAdminGroup/go-admin/modules/language" "github.com/GoAdminGroup/go-admin/modules/logger" "github.com/GoAdminGroup/go-admin/modules/utils" "github.com/GoAdminGroup/go-admin/plugins/admin/modules" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/form" form2 "github.com/GoAdminGroup/go-admin/template/types/form" ) type FieldOption struct { Text string `json:"text"` Value string `json:"value"` TextHTML template.HTML `json:"-"` Selected bool `json:"-"` SelectedLabel template.HTML `json:"-"` Extra map[string]string `json:"-"` } type FieldOptions []FieldOption func (fo FieldOptions) Copy() FieldOptions { newOptions := make(FieldOptions, len(fo)) copy(newOptions, fo) return newOptions } func (fo FieldOptions) SetSelected(val interface{}, labels []template.HTML) FieldOptions { if valArr, ok := val.([]string); ok { for k := range fo { text := fo[k].Text if text == "" { text = string(fo[k].TextHTML) } fo[k].Selected = utils.InArray(valArr, fo[k].Value) || utils.InArray(valArr, text) if fo[k].Selected { fo[k].SelectedLabel = labels[0] } else { fo[k].SelectedLabel = labels[1] } } } else { for k := range fo { text := fo[k].Text if text == "" { text = string(fo[k].TextHTML) } fo[k].Selected = fo[k].Value == val || text == val if fo[k].Selected { fo[k].SelectedLabel = labels[0] } else { fo[k].SelectedLabel = labels[1] } } } return fo } func (fo FieldOptions) SetSelectedLabel(labels []template.HTML) FieldOptions { for k := range fo { if fo[k].Selected { fo[k].SelectedLabel = labels[0] } else { fo[k].SelectedLabel = labels[1] } } return fo } func (fo FieldOptions) Marshal() string { if len(fo) == 0 { return "" } eo, err := json.Marshal(fo) if err != nil { return "" } return string(eo) } type ( OptionInitFn func(val FieldModel) FieldOptions OptionArrInitFn func(val FieldModel) []FieldOptions OptionTableQueryProcessFn func(sql *db.SQL) *db.SQL OptionProcessFn func(options FieldOptions) FieldOptions OptionTable struct { Table string TextField string ValueField string QueryProcessFn OptionTableQueryProcessFn ProcessFn OptionProcessFn } ) // FormField is the form field with different options. type FormField struct { Field string `json:"field"` FieldClass string `json:"field_class"` TypeName db.DatabaseType `json:"type_name"` Head string `json:"head"` Foot template.HTML `json:"foot"` FormType form2.Type `json:"form_type"` FatherFormType form2.Type `json:"father_form_type"` FatherField string `json:"father_field"` RowWidth int RowFlag uint8 Default template.HTML `json:"default"` DefaultArr interface{} `json:"default_arr"` Value template.HTML `json:"value"` Value2 string `json:"value_2"` ValueArr []string `json:"value_arr"` Value2Arr []string `json:"value_2_arr"` Options FieldOptions `json:"options"` OptionsArr []FieldOptions `json:"options_arr"` DefaultOptionDelimiter string `json:"default_option_delimiter"` Label template.HTML `json:"label"` HideLabel bool `json:"hide_label"` Placeholder string `json:"placeholder"` CustomContent template.HTML `json:"custom_content"` CustomJs template.JS `json:"custom_js"` CustomCss template.CSS `json:"custom_css"` Editable bool `json:"editable"` NotAllowEdit bool `json:"not_allow_edit"` NotAllowAdd bool `json:"not_allow_add"` DisplayButNotAdd bool `json:"display_but_not_add"` Must bool `json:"must"` Hide bool `json:"hide"` CreateHide bool `json:"create_hide"` EditHide bool `json:"edit_hide"` Width int `json:"width"` InputWidth int `json:"input_width"` HeadWidth int `json:"head_width"` Joins Joins `json:"-"` Divider bool `json:"divider"` DividerTitle string `json:"divider_title"` HelpMsg template.HTML `json:"help_msg"` TableFields FormFields Style template.HTMLAttr `json:"style"` NoIcon bool `json:"no_icon"` OptionExt template.JS `json:"option_ext"` OptionExt2 template.JS `json:"option_ext_2"` OptionInitFn OptionInitFn `json:"-"` OptionArrInitFn OptionArrInitFn `json:"-"` OptionTable OptionTable `json:"-"` FieldDisplay `json:"-"` PostFilterFn PostFieldFilterFn `json:"-"` } func (f *FormField) GetRawValue(columns []string, v interface{}) string { isJSON := len(columns) == 0 return modules.AorB(isJSON || modules.InArray(columns, f.Field), db.GetValueFromDatabaseType(f.TypeName, v, isJSON).String(), "") } func (f *FormField) UpdateValue(id, val string, res map[string]interface{}, sql *db.SQL) *FormField { return f.updateValue(id, val, res, PostTypeUpdate, sql) } func (f *FormField) UpdateDefaultValue(sql *db.SQL) *FormField { f.Value = f.Default return f.updateValue("", string(f.Value), make(map[string]interface{}), PostTypeCreate, sql) } func (f *FormField) setOptionsFromSQL(sql *db.SQL) { if sql != nil && f.OptionTable.Table != "" && len(f.Options) == 0 { sql.Table(f.OptionTable.Table).Select(f.OptionTable.ValueField, f.OptionTable.TextField) if f.OptionTable.QueryProcessFn != nil { f.OptionTable.QueryProcessFn(sql) } queryRes, err := sql.All() if err == nil { for _, item := range queryRes { f.Options = append(f.Options, FieldOption{ Value: fmt.Sprintf("%v", item[f.OptionTable.ValueField]), Text: fmt.Sprintf("%v", item[f.OptionTable.TextField]), }) } } if f.OptionTable.ProcessFn != nil { f.Options = f.OptionTable.ProcessFn(f.Options) } } } func (f *FormField) isBelongToATable() bool { return f.FatherField != "" && f.FatherFormType.IsTable() } func (f *FormField) isNotBelongToATable() bool { return f.FatherField == "" && !f.FatherFormType.IsTable() } func (f *FormField) allowAdd() bool { return !f.NotAllowAdd } func (f *FormField) updateValue(id, val string, res map[string]interface{}, typ PostType, sql *db.SQL) *FormField { m := FieldModel{ ID: id, Value: val, Row: res, PostType: typ, } if f.isBelongToATable() { if f.FormType.IsSelect() { if len(f.OptionsArr) == 0 && f.OptionArrInitFn != nil { f.OptionsArr = f.OptionArrInitFn(m) for i := 0; i < len(f.OptionsArr); i++ { f.OptionsArr[i] = f.OptionsArr[i].SetSelectedLabel(f.FormType.SelectedLabel()) } } else { f.setOptionsFromSQL(sql) if f.FormType.IsSingleSelect() { values := f.ToDisplayStringArray(m) f.OptionsArr = make([]FieldOptions, len(values)) for k, value := range values { f.OptionsArr[k] = f.Options.Copy().SetSelected(value, f.FormType.SelectedLabel()) } } else { values := f.ToDisplayStringArrayArray(m) f.OptionsArr = make([]FieldOptions, len(values)) for k, value := range values { f.OptionsArr[k] = f.Options.Copy().SetSelected(value, f.FormType.SelectedLabel()) } } } } else { f.ValueArr = f.ToDisplayStringArray(m) } } else { if f.FormType.IsSelect() { if len(f.Options) == 0 && f.OptionInitFn != nil { f.Options = f.OptionInitFn(m).SetSelectedLabel(f.FormType.SelectedLabel()) } else { f.setOptionsFromSQL(sql) f.Options.SetSelected(f.ToDisplay(m), f.FormType.SelectedLabel()) } } else if f.FormType.IsArray() { f.ValueArr = f.ToDisplayStringArray(m) } else { f.Value = f.ToDisplayHTML(m) if f.FormType.IsFile() { if f.Value != template.HTML("") { f.Value2 = config.GetStore().URL(string(f.Value)) } } } } return f } func (f *FormField) FillCustomContent() *FormField { // TODO: optimize if f.CustomContent != "" { f.CustomContent = template.HTML(f.fillCustom(string(f.CustomContent))) } if f.CustomJs != "" { f.CustomJs = template.JS(f.fillCustom(string(f.CustomJs))) } if f.CustomCss != "" { f.CustomCss = template.CSS(f.fillCustom(string(f.CustomCss))) } return f } func (f *FormField) fillCustom(src string) string { t := template.New("custom") t, err := t.Parse(src) if err != nil { logger.Error(err) return "" } buf := new(bytes.Buffer) err = t.Execute(buf, f) if err != nil { logger.Error(err) return "" } return buf.String() } // FormPanel type FormPanel struct { FieldList FormFields `json:"field_list"` curFieldListIndex int // Warn: may be deprecated in the future. `json:"" TabGroups TabGroups `json:"tab_groups"` TabHeaders TabHeaders `json:"tab_headers"` Table string `json:"table"` Title string `json:"title"` Description string `json:"description"` Validator FormPostFn `json:"validator"` PostHook FormPostFn `json:"post_hook"` PreProcessFn FormPreProcessFn `json:"pre_process_fn"` Callbacks Callbacks `json:"callbacks"` primaryKey primaryKey UpdateFn FormPostFn `json:"update_fn"` InsertFn FormPostFn `json:"insert_fn"` IsHideContinueEditCheckBox bool `json:"is_hide_continue_edit_check_box"` IsHideContinueNewCheckBox bool `json:"is_hide_continue_new_check_box"` IsHideResetButton bool `json:"is_hide_reset_button"` IsHideBackButton bool `json:"is_hide_back_button"` Layout form2.Layout `json:"layout"` HTMLContent template.HTML `json:"html_content"` Header template.HTML `json:"header"` InputWidth int `json:"input_width"` HeadWidth int `json:"head_width"` FormNewTitle template.HTML `json:"form_new_title"` FormNewBtnWord template.HTML `json:"form_new_btn_word"` FormEditTitle template.HTML `json:"form_edit_title"` FormEditBtnWord template.HTML `json:"form_edit_btn_word"` Ajax bool `json:"ajax"` AjaxSuccessJS template.JS `json:"ajax_success_js"` AjaxErrorJS template.JS `json:"ajax_error_js"` Responder Responder `json:"responder"` Wrapper ContentWrapper `json:"wrapper"` HideSideBar bool `json:"hide_side_bar"` processChains DisplayProcessFnChains HeaderHtml template.HTML `json:"header_html"` FooterHtml template.HTML `json:"footer_html"` PageError errors.PageError `json:"page_error"` PageErrorHTML template.HTML `json:"page_error_html"` NoCompress bool `json:"no_compress"` } type Responder func(ctx *context.Context) func NewFormPanel() *FormPanel { return &FormPanel{ curFieldListIndex: -1, Callbacks: make(Callbacks, 0), Layout: form2.LayoutDefault, FormNewTitle: "New", FormEditTitle: "Edit", FormNewBtnWord: language.GetFromHtml("Save"), FormEditBtnWord: language.GetFromHtml("Save"), } } func (f *FormPanel) AddLimitFilter(limit int) *FormPanel { f.processChains = addLimit(limit, f.processChains) return f } func (f *FormPanel) AddTrimSpaceFilter() *FormPanel { f.processChains = addTrimSpace(f.processChains) return f } func (f *FormPanel) AddSubstrFilter(start int, end int) *FormPanel { f.processChains = addSubstr(start, end, f.processChains) return f } func (f *FormPanel) AddToTitleFilter() *FormPanel { f.processChains = addToTitle(f.processChains) return f } func (f *FormPanel) AddToUpperFilter() *FormPanel { f.processChains = addToUpper(f.processChains) return f } func (f *FormPanel) AddToLowerFilter() *FormPanel { f.processChains = addToLower(f.processChains) return f } func (f *FormPanel) AddXssFilter() *FormPanel { f.processChains = addXssFilter(f.processChains) return f } func (f *FormPanel) AddXssJsFilter() *FormPanel { f.processChains = addXssJsFilter(f.processChains) return f } func (f *FormPanel) SetPrimaryKey(name string, typ db.DatabaseType) *FormPanel { f.primaryKey = primaryKey{Name: name, Type: typ} return f } func (f *FormPanel) HideContinueEditCheckBox() *FormPanel { f.IsHideContinueEditCheckBox = true return f } func (f *FormPanel) HideContinueNewCheckBox() *FormPanel { f.IsHideContinueNewCheckBox = true return f } func (f *FormPanel) HideResetButton() *FormPanel { f.IsHideResetButton = true return f } func (f *FormPanel) HideBackButton() *FormPanel { f.IsHideBackButton = true return f } func (f *FormPanel) AddFieldTr(ctx *context.Context, head, field string, filedType db.DatabaseType, formType form2.Type) *FormPanel { return f.AddFieldWithTranslation(ctx, head, field, filedType, formType) } func (f *FormPanel) AddFieldWithTranslation(ctx *context.Context, head, field string, filedType db.DatabaseType, formType form2.Type) *FormPanel { return f.AddField(language.GetWithLang(head, ctx.Lang()), field, filedType, formType) } func (f *FormPanel) AddField(head, field string, filedType db.DatabaseType, formType form2.Type) *FormPanel { f.FieldList = append(f.FieldList, FormField{ Head: head, Field: field, FieldClass: field, TypeName: filedType, Editable: true, Hide: false, TableFields: make(FormFields, 0), Placeholder: language.Get("input") + " " + head, FormType: formType, FieldDisplay: FieldDisplay{ Display: func(value FieldModel) interface{} { return value.Value }, DisplayProcessChains: chooseDisplayProcessChains(f.processChains), }, }) f.curFieldListIndex++ // Set default options of different form type op1, op2, js := formType.GetDefaultOptions(field) f.FieldOptionExt(op1) f.FieldOptionExt2(op2) f.FieldOptionExtJS(js) // Set default Display Filter Function of different form type setDefaultDisplayFnOfFormType(f, formType) if formType.IsEditor() { f.NoCompress = true } return f } type AddFormFieldFn func(panel *FormPanel) func (f *FormPanel) AddTable(head, field string, addFields AddFormFieldFn) *FormPanel { index := f.curFieldListIndex addFields(f) for i := index + 1; i <= f.curFieldListIndex; i++ { f.FieldList[i].FatherFormType = form2.Table f.FieldList[i].FatherField = field } fields := make(FormFields, f.curFieldListIndex-index) copy(fields, f.FieldList[index+1:f.curFieldListIndex+1]) f.FieldList = append(f.FieldList, FormField{ Head: head, Field: field, FieldClass: field, TypeName: db.Varchar, Editable: true, Hide: false, TableFields: fields, FormType: form2.Table, FieldDisplay: FieldDisplay{ Display: func(value FieldModel) interface{} { return value.Value }, DisplayProcessChains: chooseDisplayProcessChains(f.processChains), }, }) f.curFieldListIndex++ return f } func (f *FormPanel) AddRow(addFields AddFormFieldFn) *FormPanel { index := f.curFieldListIndex addFields(f) if f.curFieldListIndex != index+1 { for i := index + 1; i <= f.curFieldListIndex; i++ { if i == index+1 { f.FieldList[i].RowFlag = 1 } else if i == f.curFieldListIndex { f.FieldList[i].RowFlag = 2 } else { f.FieldList[i].RowFlag = 3 } } } return f } // Field attribute setting functions // ==================================================== func (f *FormPanel) FieldDisplay(filter FieldFilterFn) *FormPanel { f.FieldList[f.curFieldListIndex].Display = filter return f } func (f *FormPanel) SetTable(table string) *FormPanel { f.Table = table return f } func (f *FormPanel) FieldMust() *FormPanel { f.FieldList[f.curFieldListIndex].Must = true return f } func (f *FormPanel) FieldHide() *FormPanel { f.FieldList[f.curFieldListIndex].Hide = true return f } func (f *FormPanel) FieldPlaceholder(placeholder string) *FormPanel { f.FieldList[f.curFieldListIndex].Placeholder = placeholder return f } func (f *FormPanel) FieldWidth(width int) *FormPanel { f.FieldList[f.curFieldListIndex].Width = width return f } func (f *FormPanel) FieldInputWidth(width int) *FormPanel { f.FieldList[f.curFieldListIndex].InputWidth = width return f } func (f *FormPanel) FieldHeadWidth(width int) *FormPanel { f.FieldList[f.curFieldListIndex].HeadWidth = width return f } func (f *FormPanel) FieldRowWidth(width int) *FormPanel { f.FieldList[f.curFieldListIndex].RowWidth = width return f } func (f *FormPanel) FieldHideLabel() *FormPanel { f.FieldList[f.curFieldListIndex].HideLabel = true return f } func (f *FormPanel) FieldFoot(foot template.HTML) *FormPanel { f.FieldList[f.curFieldListIndex].Foot = foot return f } func (f *FormPanel) FieldDivider(title ...string) *FormPanel { f.FieldList[f.curFieldListIndex].Divider = true if len(title) > 0 { f.FieldList[f.curFieldListIndex].DividerTitle = title[0] } return f } func (f *FormPanel) FieldHelpMsg(s template.HTML) *FormPanel { f.FieldList[f.curFieldListIndex].HelpMsg = s return f } func (f *FormPanel) FieldOptionInitFn(fn OptionInitFn) *FormPanel { f.FieldList[f.curFieldListIndex].OptionInitFn = fn return f } func (f *FormPanel) FieldOptionExt(m map[string]interface{}) *FormPanel { if m == nil { return f } if f.FieldList[f.curFieldListIndex].FormType.IsCode() { f.FieldList[f.curFieldListIndex].OptionExt = template.JS(fmt.Sprintf(` theme = "%s"; font_size = %s; language = "%s"; options = %s; `, m["theme"], m["font_size"], m["language"], m["options"])) return f } m = f.FieldList[f.curFieldListIndex].FormType.FixOptions(m) s, _ := json.Marshal(m) if f.FieldList[f.curFieldListIndex].OptionExt != template.JS("") { ss := string(f.FieldList[f.curFieldListIndex].OptionExt) ss = strings.Replace(ss, "}", "", strings.Count(ss, "}")) ss = strings.TrimRight(ss, " ") ss += "," f.FieldList[f.curFieldListIndex].OptionExt = template.JS(ss) + template.JS(strings.Replace(string(s), "{", "", 1)) } else { f.FieldList[f.curFieldListIndex].OptionExt = template.JS(string(s)) } return f } func (f *FormPanel) FieldOptionExt2(m map[string]interface{}) *FormPanel { if m == nil { return f } m = f.FieldList[f.curFieldListIndex].FormType.FixOptions(m) s, _ := json.Marshal(m) if f.FieldList[f.curFieldListIndex].OptionExt2 != template.JS("") { ss := string(f.FieldList[f.curFieldListIndex].OptionExt2) ss = strings.Replace(ss, "}", "", strings.Count(ss, "}")) ss = strings.TrimRight(ss, " ") ss += "," f.FieldList[f.curFieldListIndex].OptionExt2 = template.JS(ss) + template.JS(strings.Replace(string(s), "{", "", 1)) } else { f.FieldList[f.curFieldListIndex].OptionExt2 = template.JS(string(s)) } return f } func (f *FormPanel) FieldOptionExtJS(js template.JS) *FormPanel { if js != template.JS("") { f.FieldList[f.curFieldListIndex].OptionExt = js } return f } func (f *FormPanel) FieldOptionExtJS2(js template.JS) *FormPanel { f.FieldList[f.curFieldListIndex].OptionExt2 = js return f } func (f *FormPanel) FieldEnableFileUpload(data ...interface{}) *FormPanel { url := f.OperationURL("/file/upload") if len(data) > 0 { url = data[0].(string) } field := f.FieldList[f.curFieldListIndex].Field f.FieldList[f.curFieldListIndex].OptionExt = template.JS(fmt.Sprintf(` %seditor.customConfig.uploadImgServer = '%s'; %seditor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024; %seditor.customConfig.uploadImgMaxLength = 5; %seditor.customConfig.uploadFileName = 'file'; `, field, url, field, field, field)) var fileUploadHandler context.Handler if len(data) > 1 { fileUploadHandler = data[1].(context.Handler) } else { fileUploadHandler = func(ctx *context.Context) { if len(ctx.Request.MultipartForm.File) == 0 { ctx.JSON(http.StatusOK, map[string]interface{}{ "errno": 400, }) return } err := file.GetFileEngine(config.GetFileUploadEngine().Name).Upload(ctx.Request.MultipartForm) if err != nil { ctx.JSON(http.StatusOK, map[string]interface{}{ "errno": 500, }) return } var imgPath = make([]string, len(ctx.Request.MultipartForm.Value["file"])) for i, path := range ctx.Request.MultipartForm.Value["file"] { imgPath[i] = config.GetStore().URL(path) } ctx.JSON(http.StatusOK, map[string]interface{}{ "errno": 0, "data": imgPath, }) } } f.Callbacks = f.Callbacks.AddCallback(context.Node{ Path: url, Method: "post", Value: map[string]interface{}{constant.ContextNodeNeedAuth: 1}, Handlers: []context.Handler{fileUploadHandler}, }) return f } func (f *FormPanel) FieldDefault(def string) *FormPanel { f.FieldList[f.curFieldListIndex].Default = template.HTML(def) return f } // FieldNotAllowEdit means when update record the field can not be edited but will still be displayed and submitted. // Deprecated: Use FieldDisplayButCanNotEditWhenUpdate instead. func (f *FormPanel) FieldNotAllowEdit() *FormPanel { f.FieldList[f.curFieldListIndex].Editable = false return f } // FieldDisplayButCanNotEditWhenUpdate means when update record the field can not be edited but will still be displayed and submitted. func (f *FormPanel) FieldDisplayButCanNotEditWhenUpdate() *FormPanel { f.FieldList[f.curFieldListIndex].Editable = false return f } // FieldDisableWhenUpdate means when update record the field can not be edited, displayed and submitted. func (f *FormPanel) FieldDisableWhenUpdate() *FormPanel { f.FieldList[f.curFieldListIndex].NotAllowEdit = true return f } // FieldNotAllowAdd means when create record the field can not be edited, displayed and submitted. // Deprecated: Use FieldDisableWhenCreate instead. func (f *FormPanel) FieldNotAllowAdd() *FormPanel { f.FieldList[f.curFieldListIndex].NotAllowAdd = true return f } // FieldDisableWhenCreate means when create record the field can not be edited, displayed and submitted. func (f *FormPanel) FieldDisableWhenCreate() *FormPanel { f.FieldList[f.curFieldListIndex].NotAllowAdd = true return f } // FieldDisplayButCanNotEditWhenCreate means when create record the field can not be edited but will still be displayed and submitted. func (f *FormPanel) FieldDisplayButCanNotEditWhenCreate() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayButNotAdd = true return f } // FieldHideWhenCreate means when create record the field can not be edited and displayed, but will be submitted. func (f *FormPanel) FieldHideWhenCreate() *FormPanel { f.FieldList[f.curFieldListIndex].CreateHide = true return f } // FieldHideWhenUpdate means when update record the field can not be edited and displayed, but will be submitted. func (f *FormPanel) FieldHideWhenUpdate() *FormPanel { f.FieldList[f.curFieldListIndex].EditHide = true return f } func (f *FormPanel) FieldFormType(formType form2.Type) *FormPanel { f.FieldList[f.curFieldListIndex].FormType = formType return f } func (f *FormPanel) FieldValue(value string) *FormPanel { f.FieldList[f.curFieldListIndex].Value = template.HTML(value) return f } func (f *FormPanel) FieldOptionsFromTable(table, textFieldName, valueFieldName string, process ...OptionTableQueryProcessFn) *FormPanel { var fn OptionTableQueryProcessFn if len(process) > 0 { fn = process[0] } f.FieldList[f.curFieldListIndex].OptionTable = OptionTable{ Table: table, TextField: textFieldName, ValueField: valueFieldName, QueryProcessFn: fn, } return f } func (f *FormPanel) FieldOptionsTableProcessFn(fn OptionProcessFn) *FormPanel { f.FieldList[f.curFieldListIndex].OptionTable.ProcessFn = fn return f } func (f *FormPanel) FieldOptions(options FieldOptions) *FormPanel { f.FieldList[f.curFieldListIndex].Options = options return f } func (f *FormPanel) FieldDefaultOptionDelimiter(delimiter string) *FormPanel { f.FieldList[f.curFieldListIndex].DefaultOptionDelimiter = delimiter return f } func (f *FormPanel) FieldPostFilterFn(post PostFieldFilterFn) *FormPanel { f.FieldList[f.curFieldListIndex].PostFilterFn = post return f } func (f *FormPanel) FieldNow() *FormPanel { f.FieldList[f.curFieldListIndex].PostFilterFn = func(value PostFieldModel) interface{} { return time.Now().Format("2006-01-02 15:04:05") } return f } func (f *FormPanel) FieldNowWhenUpdate() *FormPanel { f.FieldList[f.curFieldListIndex].PostFilterFn = func(value PostFieldModel) interface{} { if value.IsUpdate() { return time.Now().Format("2006-01-02 15:04:05") } return value.Value.Value() } return f } func (f *FormPanel) FieldNowWhenInsert() *FormPanel { f.FieldList[f.curFieldListIndex].PostFilterFn = func(value PostFieldModel) interface{} { if value.IsCreate() { return time.Now().Format("2006-01-02 15:04:05") } return value.Value.Value() } return f } func (f *FormPanel) FieldLimit(limit int) *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddLimit(limit) return f } func (f *FormPanel) FieldTrimSpace() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddTrimSpace() return f } func (f *FormPanel) FieldSubstr(start int, end int) *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddSubstr(start, end) return f } func (f *FormPanel) FieldToTitle() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddToTitle() return f } func (f *FormPanel) FieldToUpper() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddToUpper() return f } func (f *FormPanel) FieldToLower() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].AddToLower() return f } func (f *FormPanel) FieldXssFilter() *FormPanel { f.FieldList[f.curFieldListIndex].DisplayProcessChains = f.FieldList[f.curFieldListIndex].DisplayProcessChains. Add(func(value FieldModel) interface{} { return html.EscapeString(value.Value) }) return f } func (f *FormPanel) FieldCustomContent(content template.HTML) *FormPanel { f.FieldList[f.curFieldListIndex].CustomContent = content return f } func (f *FormPanel) FieldCustomJs(js template.JS) *FormPanel { f.FieldList[f.curFieldListIndex].CustomJs = js return f } func (f *FormPanel) FieldCustomCss(css template.CSS) *FormPanel { f.FieldList[f.curFieldListIndex].CustomCss = css return f } func (f *FormPanel) FieldOnSearch(url string, handler Handler, delay ...int) *FormPanel { ext, callback := searchJS(f.FieldList[f.curFieldListIndex].OptionExt, f.OperationURL(url), handler, delay...) f.FieldList[f.curFieldListIndex].OptionExt = ext f.Callbacks = f.Callbacks.AddCallback(callback) return f } func (f *FormPanel) FieldOnChooseCustom(js template.HTML) *FormPanel { f.FooterHtml += chooseCustomJS(f.FieldList[f.curFieldListIndex].Field, js) return f } type LinkField struct { Field string Value template.HTML Hide bool Disable bool } func (f *FormPanel) FieldOnChooseMap(m map[string]LinkField) *FormPanel { f.FooterHtml += chooseMapJS(f.FieldList[f.curFieldListIndex].Field, m) return f } func (f *FormPanel) FieldOnChoose(val, field string, value template.HTML) *FormPanel { f.FooterHtml += chooseJS(f.FieldList[f.curFieldListIndex].Field, field, val, value) return f } func (f *FormPanel) OperationURL(id string) string { return config.Url("/operation/" + utils.WrapURL(id)) } func (f *FormPanel) FieldOnChooseAjax(field, url string, handler Handler, custom ...template.HTML) *FormPanel { js, callback := chooseAjax(f.FieldList[f.curFieldListIndex].Field, field, f.OperationURL(url), handler, custom...) f.FooterHtml += js f.Callbacks = f.Callbacks.AddCallback(callback) return f } func (f *FormPanel) FieldOnChooseHide(value string, field ...string) *FormPanel { f.FooterHtml += chooseHideJS(f.FieldList[f.curFieldListIndex].Field, []string{value}, field...) return f } func (f *FormPanel) FieldOnChooseOptionsHide(values []string, field ...string) *FormPanel { f.FooterHtml += chooseHideJS(f.FieldList[f.curFieldListIndex].Field, values, field...) return f } func (f *FormPanel) FieldOnChooseShow(value string, field ...string) *FormPanel { f.FooterHtml += chooseShowJS(f.FieldList[f.curFieldListIndex].Field, []string{value}, field...) return f } func (f *FormPanel) FieldOnChooseOptionsShow(values []string, field ...string) *FormPanel { f.FooterHtml += chooseShowJS(f.FieldList[f.curFieldListIndex].Field, values, field...) return f } func (f *FormPanel) FieldOnChooseDisable(value string, field ...string) *FormPanel { f.FooterHtml += chooseDisableJS(f.FieldList[f.curFieldListIndex].Field, []string{value}, field...) return f } func (f *FormPanel) addFooterHTML(footer template.HTML) *FormPanel { f.FooterHtml += template.HTML(ParseTableDataTmpl(footer)) return f } func (f *FormPanel) AddCSS(css template.CSS) *FormPanel { return f.addFooterHTML(template.HTML("<style>" + css + "</style>")) } func (f *FormPanel) AddJS(js template.JS) *FormPanel { return f.addFooterHTML(template.HTML("<script>" + js + "</script>")) } func searchJS(ext template.JS, url string, handler Handler, delay ...int) (template.JS, context.Node) { delayStr := "500" if len(delay) > 0 { delayStr = strconv.Itoa(delay[0]) } if ext != template.JS("") { s := string(ext) s = strings.Replace(s, "{", "", 1) s = utils.ReplaceNth(s, "}", "", strings.Count(s, "}")) s = strings.TrimRight(s, " ") s += "," ext = template.JS(s) } return template.JS(`{ `) + ext + template.JS(` ajax: {     url: "`+url+`",     dataType: 'json',     data: function (params) {       var query = {         search: params.term, page: params.page || 1       }       return query;     },     delay: `+delayStr+`,     processResults: function (data, params) {       return data.data;     }   } }`), context.Node{ Path: url, Method: "get", Handlers: context.Handlers{handler.Wrap()}, Value: map[string]interface{}{constant.ContextNodeNeedAuth: 1}, } } func chooseCustomJS(field string, js template.HTML) template.HTML { return utils.ParseHTML("choose_custom", tmpls["choose_custom"], struct { Field template.JS JS template.JS }{Field: template.JS(field), JS: template.JS(js)}) } func chooseMapJS(field string, m map[string]LinkField) template.HTML { return utils.ParseHTML("choose_map", tmpls["choose_map"], struct { Field template.JS Data map[string]LinkField }{ Field: template.JS(field), Data: m, }) } func chooseJS(field, chooseField, val string, value template.HTML) template.HTML { return utils.ParseHTML("choose", tmpls["choose"], struct { Field template.JS ChooseField template.JS Val template.JS Value template.JS }{ Field: template.JS(field), ChooseField: template.JS(chooseField), Value: decorateChooseValue([]string{string(value)}), Val: decorateChooseValue([]string{string(val)}), }) } func chooseAjax(field, chooseField, url string, handler Handler, js ...template.HTML) (template.HTML, context.Node) { actionJS := template.HTML("") passValue := template.JS("") if len(js) > 0 { actionJS = js[0] } if len(js) > 1 { passValue = template.JS(js[1]) } return utils.ParseHTML("choose_ajax", tmpls["choose_ajax"], struct { Field template.JS ChooseField template.JS PassValue template.JS ActionJS template.JS Url template.JS }{ Url: template.JS(url), Field: template.JS(field), ChooseField: template.JS(chooseField), PassValue: passValue, ActionJS: template.JS(actionJS), }), context.Node{ Path: url, Method: "post", Handlers: context.Handlers{handler.Wrap()}, Value: map[string]interface{}{constant.ContextNodeNeedAuth: 1}, } } func chooseHideJS(field string, value []string, chooseFields ...string) template.HTML { if len(chooseFields) == 0 { return "" } return utils.ParseHTML("choose_hide", tmpls["choose_hide"], struct { Field template.JS Value template.JS ChooseFields []string }{ Field: template.JS(field), Value: decorateChooseValue(value), ChooseFields: chooseFields, }) } func chooseShowJS(field string, value []string, chooseFields ...string) template.HTML { if len(chooseFields) == 0 { return "" } return utils.ParseHTML("choose_show", tmpls["choose_show"], struct { Field template.JS Value template.JS ChooseFields []string }{ Field: template.JS(field), Value: decorateChooseValue(value), ChooseFields: chooseFields, }) } func chooseDisableJS(field string, value []string, chooseFields ...string) template.HTML { if len(chooseFields) == 0 { return "" } return utils.ParseHTML("choose_disable", tmpls["choose_disable"], struct { Field template.JS Value template.JS ChooseFields []string }{ Field: template.JS(field), Value: decorateChooseValue(value), ChooseFields: chooseFields, }) } func decorateChooseValue(val []string) template.JS { if len(val) == 0 { return "" } res := make([]string, len(val)) for k, v := range val { if v == "" { v = `""` } if v[0] != '"' { if strings.Contains(v, "$(this)") { res[k] = v } if v == "{{.vue}}" { res[k] = "$(this).v()" } if len(v) > 3 && v[:3] == "js:" { res[k] = v[3:] } res[k] = `"` + v + `"` } else { res[k] = v } } return template.JS("[" + strings.Join(res, ",") + "]") } // FormPanel attribute setting functions // ==================================================== func (f *FormPanel) SetTitle(title string) *FormPanel { f.Title = title return f } func (f *FormPanel) SetTabGroups(groups TabGroups) *FormPanel { f.TabGroups = groups return f } func (f *FormPanel) SetTabHeaders(headers ...string) *FormPanel { f.TabHeaders = headers return f } func (f *FormPanel) SetDescription(desc string) *FormPanel { f.Description = desc return f } func (f *FormPanel) SetHeaderHtml(header template.HTML) *FormPanel { f.HeaderHtml += header return f } func (f *FormPanel) SetFooterHtml(footer template.HTML) *FormPanel { f.FooterHtml += footer return f } func (f *FormPanel) HasError() bool { return f.PageError != nil } func (f *FormPanel) SetError(err errors.PageError, content ...template.HTML) *FormPanel { f.PageError = err if len(content) > 0 { f.PageErrorHTML = content[0] } return f } func (f *FormPanel) SetNoCompress() *FormPanel { f.NoCompress = true return f } func (f *FormPanel) Set404Error(content ...template.HTML) *FormPanel { f.SetError(errors.PageError404, content...) return f } func (f *FormPanel) Set403Error(content ...template.HTML) *FormPanel { f.SetError(errors.PageError403, content...) return f } func (f *FormPanel) Set400Error(content ...template.HTML) *FormPanel { f.SetError(errors.PageError401, content...) return f } func (f *FormPanel) Set500Error(content ...template.HTML) *FormPanel { f.SetError(errors.PageError500, content...) return f } func (f *FormPanel) SetLayout(layout form2.Layout) *FormPanel { f.Layout = layout return f } func (f *FormPanel) SetPostValidator(va FormPostFn) *FormPanel { f.Validator = va return f } func (f *FormPanel) SetPreProcessFn(fn FormPreProcessFn) *FormPanel { f.PreProcessFn = fn return f } func (f *FormPanel) SetHTMLContent(content template.HTML) *FormPanel { f.HTMLContent = content return f } func (f *FormPanel) SetHeader(content template.HTML) *FormPanel { f.Header = content return f } func (f *FormPanel) SetInputWidth(width int) *FormPanel { f.InputWidth = width return f } func (f *FormPanel) SetHeadWidth(width int) *FormPanel { f.HeadWidth = width return f } func (f *FormPanel) SetWrapper(wrapper ContentWrapper) *FormPanel { f.Wrapper = wrapper return f } func (f *FormPanel) SetHideSideBar() *FormPanel { f.HideSideBar = true return f } func (f *FormPanel) SetFormNewTitle(title template.HTML) *FormPanel { f.FormNewTitle = title return f } func (f *FormPanel) SetFormNewBtnWord(word template.HTML) *FormPanel { f.FormNewBtnWord = word return f } func (f *FormPanel) SetFormEditTitle(title template.HTML) *FormPanel { f.FormEditTitle = title return f } func (f *FormPanel) SetFormEditBtnWord(word template.HTML) *FormPanel { f.FormEditBtnWord = word return f } func (f *FormPanel) SetResponder(responder Responder) *FormPanel { f.Responder = responder return f } type AjaxData struct { SuccessTitle string SuccessText string ErrorTitle string ErrorText string SuccessJumpURL string DisableJump bool SuccessJS string JumpInNewTab string } func (f *FormPanel) EnableAjaxData(data AjaxData) *FormPanel { f.Ajax = true if f.AjaxSuccessJS == template.JS("") { successMsg := modules.AorB(data.SuccessTitle != "", `"`+data.SuccessTitle+`"`, "data.msg") errorMsg := modules.AorB(data.ErrorTitle != "", `"`+data.ErrorTitle+`"`, "data.msg") jump := modules.AorB(data.SuccessJumpURL != "", `"`+data.SuccessJumpURL+`"`, "data.data.url") text := modules.AorB(data.SuccessText != "", `text:"`+data.SuccessText+`",`, "") wrongText := modules.AorB(data.ErrorText != "", `text:"`+data.ErrorText+`",`, "text:data.msg,") jumpURL := "" if !data.DisableJump { if data.JumpInNewTab != "" { jumpURL = `listenerForAddNavTab(` + jump + `, "` + data.JumpInNewTab + `");` } jumpURL += `$.pjax({url: ` + jump + `, container: '#pjax-container'});` } else { jumpURL = ` if (data.data && data.data.token !== "") { $("input[name='__go_admin_t_']").val(data.data.token) }` } f.AjaxSuccessJS = template.JS(` if (typeof (data) === "string") { data = JSON.parse(data); } if (data.code === 200) { swal({ type: "success", title: ` + successMsg + `, ` + text + ` showCancelButton: false, confirmButtonColor: "#3c8dbc", confirmButtonText: '` + language.Get("got it") + `', }, function() { $(".modal-backdrop.fade.in").remove(); ` + jumpURL + ` ` + data.SuccessJS + ` }); } else { if (data.data && data.data.token !== "") { $("input[name='__go_admin_t_']").val(data.data.token); } swal({ type: "error", title: ` + errorMsg + `, ` + wrongText + ` showCancelButton: false, confirmButtonColor: "#3c8dbc", confirmButtonText: '` + language.Get("got it") + `', }) } `) } if f.AjaxErrorJS == template.JS("") { errorMsg := modules.AorB(data.ErrorTitle != "", `"`+data.ErrorTitle+`"`, "data.responseJSON.msg") error2Msg := modules.AorB(data.ErrorTitle != "", `"`+data.ErrorTitle+`"`, "'"+language.Get("error")+"'") wrongText := modules.AorB(data.ErrorText != "", `text:"`+data.ErrorText+`",`, "text:data.msg,") f.AjaxErrorJS = template.JS(` if (data.responseText !== "") { if (data.responseJSON.data && data.responseJSON.data.token !== "") { $("input[name='__go_admin_t_']").val(data.responseJSON.data.token) } swal({ type: "error", title: ` + errorMsg + `, ` + wrongText + ` showCancelButton: false, confirmButtonColor: "#3c8dbc", confirmButtonText: '` + language.Get("got it") + `', }) } else { swal({ type: "error", title: ` + error2Msg + `, ` + wrongText + ` showCancelButton: false, confirmButtonColor: "#3c8dbc", confirmButtonText: '` + language.Get("got it") + `', }) } `) } return f } func (f *FormPanel) EnableAjax(msgs ...string) *FormPanel { var data AjaxData if len(msgs) > 0 && msgs[0] != "" { data.SuccessTitle = msgs[0] } if len(msgs) > 1 && msgs[1] != "" { data.ErrorTitle = msgs[1] } if len(msgs) > 2 && msgs[2] != "" { data.SuccessJumpURL = msgs[2] } if len(msgs) > 3 && msgs[3] != "" { data.SuccessText = msgs[3] } if len(msgs) > 4 && msgs[4] != "" { data.ErrorText = msgs[4] } return f.EnableAjaxData(data) } func (f *FormPanel) SetAjaxSuccessJS(js template.JS) *FormPanel { f.AjaxSuccessJS = js return f } func (f *FormPanel) SetAjaxErrorJS(js template.JS) *FormPanel { f.AjaxErrorJS = js return f } func (f *FormPanel) SetPostHook(fn FormPostFn) *FormPanel { f.PostHook = fn return f } func (f *FormPanel) SetUpdateFn(fn FormPostFn) *FormPanel { f.UpdateFn = fn return f } func (f *FormPanel) SetInsertFn(fn FormPostFn) *FormPanel { f.InsertFn = fn return f } func (f *FormPanel) GroupFieldWithValue(pk, id string, columns []string, res map[string]interface{}, sql func() *db.SQL) ([]FormFields, []string) { var ( groupFormList = make([]FormFields, 0) groupHeaders = make([]string, 0) hasPK = false existField = make([]string, 0) ) if len(f.TabGroups) > 0 { for index, group := range f.TabGroups { list := make(FormFields, 0) for index, fieldName := range group { label := "_ga_group_" + strconv.Itoa(index) field := f.FieldList.FindByFieldName(fieldName) if field != nil && field.isNotBelongToATable() && !field.NotAllowEdit { if !field.Hide { field.Hide = field.EditHide } if field.FormType.IsTable() { for z := 0; z < len(field.TableFields); z++ { rowValue := field.TableFields[z].GetRawValue(columns, res[field.TableFields[z].Field]) if field.TableFields[z].Field == pk { hasPK = true } field.TableFields[z] = *(field.TableFields[z].UpdateValue(id, rowValue, res, sql())) } if utils.InArray(existField, field.Field) { field.Field = field.Field + label } list = append(list, *field) existField = append(existField, field.Field) } else { if field.Field == pk { hasPK = true } rowValue := field.GetRawValue(columns, res[field.Field]) if utils.InArray(existField, field.Field) { field.Field = field.Field + label } list = append(list, *(field.UpdateValue(id, rowValue, res, sql()))) existField = append(existField, field.Field) } } } groupFormList = append(groupFormList, list.FillCustomContent()) groupHeaders = append(groupHeaders, f.TabHeaders[index]) } if len(groupFormList) > 0 && !hasPK { groupFormList[len(groupFormList)-1] = groupFormList[len(groupFormList)-1].Add(&FormField{ Head: pk, FieldClass: pk, Field: pk, Value: template.HTML(id), Hide: true, }) } } return groupFormList, groupHeaders } func (f *FormPanel) GroupField(sql ...func() *db.SQL) ([]FormFields, []string) { var ( groupFormList = make([]FormFields, 0) groupHeaders = make([]string, 0) existField = make([]string, 0) ) for index, group := range f.TabGroups { list := make(FormFields, 0) for index, fieldName := range group { field := f.FieldList.FindByFieldName(fieldName) label := "_ga_group_" + strconv.Itoa(index) if field != nil && field.isNotBelongToATable() && field.allowAdd() { field.Editable = !field.DisplayButNotAdd if !field.Hide { field.Hide = field.CreateHide } if field.FormType.IsTable() { for z := 0; z < len(field.TableFields); z++ { if len(sql) > 0 { field.TableFields[z] = *(field.TableFields[z].UpdateDefaultValue(sql[0]())) } else { field.TableFields[z] = *(field.TableFields[z].UpdateDefaultValue(nil)) } } if utils.InArray(existField, field.Field) { field.Field = field.Field + label } list = append(list, *field) existField = append(existField, field.Field) } else { if utils.InArray(existField, field.Field) { field.Field = field.Field + label } if len(sql) > 0 { list = append(list, *(field.UpdateDefaultValue(sql[0]()))) } else { list = append(list, *(field.UpdateDefaultValue(nil))) } existField = append(existField, field.Field) } } } groupFormList = append(groupFormList, list.FillCustomContent()) groupHeaders = append(groupHeaders, f.TabHeaders[index]) } return groupFormList, groupHeaders } func (f *FormPanel) FieldsWithValue(pk, id string, columns []string, res map[string]interface{}, sql func() *db.SQL) FormFields { var ( list = make(FormFields, 0) hasPK = false ) for i := 0; i < len(f.FieldList); i++ { if !f.FieldList[i].NotAllowEdit { if !f.FieldList[i].Hide { f.FieldList[i].Hide = f.FieldList[i].EditHide } rowValue := f.FieldList[i].GetRawValue(columns, res[f.FieldList[i].Field]) if f.FieldList[i].FatherField != "" { f.FieldList.FindTableField(f.FieldList[i].Field, f.FieldList[i].FatherField).UpdateValue(id, rowValue, res, sql()) } else if f.FieldList[i].FormType.IsTable() { list = append(list, f.FieldList[i]) } else { list = append(list, *(f.FieldList[i].UpdateValue(id, rowValue, res, sql()))) } if f.FieldList[i].Field == pk { hasPK = true } } } if !hasPK { list = list.Add(&FormField{ Head: pk, FieldClass: pk, Field: pk, Value: template.HTML(id), FormType: form2.Default, Hide: true, }) } return list.FillCustomContent() } func (f *FormPanel) FieldsWithDefaultValue(sql ...func() *db.SQL) FormFields { var list = make(FormFields, 0) for i := 0; i < len(f.FieldList); i++ { if f.FieldList[i].allowAdd() { f.FieldList[i].Editable = !f.FieldList[i].DisplayButNotAdd if !f.FieldList[i].Hide { f.FieldList[i].Hide = f.FieldList[i].CreateHide } if f.FieldList[i].FatherField != "" { if len(sql) > 0 { f.FieldList.FindTableField(f.FieldList[i].Field, f.FieldList[i].FatherField).UpdateDefaultValue(sql[0]()) } else { f.FieldList.FindTableField(f.FieldList[i].Field, f.FieldList[i].FatherField).UpdateDefaultValue(nil) } } else if f.FieldList[i].FormType.IsTable() { list = append(list, f.FieldList[i]) } else { if len(sql) > 0 { list = append(list, *(f.FieldList[i].UpdateDefaultValue(sql[0]()))) } else { list = append(list, *(f.FieldList[i].UpdateDefaultValue(nil))) } } } } return list.FillCustomContent().RemoveNotShow() } func (f *FormPanel) GetNewFormFields(sql ...func() *db.SQL) (FormFields, []FormFields, []string) { if len(f.TabGroups) > 0 { tabFields, tabHeaders := f.GroupField(sql...) return make(FormFields, 0), tabFields, tabHeaders } return f.FieldsWithDefaultValue(sql...), make([]FormFields, 0), make([]string, 0) } type ( FormPreProcessFn func(values form.Values) form.Values FormPostFn func(values form.Values) error FormFields []FormField GroupFormFields []FormFields GroupFieldHeaders []string ) func (f FormFields) Copy() FormFields { formList := make(FormFields, len(f)) copy(formList, f) for i := 0; i < len(formList); i++ { formList[i].Options = make(FieldOptions, len(f[i].Options)) for j := 0; j < len(f[i].Options); j++ { formList[i].Options[j] = FieldOption{ Value: f[i].Options[j].Value, Text: f[i].Options[j].Text, TextHTML: f[i].Options[j].TextHTML, Selected: f[i].Options[j].Selected, } } } return formList } func (f FormFields) FindByFieldName(field string) *FormField { for i := 0; i < len(f); i++ { if f[i].Field == field { return &f[i] } } return nil } func (f FormFields) FindIndexByFieldName(field string) int { for i := 0; i < len(f); i++ { if f[i].Field == field { return i } } return -1 } func (f FormFields) FindTableField(field, father string) *FormField { ff := f.FindByFieldName(father) return ff.TableFields.FindByFieldName(field) } func (f FormFields) FindTableChildren(father string) []*FormField { list := make([]*FormField, 0) for i := 0; i < len(f); i++ { if f[i].FatherField == father { list = append(list, &f[i]) } } return list } func (f FormFields) FillCustomContent() FormFields { for i := range f { if f[i].FormType.IsCustom() { f[i] = *(f[i]).FillCustomContent() } } return f } func (f FormFields) Add(field *FormField) FormFields { return append(f, *field) } func (f FormFields) RemoveNotShow() FormFields { ff := f for i := 0; i < len(ff); { if ff[i].FatherFormType == form2.Table { ff = append(ff[:i], ff[i+1:]...) } else { i++ } } return ff }
/* You have an array of item codes with the following format: "[letters][digits]" Create a function that splits these strings into their alphabetic and numeric parts. */ package main import ( "fmt" "unicode" ) func main() { fmt.Println(splitcode("TEWA8392")) fmt.Println(splitcode("MMU778")) fmt.Println(splitcode("SRPE5532")) fmt.Println(splitcode("SKU8977")) fmt.Println(splitcode("MCI5589")) fmt.Println(splitcode("WIEB3921")) } func splitcode(s string) [2]string { var c [2]string for i, r := range s { if unicode.IsDigit(r) { c = [2]string{s[:i], s[i:]} break } } return c }
package jwtcontroller import ( "errors" "strings" "time" "github.com/GlitchyGlitch/typinger/config" "github.com/dgrijalva/jwt-go" ) var ( ErrInvalidHeader = errors.New("invalid authorization header") ErrInvalidToken = errors.New("invalid token") ) const prefix = "Bearer " type JWTController struct { Config *config.Config } func New(config *config.Config) *JWTController { c := &JWTController{Config: config} return c } func (c JWTController) Token(id string) (string, error) { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["sub"] = id claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // TODO: Add as config to config struct rawToken, err := token.SignedString(c.Config.JWTSecret) if err != nil { return "", err } return rawToken, nil } func (c JWTController) ParseAuthorization(header string) (map[string]interface{}, error) { if !strings.HasPrefix(header, prefix) { return nil, ErrInvalidHeader } rawToken := header[len(prefix):] token, err := jwt.Parse(rawToken, func(token *jwt.Token) (interface{}, error) { return c.Config.JWTSecret, nil }) if err != nil { return nil, ErrInvalidToken } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { return nil, ErrInvalidToken } return claims, err }
package cmd import ( "testing" "github.com/stretchr/testify/assert" ) func TestRootCmdShouldHaveNonEmptyUse(t *testing.T) { assert.NotEqual(t, "", rootCmd.Use) } func TestRootCmdShouldHaveNonEmptyShort(t *testing.T) { assert.NotEqual(t, "", rootCmd.Short) } func TestRootCmdShouldHaveNonEmptyLong(t *testing.T) { assert.NotEqual(t, "", rootCmd.Long) } func TestRootCmdShouldHaveNonEmptyVersion(t *testing.T) { assert.NotEqual(t, "", rootCmd.Version) }
package main import "sync" type intLocker struct { m *sync.Mutex intM map[int]*sync.Mutex } func newIntLocker() *intLocker { return &intLocker{ m: &sync.Mutex{}, intM: map[int]*sync.Mutex{}, } } func (il *intLocker) get(i int) *sync.Mutex { il.m.Lock() defer il.m.Unlock() intM, ok := il.intM[i] if !ok { intM = &sync.Mutex{} il.intM[i] = intM } return intM } func (il *intLocker) lock(i int) { il.get(i).Lock() } func (il *intLocker) unlock(i int) { il.get(i).Unlock() }
/* Slavko is learning about different numeral systems. Slavko is not the brightest when it comes to math, so he is starting out converting binary numerals to octal. The algorithm Slavko uses is this: Pad the binary numeral with zeros on the left until the number of digits is divisible by three. Group adjacent binary digits into groups of 3 digits. Replace each group of binary digits with the corresponding octal digit (as in Table 1). 000 0 001 1 010 2 011 3 100 4 101 5 110 6 111 7 Table 1: Binary to octal Write a program that converts a binary numeral to octal so that Slavko can verify his results. Input The input contains a binary numeral. The number of digits will be less than 100, and the first digit will be 1. Output Output the number in octal. */ package main func main() { assert(octal(0b1010) == 12) assert(octal(0b11001100) == 314) } func assert(x bool) { if !x { panic("assertion failed") } } func octal(n uint) uint { var x, y uint for ; n != 0; n /= 8 { x = (x * 10) + (n % 8) } for ; x != 0; x /= 10 { y = (y * 10) + (x % 10) } return y }
package ssvgc import ( "image/color" "testing" ) func TestColorFromPaintToken(t *testing.T) { var tests = []struct { in string out color.Color }{ {"red", color.RGBA{0xff, 0, 0, 0xff}}, {"#fff", color.RGBA{0xff, 0xff, 0xff, 0xff}}, {"#fe0000", color.RGBA{0xfe, 00, 00, 0xff}}, {"none", color.Transparent}, {"qwerty", color.Black}, } for _, tt := range tests { col := colorFromPaintToken(tt.in) r, g, b, a := col.RGBA() rr, gg, bb, aa := tt.out.RGBA() if r != rr || g != gg || b != bb || a != aa { t.Errorf("colorFromPaintToken(%q) => %v, expected %v", tt.in, col, tt.out) } } }
package p9p import ( "context" "io" "net" "testing" "time" ) const realPlan9 = "1.1.1.1:808" func ckHasPlan9(t *testing.T) { t.Helper() if realPlan9 == "" { t.Skip("no real plan9 defined") } result := make(chan error) ctx, fn := context.WithTimeout(context.Background(), time.Second) defer fn() go func() { dialer := net.Dialer{} conn, err := dialer.DialContext(ctx, "tcp", realPlan9) result <- err if err == nil { conn.Close() } }() select { case <-ctx.Done(): case err := <-result: if err == nil { return } } t.Skip("plan9 isn't responding here:", realPlan9) } func TestPlan9Version(t *testing.T) { testPlan9Version(t) } // The server should run the equivalent of // aux/listen1 -t -v tcp!*!808 exportfs -r / func testPlan9Version(t *testing.T) *Conn { t.Helper() ckHasPlan9(t) conn, err := Dial("tcp", realPlan9) if err != nil { t.Fatal(err) } iounit, version, err := conn.Ver() t.Logf("iounit, version: %v, %v\n", iounit, version) if err != nil { t.Fatal(err) } return conn } func TestPlan9WalkWrite(t *testing.T) { conn := testPlan9Version(t) qid, err := conn.Attach(1, NoFid, "none", "/tmp") if err != nil { t.Fatal(err) } qid, iounit, err := conn.Create(1, "testglenda4.txt", 0, 0) t.Logf("qid, iounit, err %v %v %v\n", qid, iounit, err) if err != nil { t.Fatal(err) } p := make([]byte, iounit) n, err := conn.WriteFid(2, 0, p) t.Logf("n, err, p %v %v %v\n", n, err, p) if err != nil { t.Fatal(err) } } func TestPlan9WalkReadNdb(t *testing.T) { conn := testPlan9Version(t) qid, err := conn.Attach(1, NoFid, "none", "/") if err != nil { t.Fatal(err) } t.Logf("qid is %#v\n", qid) q, err := conn.Walk(1, 2, "/", "lib", "ndb", "local") t.Logf("quids, err %v %v\n", q, err) if err != nil { t.Fatal(err) } qid, iounit, err := conn.Open(2, 0) t.Logf("qid, iounit, err %v %v %v\n", qid, iounit, err) if err != nil { t.Fatal(err) } p := make([]byte, iounit) n, err := conn.ReadFid(2, 0, p) t.Logf("n, err, p %v %v %v\n", n, err, p) if err != io.EOF && err != nil { t.Fatal(err) } } func TestPlan9Create(t *testing.T) { conn := testPlan9Version(t) qid, err := conn.Attach(1, NoFid, "none", "/") if err != nil { t.Fatal(err) } t.Logf("qid is %#v\n", qid) qid, iounit, err := conn.Create(1, "glend4.txt", 0, 0) t.Logf("qid, iounit, err %v %v %v\n", qid, iounit, err) if err != nil { t.Fatal(err) } } func TestPlan9Flush(t *testing.T) { conn := testPlan9Version(t) err := conn.Flush(0xffff) if err != nil { t.Fatalf("error: %s\n", err) } } func TestPlan9Error(t *testing.T) { t.Skip("client doesnt send errors to server") conn := testPlan9Version(t) err := conn.Error("because") if err != nil { t.Fatalf("error %s", err) } }
package controllers import ( "GoldenTimes-web/forms" "GoldenTimes-web/models" "GoldenTimes-web/orm" "GoldenTimes-web/request" "GoldenTimes-web/response" "encoding/json" "strconv" "github.com/astaxie/beego" ) type AlbumController struct { beego.Controller } func (c *AlbumController) URLMapping() { c.Mapping("CreateAlbum", c.CreateAlbum) c.Mapping("ReadAlbums", c.ReadAlbums) c.Mapping("ReadAlbum", c.ReadAlbum) c.Mapping("UpdateAlbum", c.UpdateAlbum) c.Mapping("DeleteAlbum", c.DeleteAlbum) } // @router /album [post] func (this *AlbumController) CreateAlbum() { beego.Trace("CreateAlbum") rsp := new(response.Response) var album models.Album err := json.Unmarshal(this.Ctx.Input.RequestBody, &album) if err == nil { beego.Trace("Released", album.Released) _, err := orm.CreateAlbum(&album) //num, err if err == nil { rsp.Data = album } else { e := new(response.Error) e.Code = 2 e.Message = err.Error() rsp.Error = e } } else { e := new(response.Error) e.Code = 2 e.Message = err.Error() rsp.Error = e } this.Data["json"] = rsp this.ServeJson() } // @router /album [get] func (this *AlbumController) ReadAlbums() { beego.Trace("ReadAlbums") rsp := new(response.Response) form := forms.ReadAlbumsForm{} if err := this.ParseForm(&form); err == nil { beego.Trace("form:", form) count, num, albums, err := orm.ReadAlbums(form.AlbumName, form.AlbumType, form.AlbumReleasedBegin, form.AlbumReleasedEnd, form.Limit, form.Offset) if err == nil { data := new(response.Data) data.Count = count data.Num = num data.Limit = form.Limit data.Offset = form.Offset data.Items = make([]interface{}, len(albums)) for i, v := range albums { data.Items[i] = v } rsp.Data = data } else { } } else { //handle error beego.Trace("err:", err) e := new(response.Error) e.Code = 3 rsp.Error = e } this.Data["json"] = rsp this.ServeJson() } // @router /album/:id [get] func (this *AlbumController) ReadAlbum() { beego.Trace("ReadAlbum") rsp := new(response.Response) id := this.Ctx.Input.Param(":id") intValue, err := strconv.ParseInt(id, 10, 64) beego.Trace("intValue", intValue) if err == nil { album := models.Album{Id: intValue} err := orm.ReadAlbum(&album) if err == nil { rsp.Data = album } else { err := new(response.Error) err.Code = response.ERROR_CODE_DATABASE rsp.Error = err } } else { err := new(response.Error) err.Code = response.ERROR_CODE_PARAMS rsp.Error = err } this.Data["json"] = rsp this.ServeJson() } // @router /album/:id [put] func (this *AlbumController) UpdateAlbum() { beego.Trace("UpdateAlbum") rsp := new(response.Response) id := this.Ctx.Input.Param(":id") intValue, err := strconv.ParseInt(id, 10, 64) beego.Trace("id", id) beego.Trace("intValue", intValue) if err == nil { var album models.Album err := json.Unmarshal(this.Ctx.Input.RequestBody, &album) if err == nil { album.Id = intValue num, err := orm.UpdateAlbum(&album) beego.Trace("Update num", num) beego.Trace("Update err", err) if err == nil { rsp.Data = album } else { err := new(response.Error) err.Code = response.ERROR_CODE_DATABASE rsp.Error = err } } else { e := new(response.Error) e.Code = response.ERROR_CODE_PARAMS e.Message = err.Error() rsp.Error = e } } else { e := new(response.Error) e.Code = response.ERROR_CODE_PARAMS e.Message = err.Error() rsp.Error = e } this.Data["json"] = rsp this.ServeJson() } // @router /album/:id [delete] func (this *AlbumController) DeleteAlbum() { beego.Trace("DeleteAlbum") rsp := new(response.Response) id := this.Ctx.Input.Param(":id") beego.Trace("id", id) intValue, err := strconv.ParseInt(id, 10, 64) beego.Trace("intValue", intValue) if err == nil { album := models.Album{Id: intValue} orm.ReadAlbum(&album) num, err := orm.DeleteAlbum(&album) beego.Trace("Delete num", num) beego.Trace("Delete err", err) if err == nil { rsp.Data = true } else { err := new(response.Error) err.Code = response.ERROR_CODE_DATABASE rsp.Error = err } } else { err := new(response.Error) err.Code = response.ERROR_CODE_PARAMS rsp.Error = err } this.Data["json"] = rsp this.ServeJson() } // @router /albums/:albumId/artists [put] func (this *AlbumController) AlbumPutArtists() { beego.Trace("AlbumPutArtists") rsp := new(response.Response) stringAlbumId := this.Ctx.Input.Param(":albumId") int64AlbumId, errAlbumId := strconv.ParseInt(stringAlbumId, 10, 64) beego.Trace("int64AlbumId", int64AlbumId) var req request.AlbumPutArtistsRequest err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) beego.Trace("req", req) if errAlbumId == nil && err == nil { num, err := orm.AlbumPutArtists(int64AlbumId, req.Artists) beego.Trace("num", num) if err == nil { } else { } } else { } this.Data["json"] = rsp this.ServeJson() } // @router /albums/:albumId/artists [delete] func (this *AlbumController) AlbumDeleteArtists() { beego.Trace("AlbumDeleteArtists") rsp := new(response.Response) stringAlbumId := this.Ctx.Input.Param(":albumId") int64AlbumId, errAlbumId := strconv.ParseInt(stringAlbumId, 10, 64) beego.Trace("int64AlbumId", int64AlbumId) var req request.AlbumDeleteArtistsRequest err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) beego.Trace("req", req) if errAlbumId == nil && err == nil { num, err := orm.AlbumDeleteArtists(int64AlbumId, req.Artists) beego.Trace("num", num) if err == nil { } else { } } else { } this.Data["json"] = rsp this.ServeJson() } // @router /albums/:albumId/artists/:artistId [put] func (this *AlbumController) AlbumPutArtist() { beego.Trace("AlbumPutArtist") rsp := new(response.Response) stringAlbumId := this.Ctx.Input.Param(":albumId") int64AlbumId, errAlbumId := strconv.ParseInt(stringAlbumId, 10, 64) beego.Trace("int64AlbumId", int64AlbumId) stringArtistId := this.Ctx.Input.Param(":artistId") int64ArtistId, errArtistId := strconv.ParseInt(stringArtistId, 10, 64) beego.Trace("int64ArtistId", int64ArtistId) if errAlbumId == nil && errArtistId == nil { num, err := orm.AlbumPutArtist(int64AlbumId, int64ArtistId) beego.Trace("num", num) if err == nil { } else { } } else { } this.Data["json"] = rsp this.ServeJson() } // @router /albums/:albumId/artists/:artistId [delete] func (this *AlbumController) AlbumDeleteArtist() { beego.Trace("AlbumDeleteArtist") rsp := new(response.Response) stringAlbumId := this.Ctx.Input.Param(":albumId") int64AlbumId, errAlbumId := strconv.ParseInt(stringAlbumId, 10, 64) beego.Trace("int64AlbumId", int64AlbumId) stringArtistId := this.Ctx.Input.Param(":artistId") int64ArtistId, errArtistId := strconv.ParseInt(stringArtistId, 10, 64) beego.Trace("int64ArtistId", int64ArtistId) if errAlbumId == nil && errArtistId == nil { num, err := orm.AlbumDeleteArtist(int64AlbumId, int64ArtistId) beego.Trace("num", num) if err == nil { } else { } } else { } this.Data["json"] = rsp this.ServeJson() }
package binary_search_tree_to_greater_sum_tree import ( "github.com/stretchr/testify/assert" "testing" ) func Test_BstToGst(t *testing.T) { input := &TreeNode{ Val: 4, Left: &TreeNode{ Val: 1, Left: &TreeNode{ Val: 0, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 2, Left: nil, Right: &TreeNode{ Val: 3, Left: nil, Right: nil, }, }, }, Right: &TreeNode{ Val: 6, Left: &TreeNode{ Val: 5, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 7, Left: nil, Right: &TreeNode{ Val: 8, Left: nil, Right: nil, }, }, }, } output := &TreeNode{ Val: 30, Left: &TreeNode{ Val: 36, Left: &TreeNode{ Val: 36, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 35, Left: nil, Right: &TreeNode{ Val: 33, Left: nil, Right: nil, }, }, }, Right: &TreeNode{ Val: 21, Left: &TreeNode{ Val: 26, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 15, Left: nil, Right: &TreeNode{ Val: 8, Left: nil, Right: nil, }, }, }, } assert.Equal(t, output, bstToGst(input)) }
package handlers_test import ( "net/http" "strconv" "testing" "github.com/jchprj/GeoOrderTest/api/handlers" "github.com/jchprj/GeoOrderTest/cfg" "github.com/jchprj/GeoOrderTest/mgr" ) type request struct { start, end []string expectedCode int expectedError string } func BenchmarkPlaceHandler(b *testing.B) { for i := 0; i < b.N; i++ { handlers.PostStrings([]string{"12", ""}, []string{"667", ""}) } } func TestPlaceHandler(t *testing.T) { cfg.InitConfig("../../docker/config.yml") mgr.InitMgr() autoID := mgr.GetCurrentAutoID() t.Logf("start autoID: %v", autoID) //multiple JSON request test tt := []request{ { []string{"+90.0", "-127.554334"}, []string{"+90.0", "-127.554334"}, http.StatusOK, `{"id":` + strconv.FormatInt(autoID+1, 10) + `,"distance":0,"status":"UNASSIGNED"}`, }, { []string{"45", "180"}, []string{"+90.0", "-127.554334"}, http.StatusOK, `{"id":` + strconv.FormatInt(autoID+2, 10) + `,"distance":0,"status":"UNASSIGNED"}`, }, { []string{"+90.0", "-127.554334"}, []string{"+90.0", "-127.554334"}, http.StatusOK, `{"id":` + strconv.FormatInt(autoID+3, 10) + `,"distance":0,"status":"UNASSIGNED"}`, }, { []string{"+90.0", "-127.554334"}, []string{"+90.0", "-127.554334"}, http.StatusOK, `{"id":` + strconv.FormatInt(autoID+4, 10) + `,"distance":0,"status":"UNASSIGNED"}`}, { []string{"heap", "-127.554334"}, []string{"+90.0", "-127.554334"}, http.StatusBadRequest, `{"error":"ERROR_DESCRIPTION"}`, }, { []string{"+90.0", "-127.554334"}, []string{"", ""}, http.StatusBadRequest, `{"error":"ERROR_DESCRIPTION"}`, }, { []string{"+90.0"}, []string{""}, http.StatusBadRequest, `{"error":"ERROR_DESCRIPTION"}`, }, } for _, tc := range tt { rr, err := handlers.PostStrings(tc.start, tc.end) if err != nil { t.Fatal(err) } handlers.CheckResponse(rr, tc.expectedCode, tc.expectedError, t) } //single string test rr, err := handlers.PostString([]byte("abc")) if err != nil { t.Fatal(err) } handlers.CheckResponse(rr, http.StatusBadRequest, `{"error":"INVALID_PARAMETERS"}`, t) }
package e2e import ( . "github.com/onsi/ginkgo" . "sigs.k8s.io/multi-tenancy/incubator/hnc/pkg" ) var _ = Describe("Demo", func() { // Test for https://docs.google.com/document/d/1tKQgtMSf0wfT3NOGQx9ExUQ-B8UkkdVZB6m4o3Zqn64 const ( nsOrg = "acme-org" nsTeamA = "team-a" nsTeamB = "team-b" nsService1 = "service-1" ) BeforeEach(func(){ CleanupNamespaces(nsOrg, nsTeamA, nsTeamB, nsService1) }) AfterEach(func(){ CleanupNamespaces(nsOrg, nsTeamA, nsTeamB, nsService1) }) It("Should test basic functionalities in demo", func(){ MustRun("kubectl create ns", nsOrg) MustRun("kubectl create ns", nsTeamA) MustRun("kubectl create ns", nsService1) MustRun("kubectl -n", nsTeamA, "create role", nsTeamA+"-sre", "--verb=update --resource=deployments") MustRun("kubectl -n", nsTeamA, "create rolebinding", nsTeamA+"-sres", "--role", nsTeamA+"-sre", "--serviceaccount="+nsTeamA+":default") MustRun("kubectl -n", nsOrg, "create role", nsOrg+"-sre", "--verb=update --resource=deployments") MustRun("kubectl -n", nsOrg, "create rolebinding", nsOrg+"-sres", "--role", nsOrg+"-sre", "--serviceaccount="+nsOrg+":default") // none of this affects service-1 RunShouldContain("No resources found in "+nsService1, 1, "kubectl -n", nsService1, "get rolebindings") // make acme-org the parent of team-a, and team-a the parent of service-1. MustRun("kubectl hns set", nsTeamA, "--parent", nsOrg) MustRun("kubectl hns set", nsService1, "--parent", nsTeamA) // This won't work, will be rejected since it would cause a cycle MustNotRun("kubectl hns set", nsOrg, "--parent", nsTeamA) // verify the tree RunShouldContain(nsTeamA, 5, "kubectl hns describe", nsOrg) RunShouldContain(nsService1, 5, "kubectl hns describe", nsTeamA) // Now, if we check service-1 again, we’ll see all the rolebindings we expect: RunShouldContainMultiple([]string{"hnc.x-k8s.io/inheritedFrom=acme-org", "hnc.x-k8s.io/inheritedFrom=team-a"}, 5, "kubectl -n", nsService1, "describe roles") RunShouldContainMultiple([]string{"Role/acme-org-sre", "Role/team-a-sre"}, 5, "kubectl -n", nsService1, "get rolebindings") MustRun("kubectl hns create", nsTeamB, "-n", nsOrg) MustRun("kubectl get ns", nsTeamB) RunShouldContainMultiple([]string{nsTeamA, nsTeamB, nsService1}, 5, "kubectl hns tree", nsOrg) // set up roles in team-b MustRun("kubectl -n", nsTeamB, "create role", nsTeamB+"-wizard", "--verb=update --resource=deployments") MustRun("kubectl -n", nsTeamB, "create rolebinding", nsTeamB+"-wizards", "--role", nsTeamB+"-wizard", "--serviceaccount="+nsTeamB+":default") // assign the service to the new team, and check that all the RBAC roles get updated MustRun("kubectl hns set", nsService1, "--parent", nsTeamB) RunShouldNotContain(nsService1, 5, "kubectl hns describe", nsTeamA) RunShouldContain(nsService1, 5, "kubectl hns describe", nsTeamB) RunShouldContain(nsTeamB+"-wizard", 5, "kubectl -n", nsService1, "get roles") RunShouldNotContain(nsTeamA+"-wizard", 5, "kubectl -n", nsService1, "get roles") }) })
package cfrida func Frida_session_get_pid(obj uintptr) int { r, _, _ := frida_session_get_pid.Call(obj) return int(r) } func Frida_session_get_persist_timeout(obj uintptr) int { r, _, _ := frida_session_get_persist_timeout.Call(obj) return int(r) } func Frida_session_is_detached(obj uintptr) bool { r, _, _ := frida_session_is_detached.Call(obj) return r!=0 } func Frida_session_detach_sync(obj uintptr,cancellable uintptr)error{ gerr:=MakeGError() frida_session_detach_sync.Call(obj,cancellable,gerr.Input()) return gerr.ToError() } func Frida_session_create_script_sync(obj uintptr,source string,ops uintptr,cancellable uintptr)(uintptr,error){ gerr:=MakeGError() r,_,_:=frida_session_create_script_sync.Call(obj,GoStrToCStr(source),ops,cancellable,gerr.Input()) return r,gerr.ToError() } func Frida_session_create_script_from_bytes_sync(obj uintptr,source []byte,ops uintptr,cancellable uintptr)(uintptr,error){ gerr:=MakeGError() bt:=G_bytes_new(source) defer G_bytes_unref(bt) r,_,_:=frida_session_create_script_from_bytes_sync.Call(obj,bt,ops,cancellable,gerr.Input()) return r,gerr.ToError() } func Frida_session_compile_script_sync(obj uintptr,source string,ops uintptr,cancellable uintptr)([]byte,error){ gerr:=MakeGError() r,_,_:=frida_session_compile_script_sync.Call(obj,GoStrToCStr(source),ops,cancellable,gerr.Input()) return G_bytes_to_bytes_and_unref(r),gerr.ToError() } func Frida_session_enable_debugger_sync(obj uintptr,port int,cancellable uintptr)error{ gerr:=MakeGError() frida_session_enable_debugger_sync.Call(obj, uintptr(port),cancellable,gerr.Input()) return gerr.ToError() } func Frida_session_disable_debugger_sync(obj uintptr,cancellable uintptr)error{ gerr:=MakeGError() frida_session_disable_debugger_sync.Call(obj, cancellable,gerr.Input()) return gerr.ToError() } func Frida_session_setup_peer_connection_sync(obj uintptr,ops uintptr,cancellable uintptr)error{ gerr:=MakeGError() frida_session_setup_peer_connection_sync.Call(obj,ops, cancellable,gerr.Input()) return gerr.ToError() } func Frida_relay_new(address,username,password string,kind int)uintptr{ r,_,_:=frida_relay_new.Call(GoStrToCStr(address),GoStrToCStr(username),GoStrToCStr(password), uintptr(kind)) return r } func Frida_relay_get_address(obj uintptr)string{ r,_,_:=frida_relay_get_address.Call(obj) return CStrToGoStr(r) }
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. 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. // Code generated from the elasticsearch-specification DO NOT EDIT. // https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2 // Returns settings for one or more indices. package getsettings import ( gobytes "bytes" "context" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "github.com/elastic/elastic-transport-go/v8/elastictransport" "github.com/elastic/go-elasticsearch/v8/typedapi/types" "github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/expandwildcard" ) const ( indexMask = iota + 1 nameMask ) // ErrBuildPath is returned in case of missing parameters within the build of the request. var ErrBuildPath = errors.New("cannot build path, check for missing path parameters") type GetSettings struct { transport elastictransport.Interface headers http.Header values url.Values path url.URL buf *gobytes.Buffer paramSet int index string name string } // NewGetSettings type alias for index. type NewGetSettings func() *GetSettings // NewGetSettingsFunc returns a new instance of GetSettings with the provided transport. // Used in the index of the library this allows to retrieve every apis in once place. func NewGetSettingsFunc(tp elastictransport.Interface) NewGetSettings { return func() *GetSettings { n := New(tp) return n } } // Returns settings for one or more indices. // // https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-get-settings.html func New(tp elastictransport.Interface) *GetSettings { r := &GetSettings{ transport: tp, values: make(url.Values), headers: make(http.Header), buf: gobytes.NewBuffer(nil), } return r } // HttpRequest returns the http.Request object built from the // given parameters. func (r *GetSettings) HttpRequest(ctx context.Context) (*http.Request, error) { var path strings.Builder var method string var req *http.Request var err error r.path.Scheme = "http" switch { case r.paramSet == 0: path.WriteString("/") path.WriteString("_settings") method = http.MethodGet case r.paramSet == indexMask: path.WriteString("/") path.WriteString(r.index) path.WriteString("/") path.WriteString("_settings") method = http.MethodGet case r.paramSet == indexMask|nameMask: path.WriteString("/") path.WriteString(r.index) path.WriteString("/") path.WriteString("_settings") path.WriteString("/") path.WriteString(r.name) method = http.MethodGet case r.paramSet == nameMask: path.WriteString("/") path.WriteString("_settings") path.WriteString("/") path.WriteString(r.name) method = http.MethodGet } r.path.Path = path.String() r.path.RawQuery = r.values.Encode() if r.path.Path == "" { return nil, ErrBuildPath } if ctx != nil { req, err = http.NewRequestWithContext(ctx, method, r.path.String(), r.buf) } else { req, err = http.NewRequest(method, r.path.String(), r.buf) } req.Header = r.headers.Clone() if req.Header.Get("Accept") == "" { req.Header.Set("Accept", "application/vnd.elasticsearch+json;compatible-with=8") } if err != nil { return req, fmt.Errorf("could not build http.Request: %w", err) } return req, nil } // Perform runs the http.Request through the provided transport and returns an http.Response. func (r GetSettings) Perform(ctx context.Context) (*http.Response, error) { req, err := r.HttpRequest(ctx) if err != nil { return nil, err } res, err := r.transport.Perform(req) if err != nil { return nil, fmt.Errorf("an error happened during the GetSettings query execution: %w", err) } return res, nil } // Do runs the request through the transport, handle the response and returns a getsettings.Response func (r GetSettings) Do(ctx context.Context) (Response, error) { response := NewResponse() res, err := r.Perform(ctx) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode < 299 { err = json.NewDecoder(res.Body).Decode(&response) if err != nil { return nil, err } return response, nil } errorResponse := types.NewElasticsearchError() err = json.NewDecoder(res.Body).Decode(errorResponse) if err != nil { return nil, err } if errorResponse.Status == 0 { errorResponse.Status = res.StatusCode } return nil, errorResponse } // IsSuccess allows to run a query with a context and retrieve the result as a boolean. // This only exists for endpoints without a request payload and allows for quick control flow. func (r GetSettings) IsSuccess(ctx context.Context) (bool, error) { res, err := r.Perform(ctx) if err != nil { return false, err } io.Copy(ioutil.Discard, res.Body) err = res.Body.Close() if err != nil { return false, err } if res.StatusCode >= 200 && res.StatusCode < 300 { return true, nil } return false, nil } // Header set a key, value pair in the GetSettings headers map. func (r *GetSettings) Header(key, value string) *GetSettings { r.headers.Set(key, value) return r } // Index Comma-separated list of data streams, indices, and aliases used to limit // the request. Supports wildcards (`*`). To target all data streams and // indices, omit this parameter or use `*` or `_all`. // API Name: index func (r *GetSettings) Index(index string) *GetSettings { r.paramSet |= indexMask r.index = index return r } // Name Comma-separated list or wildcard expression of settings to retrieve. // API Name: name func (r *GetSettings) Name(name string) *GetSettings { r.paramSet |= nameMask r.name = name return r } // AllowNoIndices If `false`, the request returns an error if any wildcard expression, index // alias, or `_all` value targets only missing or closed indices. This // behavior applies even if the request targets other open indices. For // example, a request targeting `foo*,bar*` returns an error if an index // starts with foo but no index starts with `bar`. // API name: allow_no_indices func (r *GetSettings) AllowNoIndices(allownoindices bool) *GetSettings { r.values.Set("allow_no_indices", strconv.FormatBool(allownoindices)) return r } // ExpandWildcards Type of index that wildcard patterns can match. // If the request can target data streams, this argument determines whether // wildcard expressions match hidden data streams. // Supports comma-separated values, such as `open,hidden`. // API name: expand_wildcards func (r *GetSettings) ExpandWildcards(expandwildcards ...expandwildcard.ExpandWildcard) *GetSettings { tmp := []string{} for _, item := range expandwildcards { tmp = append(tmp, item.String()) } r.values.Set("expand_wildcards", strings.Join(tmp, ",")) return r } // FlatSettings If `true`, returns settings in flat format. // API name: flat_settings func (r *GetSettings) FlatSettings(flatsettings bool) *GetSettings { r.values.Set("flat_settings", strconv.FormatBool(flatsettings)) return r } // IgnoreUnavailable If `false`, the request returns an error if it targets a missing or closed // index. // API name: ignore_unavailable func (r *GetSettings) IgnoreUnavailable(ignoreunavailable bool) *GetSettings { r.values.Set("ignore_unavailable", strconv.FormatBool(ignoreunavailable)) return r } // IncludeDefaults If `true`, return all default settings in the response. // API name: include_defaults func (r *GetSettings) IncludeDefaults(includedefaults bool) *GetSettings { r.values.Set("include_defaults", strconv.FormatBool(includedefaults)) return r } // Local If `true`, the request retrieves information from the local node only. If // `false`, information is retrieved from the master node. // API name: local func (r *GetSettings) Local(local bool) *GetSettings { r.values.Set("local", strconv.FormatBool(local)) return r } // MasterTimeout Period to wait for a connection to the master node. If no response is // received before the timeout expires, the request fails and returns an // error. // API name: master_timeout func (r *GetSettings) MasterTimeout(duration string) *GetSettings { r.values.Set("master_timeout", duration) return r }
package requests import ( "compress/gzip" "errors" "github.com/sirupsen/logrus" "io" "io/ioutil" "net/http" "net/http/cookiejar" "net/url" "os" "strings" ) type Requests struct { hearders map[string]string JarCks http.CookieJar //需要在init初始化设置 } var ( UnKnown = errors.New("unknown error") NetWork = errors.New("network error") ) var JarCks http.CookieJar func (self *Requests) IntiRequests() { self.JarCks, _ = cookiejar.New(nil) self.setDefaultMapHeader() } func (self *Requests) setDefaultMapHeader() { self.hearders = make(map[string]string) self.hearders["Connection"] = "keep-alive" self.hearders["Cache-Control"] = "max-age=0" self.hearders["Upgrade-Insecure-Requests"] = "1" self.hearders["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36" self.hearders["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" self.hearders["Accept-Encoding"] = "gzip, deflate, br" self.hearders["Accept-Language"] = "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,fr;q=0.6,zh-TW;q=0.5" } func (self *Requests) SetHeader(sKey, sValue string) { self.hearders[sKey] = sValue } func (self *Requests) handle(method, url string, postVal url.Values) (strHtml string, err error) { var ( postData *strings.Reader request *http.Request errRequest error ) if postVal == nil { request, errRequest = http.NewRequest(method, url, nil) }else{ postData = strings.NewReader(postVal.Encode()) request, errRequest = http.NewRequest(method, url, postData) } //logrus.Info(postVal.Encode()) //将Values转为aa=bb&cc=dd这样格式的字符串 if errRequest == nil { //self.setDefaultMapHeader() client := &http.Client{Jar: self.JarCks} response, errDo := client.Do(request) //defer response.Body.Close() if errDo == nil { var sBody string if response.StatusCode == 200 { if response.Header.Get("Content-Encoding") == "gzip" { reader, _ := gzip.NewReader(response.Body) for { buf := make([]byte, 1024) n, errBuf := reader.Read(buf) if errBuf != nil && errBuf != io.EOF { //panic(errBuf) err = errBuf logrus.Error(errBuf) return } if n == 0 { break } sBody += string(buf) } strHtml = sBody } else { bBody, _ := ioutil.ReadAll(response.Body) strHtml = string(bBody) } } else { NetWork = errors.New(NetWork.Error()+" StatusCode: " + response.Status) err = NetWork } } else { err = errDo return } //defer response.Body.Close() } else { err = errRequest return } return } func (self *Requests) PostData(data map[string]string) (postVal url.Values) { postVal = url.Values{} for key, val := range data { postVal.Add(key, val) } return } func (self *Requests) Post(url string, data map[string]string) (strHtml string, err error) { return self.handle("POST", url, self.PostData(data)) } func (self *Requests) Get(url string) (strHtml string, err error) { return self.handle("GET", url, nil) } func (self *Requests) Download(url string, savePath string) (err error) { res, err := http.Get(url) if err != nil { return } file, err := os.Create(savePath) if err != nil { return } _, err = io.Copy(file, res.Body) if err != nil { return } return }
package example import ( "context" "log" pubsub "github.com/utilitywarehouse/go-pubsub" "github.com/utilitywarehouse/go-pubsub/sqs" ) func consumerExample() { source, err := sqs.NewMessageSource(sqs.MessageSourceConfig{ Client: getClient(), // defined in sink.go QueueURL: "https://sqs.eu-west-1.amazonaws.com/123/queueName", // Optionally set how long you want to wait between API poll requests (in seconds). // Defaults to 0 (disabled) if not set. WaitSeconds: 1, }) if err != nil { log.Fatalf("failed to get SQS source: %v", err) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Poll for messages. To stop the loop, call `cancel()` and it will cancel the context. if err := source.ConsumeMessages(ctx, msgHandler, errHandler); err != nil { log.Fatalf("failed to consume from SQS: %v", err) } } // msgHandler will process messages from SQS. func msgHandler(msg pubsub.ConsumerMessage) error { // Add your message handling logic here. return nil } // errHandler will be called if message handler fails. func errHandler(pubsub.ConsumerMessage, error) error { // Add your error handling logic here. return nil }
package resource import ( "github.com/cisordeng/beego/xenon" bResource "kylin/business/resource" ) type Uploads struct { xenon.RestResource } func init () { xenon.RegisterResource(new(Uploads)) } func (this *Uploads) Resource() string { return "resource.uploads" } func (this *Uploads) Params() map[string][]string { return map[string][]string{ "PUT": []string{ "files", }, } } func (this *Uploads) Put() { bCtx := this.GetBusinessContext() fileHeaders, _ := this.GetFiles("files") resources := bResource.NewResources(bCtx, fileHeaders) data := bResource.EncodeManyResource(resources) this.ReturnJSON(xenon.Map{ "resources": data, }) }
// Copyright (c) 2020 Blockwatch Data Inc. // Author: alex@blockwatch.cc package models import ( "context" "github.com/jinzhu/gorm" "tezos_index/chain" ) // BlockCrawler provides an interface to access information about the current // state of blockchain crawling. type BlockCrawler interface { // returns the blockchain params at specified block height ParamsByHeight(height int64) *chain.Params // returns the blockchain params for the specified protocol ParamsByProtocol(proto chain.ProtocolHash) *chain.Params // returns the current crawler chain tip Tip() *ChainTip // returns the crawler's most recently seen block height Height() int64 // returns stored (main chain) block at specified height BlockByHeight(ctx context.Context, height int64) (*Block, error) // returns stored chain data at specified height ChainByHeight(ctx context.Context, height int64) (*Chain, error) // returns stored supply table data at specified height SupplyByHeight(ctx context.Context, height int64) (*Supply, error) } // BlockBuilder provides an interface to access information about the currently // processed block. type BlockBuilder interface { // resolves account from address, returns nil and false when not found AccountByAddress(chain.Address) (*Account, bool) // resolves account from id, returns nil and false when not found AccountById(AccountID) (*Account, bool) // returns a map of all accounts referenced in the current block Accounts() map[AccountID]*Account // returns a map of all delegates referenced in the current block Delegates() map[AccountID]*Account // returns block rights Rights(chain.RightType) []Right } // BlockIndexer provides a generic interface for an indexer that is managed by an // etl.Indexer. type BlockIndexer interface { // Key returns the key of the index as a string. Key() string // ConnectBlock is invoked when the table manager is notified that a new // block has been connected to the main chain. ConnectBlock(ctx context.Context, block *Block, builder BlockBuilder, tx *gorm.DB) error // DisconnectBlock is invoked when the table manager is notified that a // block has been disconnected from the main chain. DisconnectBlock(ctx context.Context, block *Block, builder BlockBuilder, tx *gorm.DB) error // DeleteBlock is invoked when the table manager is notified that a // block must be rolled back after an error occured. DeleteBlock(ctx context.Context, height int64, tx *gorm.DB) error // returns the database storing all indexer tables DB() *gorm.DB }
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package derp implements DERP, the Detour Encrypted Routing Protocol. // // DERP routes packets to clients using curve25519 keys as addresses. // // DERP is used by Tailscale nodes to proxy encrypted WireGuard // packets through the Tailscale cloud servers when a direct path // cannot be found or opened. DERP is a last resort. Both sides // between very aggressive NATs, firewalls, no IPv6, etc? Well, DERP. package derp import ( "bufio" "encoding/binary" "fmt" "io" "time" ) // magic is the derp magic number, sent on the wire as a uint32. // It's "DERP" with a non-ASCII high-bit. const magic = 0x44c55250 // frameType is the one byte frame type header in frame headers. type frameType byte const ( typeServerKey = frameType(0x01) typeServerInfo = frameType(0x02) typeSendPacket = frameType(0x03) typeRecvPacket = frameType(0x04) typeKeepAlive = frameType(0x05) ) func (b frameType) Write(w io.ByteWriter) error { return w.WriteByte(byte(b)) } const keepAlive = 60 * time.Second var bin = binary.BigEndian const oneMB = 1 << 20 func readType(r *bufio.Reader, t frameType) error { packetType, err := r.ReadByte() if err != nil { return err } if frameType(packetType) != t { return fmt.Errorf("bad packet type 0x%X, want 0x%X", packetType, t) } return nil } func putUint32(w io.Writer, v uint32) error { var b [4]byte bin.PutUint32(b[:], v) _, err := w.Write(b[:]) return err } func readUint32(r io.Reader, maxVal uint32) (uint32, error) { b := make([]byte, 4) if _, err := io.ReadFull(r, b); err != nil { return 0, err } val := bin.Uint32(b) if val > maxVal { return 0, fmt.Errorf("uint32 %d exceeds limit %d", val, maxVal) } return val, nil }
package cmd import ( "errors" "fmt" "path/filepath" "github.com/andytom/tmpltr/template" "github.com/AlecAivazis/survey" "github.com/spf13/cobra" ) func init() { RootCmd.AddCommand(useCmd) } var useCmd = &cobra.Command{ Use: "use NAME DIR", Short: "Apply a template to a directory", Long: `Apply a template to a directory This applies the template with the name NAME in directory DIR. `, RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 2 { return errors.New("Need a directory and template") } templateKey := args[0] dest := filepath.Clean(args[1]) s, err := template.OpenStore(cfgDir) if err != nil { return fmt.Errorf("Unable to access the template directory %q: %q", cfgDir, err) } // Load the template t, err := s.Get(templateKey) if err != nil { return fmt.Errorf("Was unable to load template %q: %q", templateKey, err) } fmt.Printf("Loaded template %q\n", templateKey) // Ask the questions questions := t.GetQuestions() answers := map[string]interface{}{} err = survey.Ask(questions, &answers) if err != nil { return fmt.Errorf("Unable to get answers to questions: %q", err) } // Execute the template fmt.Printf("Executing in %q\n", dest) return t.Execute(dest, answers) }, }
package template import ( "context" "fmt" "os" "path/filepath" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/argoproj/argo/cmd/argo/commands/client" workflowtemplatepkg "github.com/argoproj/argo/pkg/apiclient/workflowtemplate" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" cmdutil "github.com/argoproj/argo/util/cmd" "github.com/argoproj/argo/workflow/validate" ) func NewLintCommand() *cobra.Command { var ( strict bool ) var command = &cobra.Command{ Use: "lint (DIRECTORY | FILE1 FILE2 FILE3...)", Short: "validate a file or directory of workflow template manifests", Run: func(cmd *cobra.Command, args []string) { err := ServerSideLint(args, strict) if err != nil { log.Fatal(err) } fmt.Printf("WorkflowTemplate manifests validated\n") }, } command.Flags().BoolVar(&strict, "strict", true, "perform strict workflow validation") return command } func ServerSideLint(args []string, strict bool) error { validateDir := cmdutil.MustIsDir(args[0]) ctx, apiClient := client.NewAPIClient() serviceClient := apiClient.NewWorkflowTemplateServiceClient() invalid := false if validateDir { if len(args) > 1 { fmt.Printf("Validation of a single directory supported") os.Exit(1) } walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info == nil || info.IsDir() { return nil } fileExt := filepath.Ext(info.Name()) switch fileExt { case ".yaml", ".yml", ".json": default: return nil } wfTmpls, err := validate.ParseWfTmplFromFile(path, strict) if err != nil { log.Error(err) invalid = true } for _, wfTmpl := range wfTmpls { if wfTmpl.Namespace == "" { wfTmpl.Namespace = client.Namespace() } err := ServerLintValidation(ctx, serviceClient, wfTmpl, wfTmpl.Namespace) if err != nil { log.Error(err) invalid = true } } return nil } return filepath.Walk(args[0], walkFunc) } else { for _, arg := range args { wfTmpls, err := validate.ParseWfTmplFromFile(arg, strict) if err != nil { log.Error(err) invalid = true } for _, wfTmpl := range wfTmpls { if wfTmpl.Namespace == "" { wfTmpl.Namespace = client.Namespace() } err := ServerLintValidation(ctx, serviceClient, wfTmpl, wfTmpl.Namespace) if err != nil { log.Error(err) invalid = true } } } } if invalid { log.Fatalf("Errors encountered in validation") } fmt.Printf("WorkflowTemplate manifests validated\n") return nil } func ServerLintValidation(ctx context.Context, client workflowtemplatepkg.WorkflowTemplateServiceClient, wfTmpl wfv1.WorkflowTemplate, ns string) error { wfTmplReq := workflowtemplatepkg.WorkflowTemplateLintRequest{ Namespace: ns, Template: &wfTmpl, } _, err := client.LintWorkflowTemplate(ctx, &wfTmplReq) return err }
package mapxml import ( "encoding/xml" ) type TMXWangSets struct { // <wangsets> // ~~~~~~~~~~ XMLName xml.Name `xml:"wangsets"` // Contains the list of Wang sets defined for this tileset. // Can contain any number: :ref:`tmx-wangset` } type TMXWangset struct { // <wangset> // ^^^^^^^^^ XMLName xml.Name `xml:"wangset"` // Defines a list of corner colors and a list of edge colors, and any // number of Wang tiles using these colors. // - **name:** The name of the Wang set. // - **tile:** The tile ID of the tile representing this Wang set. // Can contain at most one: :ref:`tmx-properties` // Can contain up to 255: :ref:`tmx-wangcolor` (since Tiled 1.5) // Can contain any number: :ref:`tmx-wangtile` } type TMXWangColor struct { // <wangcolor> // ''''''''''' XMLName xml.Name `xml:"wangcolor"` // A color that can be used to define the corner and/or edge of a Wang tile. // - **name:** The name of this color. // - **color:** The color in ``#RRGGBB`` format (example: ``#c17d11``). // - **tile:** The tile ID of the tile representing this color. // - **probability:** The relative probability that this color is chosen // over others in case of multiple options. (defaults to 0) // Can contain at most one: :ref:`tmx-properties` } type TMXWangTile struct { // <wangtile> // '''''''''' XMLName xml.Name `xml:"wangtile"` // Defines a Wang tile, by referring to a tile in the tileset and // associating it with a certain Wang ID. // - **tileid:** The tile ID. // - **wangid:** "The Wang ID, given by a comma-separated list of indexes // (starting from 1, because 0 means _unset_) referring to the Wang colors in // the Wang set in the following order: top, top right, right, bottom right, // bottom, bottom left, left, top left (since Tiled 1.5). Before Tiled 1.5, the // Wang ID was saved as a 32-bit unsigned integer stored in the format // ``0xCECECECE`` (where each C is a corner color and each E is an edge color, // in reverse order)." // - *hflip:* Whether the tile is flipped horizontally (removed in Tiled 1.5). // - *vflip:* Whether the tile is flipped vertically (removed in Tiled 1.5). // - *dflip:* Whether the tile is flipped on its diagonal (removed in Tiled 1.5). }
package p2p import ( "time" ) // PeerMetrics is the data shared to the metrics hook type PeerMetrics struct { Hash string PeerAddress string MomentConnected time.Time PeerQuality int32 LastReceive time.Time LastSend time.Time MessagesSent uint64 BytesSent uint64 MessagesReceived uint64 BytesReceived uint64 Incoming bool PeerType string ConnectionState string MPSDown float64 MPSUp float64 BPSDown float64 BPSUp float64 Capacity float64 Dropped uint64 } // peerStatus is an indicator for peer manager whether the associated peer is going online or offline type peerStatus struct { peer *Peer online bool } type peerParcel struct { peer *Peer parcel *Parcel }
package db import ( "context" "github.com/go-redis/redis/v8" "os" ) func GetRedisConnection() (*redis.Client, context.Context) { dsn := os.Getenv("REDIS_DSN") ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: dsn, Password: "", // no password set DB: 0, // use default DB }) return rdb, ctx }
package main import ( "github.com/streadway/amqp" "log" ) /** * Retrieves a connection from the configured AMQP host, with the given ConnectionDefinition */ func GetConnection(definition ConnectionDefinition) error { connection, err := amqp.Dial("amqp://" + definition.Username + ":" + definition.Password + "@" + RABBITMQ_HOST + ":" + RABBITMQ_PORT + "/" + definition.Vhost) if err != nil { log.Print(err) if err == amqp.ErrClosed { return retryAmqpConnection(definition) } return err } Connection[definition.Vhost] = connection getChannel(Connection[definition.Vhost], definition) return nil } /** * Retrieves a channel from the given connection, ConnectionDefinition */ func getChannel(connection *amqp.Connection, cd ConnectionDefinition) error { channel, err := connection.Channel() if err != nil { return err } Channel[cd.Vhost] = channel return nil } /** * Handles closed connection errors with a retry */ func retryAmqpConnection(connection ConnectionDefinition) error { log.Printf("AMQP connection dropped.") /** * Don't want to loop through this for too long. */ if Statistics[RUNTIME_RABBITMQ_CONNECTION_FAILURE] > HARE_RABBITMQ_CONNECTION_RETRY_MAXIMUM { log.Fatal("Maximum connection retry count has been reached.") } err := GetConnection(connection) if err != nil { return err } statisticsIncrement(RUNTIME_RABBITMQ_CONNECTION_FAILURE) log.Print("Reconnected to remote host.") return nil }
package scache import ( "context" "errors" "math" "time" ) type builder struct { conf *Config loadFunc LoadFunc } func New(shards int, maxSize int64) *builder { return &builder{ conf: &Config{ Shards: shards, MaxSize: maxSize, Kind: KindUnknown, }, } } func FromConfig(conf *Config) *builder { return &builder{ conf: conf, } } func (b *builder) LRU() *builder { b.conf.Kind = KindLRU return b } func (b *builder) TTL(val time.Duration) *builder { b.conf.TTL = val return b } func (b *builder) LoaderFunc(val LoadFunc) *builder { b.loadFunc = val return b } func (b *builder) ItemsToPrune(val uint32) *builder { b.conf.ItemsToPrune = val return b } func (b *builder) Build() (*Cache, error) { if b.conf.Shards <= 0 || b.conf.Shards >= math.MaxUint32 { return nil, errors.New("invalid count of shards") } if b.conf.MaxSize <= 0 { return nil, errors.New("invalid size") } if b.conf.TTL < 0 { return nil, errors.New("invalid cache time to live") } itemsToPrune := uint32(10) if b.conf.ItemsToPrune > 0 { itemsToPrune = b.conf.ItemsToPrune } shards := make([]iShard, 0, int(b.conf.Shards)) counter := newCounter(b.conf.MaxSize) timer := newTimer() cleanLimit := 1000 if v := int(counter.Limit()) / 10; v > cleanLimit { cleanLimit = v } chClean := make(chan struct{}, cleanLimit) for i := 0; i < b.conf.Shards; i++ { var shard iShard switch b.conf.Kind { case KindLRU: shard = newShardRU(chClean, counter, timer, b.conf, b.loadFunc) default: return nil, errors.New("invalid kind of cache") } shards = append(shards, shard) } ctx, ctxCancel := context.WithCancel(context.Background()) c := &Cache{ maxShardIndex: uint64(len(shards)) - 1, shards: shards, counter: counter, itemsToPrune: itemsToPrune, ctx: ctx, ctxCancel: ctxCancel, chClean: chClean, timer: timer, } c.runCleaner() return c, nil }
/* * Display details of a single cross-datacenter firewall policy. */ package main import ( "flag" "fmt" "os" "path" "strings" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" "github.com/olekukonko/tablewriter" ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: %s [options] <Location> <PolicyID>\n", path.Base(os.Args[0])) flag.PrintDefaults() } flag.Parse() if flag.NArg() != 2 { flag.Usage() os.Exit(1) } client, err := clcv2cli.NewCLIClient() if err != nil { exit.Fatal(err.Error()) } p, err := client.GetCrossDataCenterFirewallPolicy(flag.Arg(0), flag.Arg(1)) if err != nil { exit.Fatalf("failed to list %s firewall policy %s: %s", flag.Arg(0), flag.Arg(1), err) } fmt.Printf("Details of %s cross-datacenter Firewall Policy %s:\n", strings.ToUpper(flag.Arg(0)), flag.Arg(1)) table := tablewriter.NewWriter(os.Stdout) table.SetAutoFormatHeaders(false) table.SetAlignment(tablewriter.ALIGN_CENTER) table.SetAutoWrapText(false) table.SetHeader([]string{"Data Center", "Network", "Account", "Status", "ID"}) enabledStr := "*" if !p.Enabled { enabledStr = "-" } table.Append([]string{ strings.ToUpper(fmt.Sprintf("%s => %s", p.SourceLocation, p.DestLocation)), fmt.Sprintf("%18s => %-18s", p.SourceCIDR, p.DestCIDR), strings.ToUpper(fmt.Sprintf("%-4s => %4s", p.SourceAccount, p.DestAccount)), fmt.Sprintf("%s%s", enabledStr, p.Status), p.ID, }) table.Render() }
package add_two_numbers type ListNode struct { Val int Next *ListNode } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { newNode := &ListNode{} a, b, ab := l1, l2, newNode //进位 carry := 0 for nil != a || nil != b || carry > 0 { sum := carry if nil != a { sum += a.Val a = a.Next } if nil != b { sum += b.Val b = b.Next } ab.Val = sum % 10 carry = sum / 10 //没有进位,且两个链表都到末尾了 if a == nil && b == nil && carry == 0 { return newNode } ab.Next = &ListNode{} ab = ab.Next } return newNode }
package httputils import ( "net/http" "github.com/go-chi/render" ) // HTTPError contains the error message type HTTPError struct { Message string `json:"message"` } // RespondIfError if err != nil, returns the HTTPError and code as API response // no-op if the err is nil func RespondIfError(code *int, err *error, w http.ResponseWriter, r *http.Request) { if *err == nil { return } e := *err render.Status(r, *code) render.JSON(w, r, HTTPError{Message: e.Error()}) }
package main import ( "bufio" "fmt" "io" "log" "net" "runtime/debug" ) const port = "9002" const target = "" type client struct { listenChannel chan bool // Channel that the client is listening on transmitChannel chan bool // Channel that the client is writing to listener io.Writer // The thing to write to listenerConnected bool transmitter io.Reader // The thing to listen from transmitterConnected bool } var connectedClients map[string]client = make(map[string]client) func bindServer(clientId string) { if connectedClients[clientId].listenerConnected && connectedClients[clientId].transmitterConnected { log.Println("Two-way connection to client established!") log.Println("Client <=|F|=> Proxy <-...-> VPN") defer func() { connectedClients[clientId].listenChannel <- true connectedClients[clientId].transmitChannel <- true delete(connectedClients, clientId) }() serverConn, err := net.Dial("tcp", target) if err != nil { log.Println("Failed to connect to remote server :/", err) } defer serverConn.Close() wait := make(chan bool) go func() { _, err := io.Copy(connectedClients[clientId].listener, serverConn) if err != nil { log.Println("Disconnect:", err) } wait <- true }() go func() { _, err := io.Copy(serverConn, connectedClients[clientId].transmitter) if err != nil { log.Println("Disconnect:", err) } wait <- true }() log.Println("Full connection established!") log.Println("Client <=|F|=> Proxy <---> VPN") <-wait log.Println("Connection closed") } } func handleConnection(clientConn net.Conn) { defer clientConn.Close() defer func() { if r := recover(); r != nil { fmt.Println("Connection panic:", r) debug.PrintStack() } }() reader := bufio.NewReader(clientConn) line, err := reader.ReadString('\n') if err != nil { // log.Println("Failed to read first line", err) return } if line == "GET /listen HTTP/1.1\r\n" { // This is for LISTENING resolvedId := "" for line, err = reader.ReadString('\n'); true; line, err = reader.ReadString('\n') { if err != nil { // log.Println("Failed to read following lines", err) return } if len(line) > 10 && line[:10] == "Clientid: " { resolvedId = line[10:30] } if line == "\r\n" { break } } if len(resolvedId) > 1 { fmt.Fprintf(clientConn, "HTTP/1.1 200 OK\r\n") fmt.Fprintf(clientConn, "Content-Type: application/octet-stream\r\n") fmt.Fprintf(clientConn, "Connection: keep-alive\r\n") fmt.Fprintf(clientConn, "Content-Length: 12345789000\r\n\r\n") wait := make(chan bool) if _, ok := connectedClients[resolvedId]; !ok { connectedClients[resolvedId] = client{} } currentClient := connectedClients[resolvedId] currentClient.listener = clientConn currentClient.listenChannel = wait currentClient.listenerConnected = true connectedClients[resolvedId] = currentClient // log.Println("Attempting to bind listener") go bindServer(resolvedId) <-wait } else { // log.Println("Failed to find client id!") } } else if line == "POST /transmit HTTP/1.1\r\n" { // This is for TRANSMITTING resolvedId := "" for line, err = reader.ReadString('\n'); true; line, err = reader.ReadString('\n') { if err != nil { // log.Println("Failed to read following lines") return } if len(line) > 10 && line[:10] == "Clientid: " { resolvedId = line[10:30] } if line == "----------SWAG------BOUNDARY----\r\n" { break } } if len(resolvedId) > 1 { wait := make(chan bool) if _, ok := connectedClients[resolvedId]; !ok { connectedClients[resolvedId] = client{} } currentClient := connectedClients[resolvedId] currentClient.transmitter = reader currentClient.transmitChannel = wait currentClient.transmitterConnected = true connectedClients[resolvedId] = currentClient // log.Println("Attempting to bind transmission") go bindServer(resolvedId) <-wait } else { // log.Println("Failed to find client id!") } } else { fmt.Fprintf(clientConn, "HTTP/1.1 404 Not found\r\n") fmt.Fprintf(clientConn, "Content-Type: text/plain\r\n") fmt.Fprintf(clientConn, "Content-Length: 8\r\n\r\n") fmt.Fprintf(clientConn, "u wot m9") } } func main() { log.Println("Listening...") ln, err := net.Listen("tcp", ":"+port) if err != nil { log.Println("Error listening!", err) return } for true { conn, err := ln.Accept() if err != nil { log.Println("Error accepting connection", err) continue } go handleConnection(conn) } }
package repository import ( "fmt" "testing" "github.com/go-logr/logr" "github.com/go-test/deep" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/klogr" "github.com/isutton/orchid/pkg/orchid/config" jsc "github.com/isutton/orchid/pkg/orchid/jsonschema" "github.com/isutton/orchid/pkg/orchid/orm" "github.com/isutton/orchid/test/mocks" ) func buildTestRepository(t *testing.T) (logr.Logger, *Repository) { logger := klogr.New().WithName("test") config := &config.Config{Username: "postgres", Password: "1", Options: "sslmode=disable"} r := NewRepository(logger, config) require.NotNil(t, r) return logger, r } func TestRepository_decompose(t *testing.T) { logger, repo := buildTestRepository(t) schemaName := "orchid" s := orm.NewSchema(logger, schemaName) openAPIV3Schema := jsc.ExtV1CRDOpenAPIV3Schema() err := s.Generate(&openAPIV3Schema) require.NoError(t, err) u, err := mocks.UnstructuredCRDMock("ns", "name") require.NoError(t, err) matrix, err := repo.decompose(s, u) require.NoError(t, err) require.NotNil(t, matrix) t.Logf("matrix='%#v'", matrix) table, err := s.GetTable(schemaName) require.NoError(t, err) // looking for column position in order to acquire data from matrix columnPosition := -1 for position, column := range table.ColumNames() { if column == orm.XEmbeddedResource { columnPosition = position break } } require.NotEqual(t, -1, columnPosition) row, found := matrix[schemaName] require.True(t, found) require.Len(t, row, 1) jsonData, ok := row[0][columnPosition].(string) require.True(t, ok) assert.NotNil(t, jsonData) t.Logf("json='%s'", jsonData) // making sure json data also has a new line appended jsonData = fmt.Sprintf("%s\n", jsonData) // comparing json data with original object bytes, err := u.MarshalJSON() assert.NoError(t, err) assert.Equal(t, jsonData, string(bytes)) } func TestRepository_New(t *testing.T) { _, repo := buildTestRepository(t) err := repo.Bootstrap() require.NoError(t, err) t.Run("Create-CRD", func(t *testing.T) { crd, err := mocks.UnstructuredCRDMock(DefaultNamespace, mocks.RandomString(8)) require.NoError(t, err) t.Logf("CRD name: '%s'", crd.GetName()) err = repo.Create(crd) require.NoError(t, err) }) // List-CRD is expected to find one CRD, customresourcedefinitions.apiextensions.k8s.io after // bootstrap in DefaultNamespace; this is the contract responsible for announcing to clients new // resources can be created. t.Run("List-CRD", func(t *testing.T) { uList, err := repo.List(DefaultNamespace, CRDGVK, metav1.ListOptions{}) require.NoError(t, err) require.Len(t, uList.Items, 1) }) cr, err := mocks.UnstructuredCRMock(DefaultNamespace, mocks.RandomString(12)) t.Logf("cr='%#v'", cr) require.NoError(t, err) gvk := cr.GetObjectKind().GroupVersionKind() t.Run("Create-CR", func(t *testing.T) { err = repo.Create(cr) require.NoError(t, err) }) t.Run("Read-CR", func(t *testing.T) { namespacedName := types.NamespacedName{ Namespace: cr.GetNamespace(), Name: cr.GetName(), } u, err := repo.Read(gvk, namespacedName) require.NoError(t, err) t.Logf("u='%#v'", u) t.Log("## comparing original and obtained unstructured") diff := deep.Equal(cr, u) for _, entry := range diff { t.Log(entry) } }) t.Run("List-CR", func(t *testing.T) { cr, _ = mocks.UnstructuredCRMock(DefaultNamespace, mocks.RandomString(12)) err = repo.Create(cr) require.NoError(t, err) options := metav1.ListOptions{LabelSelector: "label=label"} list, err := repo.List(DefaultNamespace, gvk, options) require.NoError(t, err) t.Logf("List size '%d'", len(list.Items)) for _, item := range list.Items { t.Logf("item='%#v'", item.Object) } assert.True(t, len(list.Items) >= 2) // cleaning up on threshold if len(list.Items) > 6 { o, s, err := repo.factory(DefaultNamespace, gvk) require.NoError(t, err) table, err := s.GetTable(s.Name) require.NoError(t, err) _, err = o.DB.Exec(fmt.Sprintf("truncate table %s cascade", table.Name)) require.NoError(t, err) } }) }
package main import ( "flag" "log" "net/url" "github.com/mlmhl/gcrawler/handler" "github.com/mlmhl/gcrawler/request" "github.com/mlmhl/gcrawler/response" "github.com/mlmhl/gcrawler/spider" "github.com/mlmhl/gcrawler/types" "github.com/golang/glog" "github.com/mlmhl/gcrawler/storage" "golang.org/x/net/html" "golang.org/x/net/html/atom" ) type state interface { Parse(n *html.Node) (string, state) } type rootState struct{} func (s rootState) Parse(n *html.Node) (string, state) { if isRepoListNode(n) { return "", repoListNodeState{} } return "", s } func isRepoListNode(n *html.Node) bool { if n.Data == atom.Div.String() { for _, a := range n.Attr { if a.Key == atom.Id.String() && a.Val == "user-repositories-list" { return true } } } return false } // <div id="user-repositories-list"> type repoListNodeState struct{} func (s repoListNodeState) Parse(n *html.Node) (string, state) { if isRepoList(n) { return "", repoListState{} } return "", nil } func isRepoList(n *html.Node) bool { return n.Data == atom.Ul.String() } // <ul data-filterable-for="your-repos-filter" data-filterable-type="substring"> type repoListState struct{} func (s repoListState) Parse(n *html.Node) (string, state) { if isRepoItem(n) { return "", repoNodeState{} } return "", nil } func isRepoItem(n *html.Node) bool { return n.Data == atom.Li.String() } // <li class="col-12 d-block width-full py-4 border-bottom public fork" itemprop="owns" itemscope itemtype="http://schema.org/Code"> type repoNodeState struct{} func (s repoNodeState) Parse(n *html.Node) (string, state) { if isRepo(n) { return "", repoState{} } return "", nil } func isRepo(n *html.Node) bool { if n.Data == atom.Div.String() { for _, a := range n.Attr { if a.Key == atom.Class.String() && a.Val == "d-inline-block mb-1" { return true } } } return false } // <div class="d-inline-block mb-1"> type repoState struct{} func (s repoState) Parse(n *html.Node) (string, state) { if isLink(n) { return "", linkState{} } return "", nil } func isLink(n *html.Node) bool { return n.Data == atom.H3.String() } // <h3> <a href="XXX"> type linkState struct{} func (s linkState) Parse(n *html.Node) (string, state) { for _, attr := range n.Attr { if attr.Key == atom.Href.String() { return "http://github.com" + attr.Val, nil } } return "", nil } func newParser() *parser { return &parser{state: rootState{}} } type parser struct { state state items []types.Item } func (parser *parser) Parse(n *html.Node) { defer func(state state) { parser.state = state }(parser.state) repo, state := parser.state.Parse(n) if len(repo) > 0 { parser.items = append(parser.items, item(repo)) } if state == nil { return } parser.state = state for children := n.FirstChild; children != nil; children = children.NextSibling { parser.Parse(children) } } type item string func (i item) Content() string { return string(i) } type gitHubRepoHandler struct { } func newGitHubRepoHandler() handler.Handler { return &gitHubRepoHandler{} } func (processor *gitHubRepoHandler) Handle(req request.Request, resp response.Response) ([]types.Item, []request.Request) { if resp.Error() != nil { glog.Errorf("Crawl request %s failed: %v", req.Description(), resp.Error()) // If we wanted to retry this request, we can return the request as a successor. // return nil, []request.Request{req} return nil, nil } httpResp := resp.Response() if httpResp.Body == nil { // We can do nothing. return nil, nil } node, err := html.Parse(httpResp.Body) if err != nil { glog.Errorf("Parse response failed: %s, %v", req.Description(), err) return nil, nil } p := newParser() p.Parse(node) return p.items, nil } func main() { flag.Parse() u, err := url.Parse("https://github.com/mlmhl?tab=repositories") if err != nil { log.Fatalf("Parse start url failed: %v", err) } s, err := spider.New(&spider.Options{ Handler: newGitHubRepoHandler(), Storages: []storage.Storage{storage.NewConsoleStorage()}, Bootstraps: []request.Request{request.New(u, "GET")}, }) if err != nil { glog.Fatalf("Create spider failed: %v", err) } s.Run() }
package main import ( "bytes" "fmt" "github.com/kohirens/tmpltoapp/internal/cli" "os" "os/exec" "path/filepath" "regexp" "strings" ) // gitClone Clone a repo from a path/URL to a local directory. func gitClone(repoUri, repoDir, refName string) (string, string, error) { infof("branch to clone is %q", refName) infof("git clone %s", repoUri) var sco []byte var e1 error if isRemoteRepo(repoUri) { branchName := refName re := regexp.MustCompile("^refs/[^/]+/(.*)$") if re.MatchString(refName) { branchName = re.ReplaceAllString(refName, "${1}") } logf("cloning branch name: %v", branchName) // git clone --depth 1 --branch <tag_name> <repo_url> // NOTE: Branch cannot be a full ref but can be short ref name or a tag. sco, e1 = gitCmd(".", "clone", "--depth", "1", "--branch", branchName, repoUri, repoDir) } else { // git clone <repo_url> sco, e1 = gitCmd(".", "clone", repoUri, repoDir) if e1 != nil { return "", "", fmt.Errorf(cli.Errors.Cloning, repoUri, e1.Error()) } infof("clone output \n%s", sco) // get current branch cb, e4 := gitCmd(repoDir, "branch", "--show-current", refName) if e4 != nil { return "", "", fmt.Errorf(cli.Errors.CurrentBranch, repoUri, e4.Error(), cb) } // skip if already on desired branch if strings.Trim(bytes.NewBuffer(cb).String(), "\r\n") != refName { // git checkout <ref_name> co, e3 := gitCmd(repoDir, "checkout", "-b", refName) if e3 != nil { return "", "", fmt.Errorf(cli.Errors.Checkout, repoUri, e3.Error(), co) } infof("checkout output \n%s", co) } } latestCommitHash, e2 := getLastCommitHash(repoDir) if e2 != nil { return "", "", fmt.Errorf(cli.Errors.GettingCommitHash, repoDir, e2.Error()) } return repoDir, latestCommitHash, nil } // gitCheckout Open an existing repo and checkout commit by full ref-name func gitCheckout(repoLocalPath, ref string) (string, string, error) { infof("pulling latest\n") _, e1 := gitCmd(repoLocalPath, "fetch", "--all", "-p") if e1 != nil { return "", "", fmt.Errorf(cli.Errors.GitFetchFailed, repoLocalPath, ref, e1.Error()) } infof(cli.Messages.RefInfo, ref) infof(cli.Messages.GitCheckout, ref) _, e2 := gitCmd(repoLocalPath, "checkout", ""+ref) if e2 != nil { return "", "", fmt.Errorf(cli.Errors.GitCheckoutFailed, e2.Error()) } repoDir, e8 := filepath.Abs(repoLocalPath) if e8 != nil { return "", "", e8 } latestCommitHash, e4 := getLastCommitHash(repoDir) if e4 != nil { return "", "", e4 } return repoDir, latestCommitHash, nil } // gitCmd run a git command. func gitCmd(repoPath string, args ...string) ([]byte, error) { cmd := exec.Command("git", args...) cmd.Env = os.Environ() cmd.Dir = repoPath cmdStr := cmd.String() infof(cli.Messages.RunningCommand, cmdStr) cmdOut, cmdErr := cmd.CombinedOutput() exitCode := cmd.ProcessState.ExitCode() if cmdErr != nil { return nil, fmt.Errorf(cli.Errors.RunGitFailed, args, cmdErr.Error(), cmdOut) } if exitCode != 0 { return nil, fmt.Errorf(cli.Errors.GitExitErrCode, args, exitCode) } return cmdOut, nil } // getLastCommitHash Returns the HEAD commit hash. func getLastCommitHash(repoDir string) (string, error) { latestCommitHash, e1 := gitCmd(repoDir, "rev-parse", "HEAD") if e1 != nil { return "", fmt.Errorf(cli.Errors.GettingCommitHash, repoDir, e1.Error()) } return strings.Trim(string(latestCommitHash), "\n"), nil } // getLatestTag Will return the latest tag or an empty string from a repository. func getLatestTag(repoDir string) (string, error) { tags, e1 := getRemoteTags(repoDir) if e1 != nil { return "", fmt.Errorf(cli.Errors.GetLatestTag, repoDir, e1.Error()) } return tags[0], nil } // getRemoteTags Get the remote tags on a repo using git ls-remote. func getRemoteTags(repo string) ([]string, error) { // Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote: sco, e1 := gitCmd(repo, "ls-remote", "--sort=-version:refname", "--tags") if e1 != nil { return nil, fmt.Errorf(cli.Errors.GetRemoteTags, e1.Error()) } reTags := regexp.MustCompile("[a-f0-9]+\\s+refs/tags/(\\S+)") mat := reTags.FindAllSubmatch(sco, -1) if mat == nil { return nil, fmt.Errorf("%s", "no tags found") } ret := make([]string, len(mat)) for i, v := range mat { dbugf(cli.Messages.RemoteTagDbug1, string(v[1])) ret[i] = string(v[1]) } return ret, nil } // getRepoDir Extract a local dirname from a Git URL. func getRepoDir(repoLocation, refName string) string { if len(repoLocation) < 1 { return repoLocation } baseName := filepath.Base(repoLocation) // trim .git from the end baseName = strings.TrimRight(baseName, ".git") // append ref, branch, or tag if refName != "" { baseName = baseName + "-" + strings.ReplaceAll(refName, "/", "-") } infof(cli.Messages.RepoDir, baseName) return baseName } // isRemoteRepo return true if Git repository is a remote URL or false if local. func isRemoteRepo(repoLocation string) bool { if len(repoLocation) < 1 { return false } // git@github.com:kohirens/tmpltoap.git // https://github.com/kohirens/tmpltoapp.git isGitUri := regexp.MustCompile("^(git|http|https)://.+$") if isGitUri.MatchString(repoLocation) { return true } return false }
//funcoes variativas: recebem parametros variaveis package main import "fmt" func media(numeros ...float64) float64 { //numeros entra como array total := 0.0 for _, num := range numeros { total += num } if total > 0.0 { return total / float64(len(numeros)) } else { return 0.0 } } func main() { fmt.Printf("media eh %f", media()) }
package agent import ( "context" "time" "github.com/MagalixCorp/magalix-agent/v3/proto" "github.com/MagalixTechnologies/uuid-go" ) type Match struct { Namespaces []string Kinds []string Labels []map[string]string } type Constraint struct { Id string TemplateId string AccountId string ClusterId string Name string TemplateName string Parameters map[string]interface{} Match Match Code string Description string HowToSolve string UpdatedAt time.Time CategoryId string Severity string Controls []string Standards []string DeletedAt *string } type AuditResultStatus string const ( AuditResultStatusViolating = "Violation" AuditResultStatusCompliant = "Compliance" AuditResultStatusIgnored = "Ignored" ) type AuditResult struct { Id string TemplateID *string ConstraintID *string CategoryID *string Severity *string Controls []string Standards []string Description string HowToSolve string Status AuditResultStatus Msg *string EntityName *string EntityKind *string NamespaceName *string ParentName *string ParentKind *string EntitySpec map[string]interface{} Trigger string } func (a *AuditResult) GenerateID() *AuditResult { a.Id = uuid.NewV4().String() return a } func (r *AuditResult) ToPacket() *proto.PacketAuditResultItem { item := proto.PacketAuditResultItem{ Id: r.Id, TemplateID: r.TemplateID, ConstraintID: r.ConstraintID, CategoryID: r.CategoryID, Severity: r.Severity, Controls: r.Controls, Standards: r.Standards, Description: r.Description, HowToSolve: r.HowToSolve, Msg: r.Msg, EntityName: r.EntityName, EntityKind: r.EntityKind, NamespaceName: r.NamespaceName, ParentName: r.ParentName, ParentKind: r.ParentKind, EntitySpec: r.EntitySpec, Trigger: r.Trigger, } switch r.Status { case AuditResultStatusViolating: item.Status = proto.AuditResultStatusViolating case AuditResultStatusCompliant: item.Status = proto.AuditResultStatusCompliant case AuditResultStatusIgnored: item.Status = proto.AuditResultStatusIgnored } return &item } type AuditResultHandler func(auditResult []*AuditResult) error type Auditor interface { Start(ctx context.Context) error Stop() error HandleConstraints(constraint []*Constraint) map[string]error HandleAuditCommand() error SetAuditResultHandler(handler AuditResultHandler) }
package models type ConfigModel struct { NsqdAddr string HttpAddr string LookupdAddr string MasterTopic string TopicMaxChannel int N2n2Addr string NodeList []string }
package main import ( "fmt" "github.com/slack-go/slack" ) func main() { api := slack.New("YOUR_TOKEN_HERE") attachment := slack.Attachment{ Pretext: "some pretext", Text: "some text", // Uncomment the following part to send a field too /* Fields: []slack.AttachmentField{ slack.AttachmentField{ Title: "a", Value: "no", }, }, */ } channelID, timestamp, err := api.PostMessage( "CHANNEL_ID", slack.MsgOptionText("Some text", false), slack.MsgOptionAttachments(attachment), slack.MsgOptionAsUser(true), // Add this if you want that the bot would post message as a user, otherwise it will send response using the default slackbot ) if err != nil { fmt.Printf("%s\n", err) return } fmt.Printf("Message successfully sent to channel %s at %s", channelID, timestamp) }
package pie_test import ( "github.com/elliotchance/pie/v2" "github.com/stretchr/testify/assert" "testing" ) func TestStddev(t *testing.T) { assert.Equal(t, 0.0, pie.Stddev([]float64{})) assert.Equal(t, 0.0, pie.Stddev([]float64{1})) assert.Equal(t, 4.8587389053127765, pie.Stddev([]float64{10.0, 12.5, 23.3, 23.1, 16.5, 23.1, 21.2, 16.4})) }
package main func report() { }
/* 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 cli import ( "context" "fmt" "os" "strings" "testing" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "sigs.k8s.io/yaml" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" "github.com/oam-dev/kubevela/pkg/oam/util" "github.com/oam-dev/kubevela/pkg/utils/common" pkgutils "github.com/oam-dev/kubevela/pkg/utils/util" ) var _ = Describe("Test Install Command", func() { BeforeEach(func() { fluxcd := v1beta1.Application{} err := yaml.Unmarshal([]byte(fluxcdYaml), &fluxcd) Expect(err).Should(BeNil()) Expect(k8sClient.Create(context.Background(), &fluxcd)).Should(SatisfyAny(BeNil(), util.AlreadyExistMatcher{})) rollout := v1beta1.Application{} err = yaml.Unmarshal([]byte(rolloutYaml), &rollout) Expect(err).Should(BeNil()) Expect(k8sClient.Create(context.Background(), &rollout)).Should(SatisfyAny(BeNil(), util.AlreadyExistMatcher{})) }) It("Test check addon enabled", func() { addons, err := checkInstallAddon(k8sClient) Expect(err).Should(BeNil()) Expect(len(addons)).Should(BeEquivalentTo(2)) }) It("Test disable all addons", func() { err := forceDisableAddon(context.Background(), k8sClient, cfg) Expect(err).Should(BeNil()) Eventually(func() error { addons, err := checkInstallAddon(k8sClient) if err != nil { return err } if len(addons) != 0 { return fmt.Errorf("%v still exist", addons) } return nil }, 1*time.Minute, 5*time.Second).Should(BeNil()) }) }) func TestUninstall(t *testing.T) { // Test answering NO when prompted. Should just exit. cmd := NewUnInstallCommand(common.Args{}, "", pkgutils.IOStreams{ Out: os.Stdout, In: strings.NewReader("n\n"), }) cmd.SetArgs([]string{}) err := cmd.Execute() assert.Nil(t, err, "should just exit if answer is no") } var fluxcdYaml = ` apiVersion: core.oam.dev/v1beta1 kind: Application metadata: name: addon-fluxcd namespace: vela-system labels: addons.oam.dev/name: fluxcd addons.oam.dev/registry: local addons.oam.dev/version: 1.1.0 spec: components: - name: ns-flux-system properties: apiVersion: v1 kind: Namespace metadata: name: flux-system ` var fluxcdRemoteYaml = ` apiVersion: core.oam.dev/v1beta1 kind: Application metadata: name: addon-fluxcd namespace: vela-system labels: addons.oam.dev/name: fluxcd addons.oam.dev/registry: KubeVela addons.oam.dev/version: 1.1.0 spec: components: - name: ns-flux-system properties: apiVersion: v1 kind: Namespace metadata: name: flux-system ` var rolloutYaml = ` apiVersion: core.oam.dev/v1beta1 kind: Application metadata: name: addon-rollout namespace: vela-system labels: addons.oam.dev/name: rollout spec: components: - name: test-ns properties: apiVersion: v1 kind: Namespace metadata: name: test-ns `
package queue import ( "testing" ) func Test_IsEmpty(t *testing.T) { a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} q := New() for i := range a { q.Push(a[i]) } for !q.IsEmpty() { q.Pop() } }
package errors import ( "fmt" "testing" . "github.com/smartystreets/goconvey/convey" ) func TestIsFatal(t *testing.T) { Convey("Given a no error", t, func() { var err error Convey("When calling IsFatal", func() { f := IsFatal(err) Convey("The result should be false", func() { So(f, ShouldBeFalse) }) }) }) Convey("Given an error that does not implement Fatal", t, func() { err := fmt.Errorf("I'm an error!") Convey("When calling IsFatal", func() { f := IsFatal(err) Convey("The result should be false", func() { So(f, ShouldBeFalse) }) }) }) Convey("Given a non-fatal error that implements Fatal", t, func() { err := fatal{message: "I'm a non-fatal, fatal error", isfatal: false} Convey("When calling IsFatal", func() { f := IsFatal(err) Convey("The result should be false", func() { So(f, ShouldBeFalse) }) }) }) Convey("Given a fatal error that implements Fatal", t, func() { err := fatal{message: "I'm a fatal, fatal error", isfatal: true} Convey("When calling IsFatal", func() { f := IsFatal(err) Convey("The result should be true", func() { So(f, ShouldBeTrue) }) }) }) } func TestFatal(t *testing.T) { Convey("Given a fatal error", t, func() { err := fatal{message: "I'm a fatal, fatal error", isfatal: false} Convey("The error should implement Fatal", func() { _, ok := error(err).(Fatal) So(ok, ShouldBeTrue) }) Convey("When isfatal is set to false", func() { err.isfatal = false Convey("IsFatal() should return false", func() { So(err.IsFatal(), ShouldBeFalse) }) }) Convey("When isfatal is set to true", func() { err.isfatal = true Convey("IsFatal() should return true", func() { So(err.IsFatal(), ShouldBeTrue) }) }) Convey("When calling Error()", func() { err.message = "foo" Convey("The message should be correct", func() { So(err.Error(), ShouldEqual, "foo") }) }) }) } func TestFatalf(t *testing.T) { Convey("Given a new fatal error", t, func() { err := Fatalf("I'm a fatal error!") Convey("The error should implement Fatal", func() { _, ok := err.(Fatal) So(ok, ShouldBeTrue) }) Convey("When IsFatal is called", func() { f := err.(Fatal).IsFatal() Convey("The result should be true", func() { So(f, ShouldBeTrue) }) }) Convey("When calling Error()", func() { Convey("The message should be correct", func() { So(err.Error(), ShouldEqual, "I'm a fatal error!") }) }) }) }
package app type CSVMoveBase struct { ID string Identifier string GenerationID string TypeID string Power string PP string Accuracy string Priority string TargetID string DamageClassID string EffectID string EffectChance string ContestTypeID string ContestEffectID string SuperContestEffectID string } type CSVMoveMeta struct { MoveID string MetaCategoryID string MetaAilmentID string MinHits string MaxHits string MinTurns string MaxTurns string Drain string Healing string CriticalRate string AilmentChance string FlinchChance string StatChance string }
package util import ( "fmt" "github.com/maprost/application/generator/genmodel" "sort" ) func CalculateProfessionalSkills(application *genmodel.Application) ([]genmodel.Skill, error) { return calculateSkills(application.Profile.ProfessionalSkills, application.JobPosition.ProfessionalSkills) } func CalculateSoftSkills(application *genmodel.Application) ([]genmodel.Skill, error) { return calculateSkills(application.Profile.SoftSkills, application.JobPosition.SoftSkills) } func calculateSkills(skillMap map[genmodel.SkillID]genmodel.Skill, neededSkills []genmodel.SkillID) (result []genmodel.Skill, err error) { if len(neededSkills) == 0 { result = convertMapToList(skillMap) return } // collect all needed skills out of the map for _, skillID := range neededSkills { skill, ok := skillMap[skillID] if !ok { err = fmt.Errorf("Can't find skill ID '%v' in the map'%v'", skillID, skillMap) return } result = append(result, skill) } return } // return the map values sorted by ranking func convertMapToList(skillMap map[genmodel.SkillID]genmodel.Skill) (result []genmodel.Skill) { for _, skill := range skillMap { result = append(result, skill) } sort.Slice(result, func(i, j int) bool { return result[i].Rating > result[j].Rating }) return }
// Package worker_pool implements a worker pool pattern with a maximum rate // of work. Consumption from the consumer is throttled by an intermediary // which batches work and places it on a read channel at a pre-specified // interval. package worker_pool import ( "bytes" "fmt" "sync" "time" "github.com/inconshreveable/log15" ) // TimedWorkerPool reads from the queue, batching work and sending it // downstream to be processed by a series of workers only after a minimum // duration BatchInterval. // // This is useful in cases where work involves things like network requests // that can be batched together to minimize network congestion. type TimedWorkerPool struct { cfg Config logger log15.Logger queue chan *Payload done chan struct{} wg sync.WaitGroup closeOnce sync.Once } // Config defines configuration for TimedWorkerPool. type Config struct { BatchInterval time.Duration WorkerCount int Retries int Debug bool } // Payload defines a sample payload. type Payload struct { // Sample payload text string } // NewTimedWorkerPool creates a new default TimedWorkerPool. func NewTimedWorkerPool(cfg Config, logger log15.Logger, queue chan *Payload) (*TimedWorkerPool, error) { wp := &TimedWorkerPool{ cfg: cfg, logger: logger, done: make(chan struct{}), queue: queue, } sendCh := wp.batcher() wp.startWorkers(cfg.WorkerCount, sendCh) return wp, nil } // Close closes the done chan and waits for all workers to complete. To ensure // no items are placed on the queue after Close is called, the sender should // close the queue chan before calling Close. // // Close can be called more than once. func (wp *TimedWorkerPool) Close() error { wp.closeOnce.Do(func() { close(wp.done) wp.wg.Wait() }) return nil } // batcher periodically flushes the queue and places a batch of payloads on // sendCh. This ensures work is not done at a rate faster than BatchInterval. // // batcher owns sendCh and closes it on cancellation. In the case of panic, // recovery occurs by closing sendCh, restarting batcher and starting a new // set of workers. func (wp *TimedWorkerPool) batcher() <-chan []*Payload { sendCh := make(chan []*Payload) flush := func() { var payloads []*Payload for i, j := 0, len(wp.queue); i < j; i++ { payloads = append(payloads, <-wp.queue) } if len(payloads) > 0 { sendCh <- payloads } } go func() { defer func() { if r := recover(); r != nil { wp.logger.Crit("Panic occurred in batcher. Shutting down workers and restarting", "err", r) close(sendCh) sendChRecv := wp.batcher() wp.startWorkers(wp.cfg.WorkerCount, sendChRecv) } }() ticker := time.NewTicker(wp.cfg.BatchInterval) for { select { case <-ticker.C: flush() case <-wp.done: flush() ticker.Stop() close(sendCh) return } } }() return sendCh } // startWorkers spins up workers which consume batches of work from sendCh. // Workers synchronously call doWork(). func (wp *TimedWorkerPool) startWorkers(num int, sendCh <-chan []*Payload) { for i := 0; i < num; i++ { wp.wg.Add(1) go func() { defer func() { if r := recover(); r != nil { wp.logger.Crit("Panic occurred in worker. Restarting worker", "err", r) wp.startWorkers(1, sendCh) } }() defer wp.wg.Done() for payloads := range sendCh { wp.doWork(payloads) } }() } } // doWork does work and handles retries. func (wp *TimedWorkerPool) doWork(payloads []*Payload) (err error) { if wp.cfg.Debug { var s bytes.Buffer s.WriteByte('\n') for i, p := range payloads { s.WriteString(fmt.Sprintf("Payload %d: %+v\n", i, *p)) } wp.logger.Debug("Doing work for the next batch of payloads", "len_payloads", len(payloads), "dump", s.String()) } for i := 0; i <= wp.cfg.Retries; i++ { // Do some work that returns an error. if err == nil { return nil } wp.logger.Warn("Doing work failed, retrying...", "err", err) } wp.logger.Error("Doing work failed permanently", "err", err) return err }
// Copyright (c) 2020 by meng. All rights reserved. // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. /** * @Author: meng * @Description: * @File: entitymgr * @Version: 1.0.0 * @Date: 2020/4/11 22:05 */ package entity import "sync" var entityMgr *EntityMgr var once sync.Once // 实体管理器 type EntityMgr struct { entitys map[uint]*Entity } func NewEntityMgr() *EntityMgr { once.Do(func() { entityMgr = &EntityMgr{entitys: map[uint]*Entity{}} }) return entityMgr } func (this *EntityMgr) AddEntity(entity *Entity) bool { if nil == entity { return false } _, ok := this.entitys[entity.GetID()] if ok { return true } this.entitys[entity.GetID()] = entity return true } func (this *EntityMgr) DeleteEntity(entity *Entity) bool { if entity == nil { return false } delete(this.entitys, entity.GetID()) return true } func (this *EntityMgr) Update() { //for key, entity := range this.entitys { // // } }
/* Copyright © 2021 Faruk AK <kakuraf@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "github.com/spf13/cobra" ) // ec2Cmd represents the ec2 command var ec2Cmd = &cobra.Command{ Use: "ec2", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("ec2 called") instanceName, _ := cmd.Flags().GetString("instanceName") // ./terrathor provider --region=eu-west-1 instanceType, _ := cmd.Flags().GetString("instanceType") //availabilityZone, _ := cmd.Flags().GetString("availabilityZone") test, _ := cmd.Flags().GetString("test") if instanceName != "" && instanceType != "" { CreateEC2Module("modules/ec2", instanceName, test) //CreateEC2("test", instanceName, availabilityZone, instanceType) } }, } func init() { rootCmd.AddCommand(ec2Cmd) ec2Cmd.PersistentFlags().String("instanceName", "", "EC2 resource name") ec2Cmd.PersistentFlags().String("instanceType", "", "Instance type") ec2Cmd.PersistentFlags().String("availabilityZone", "", "Availability zone") ec2Cmd.MarkPersistentFlagRequired("instanceName") ec2Cmd.MarkPersistentFlagRequired("instanceType") ec2Cmd.MarkPersistentFlagRequired("availabilityZone") } func CreateEC2Module(folderName string, instanceName string, test string) { vars := make(map[string]string) vars["instance_name"] = instanceName vars["test"] = test pies := []File{ { TemplatePath: "./templates/ec2/main.tmpl", FilePath: "modules/ec2/main.tf", FolderPath: folderName, }, { TemplatePath: "./templates/ec2/outputs.tmpl", FilePath: "modules/ec2/outputs.tf", FolderPath: folderName, }, { TemplatePath: "./templates/ec2/data.tmpl", FilePath: "modules/ec2/data.tf", FolderPath: folderName, }, } for _, p := range pies { p.CreateFolder() t := p.Parse() fs := p.CreateFile() err := t.Execute(fs, vars) p.ErrorHandler(err) defer fs.Close() } } func CreateEC2(folderName string, instanceName string, availabilityZone string, instanceType string) { vars := make(map[string]string) vars["instance_name"] = instanceName vars["availability_zone"] = availabilityZone vars["instance_type"] = instanceType p := &File{ TemplatePath: "./templates/ec2/ec2.tmpl", FilePath: "test/ec2.tf", FolderPath: folderName, } p.CreateFolder() t := p.Parse() fs := p.CreateFile() err := t.Execute(fs, vars) p.ErrorHandler(err) defer fs.Close() }
package server import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "testing" restful "github.com/emicklei/go-restful" "github.com/stretchr/testify/suite" "go-gcs/src/config" "go-gcs/src/entity" "go-gcs/src/service" "go-gcs/src/service/googlecloud/storageprovider" ) type StorageSuite struct { suite.Suite sp *service.Container wc *restful.Container JWTBearer string } func (suite *StorageSuite) SetupSuite() { cf := config.MustRead("../../config/testing.json") sp := service.NewForTesting(cf) // init service provider suite.sp = sp // init restful container suite.wc = restful.NewContainer() storageService := newStorageService(suite.sp) suite.wc.Add(storageService) token, err := generateToken("myAwesomeId", sp.Config.JWTSecretKey) suite.NotEmpty(token) suite.NoError(err) suite.JWTBearer = "Bearer " + token } func TestStorageSuite(t *testing.T) { suite.Run(t, new(StorageSuite)) } func (suite *StorageSuite) TestCreateGCSSignedUrl() { to := "myAwesomeBuddyId" singlePayload := entity.SinglePayload{ To: to, } bodyBytes, err := json.MarshalIndent(singlePayload, "", " ") suite.NoError(err) fileName := "cat.jpg" contentType := "image/jpeg" tag := "single" signedUrlRequest := entity.SignedUrlRequest{ FileName: fileName, ContentType: contentType, Tag: tag, Payload: string(bodyBytes), } bodyBytes, err = json.MarshalIndent(signedUrlRequest, "", " ") suite.NoError(err) bodyReader := strings.NewReader(string(bodyBytes)) httpRequest, err := http.NewRequest("POST", "http://localhost:7890/v1/storage/signurl", bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpRequest.Header.Add("Authorization", suite.JWTBearer) httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusOK, httpWriter) signedUrl := entity.SignedUrl{} err = json.Unmarshal(httpWriter.Body.Bytes(), &signedUrl) suite.NoError(err) suite.Equal(contentType, signedUrl.UploadHeaders.ContentType) suite.Equal(suite.sp.GoogleCloudStorage.Config.ContentLengthRange, signedUrl.UploadHeaders.ContentLengthRange) } func (suite *StorageSuite) TestResizeGCSImage() { bucket := suite.sp.GoogleCloudStorage.Config.Bucket path := "test/cat.jpg" filePath := "../../test/image/cat.jpg" err := suite.sp.GoogleCloudStorage.Upload(bucket, path, filePath) suite.NoError(err) gcsPublicBaseUrl := storageprovider.GoogleCloudStoragePublicBaseUrl url := fmt.Sprintf("%s/%s/%s", gcsPublicBaseUrl, bucket, path) contentType := "image/jpeg" resizeImageRequest := entity.ResizeImageRequest{ Url: url, ContentType: contentType, } bodyBytes, err := json.MarshalIndent(resizeImageRequest, "", " ") suite.NoError(err) bodyReader := strings.NewReader(string(bodyBytes)) httpRequest, err := http.NewRequest("POST", "http://localhost:7890/v1/storage/resize/image", bodyReader) suite.NoError(err) httpRequest.Header.Add("Content-Type", "application/json") httpWriter := httptest.NewRecorder() suite.wc.Dispatch(httpWriter, httpRequest) assertResponseCode(suite.T(), http.StatusOK, httpWriter) resizeImage := entity.ResizeImage{} err = json.Unmarshal(httpWriter.Body.Bytes(), &resizeImage) suite.NoError(err) imageResizeBucket := suite.sp.GoogleCloudStorage.Config.ImageResizeBucket url = fmt.Sprintf("%s/%s/%s", gcsPublicBaseUrl, imageResizeBucket, path) suite.Equal(url, resizeImage.Origin) suite.Equal(url+"_100", resizeImage.ThumbWidth100) suite.Equal(url+"_150", resizeImage.ThumbWidth150) suite.Equal(url+"_300", resizeImage.ThumbWidth300) suite.Equal(url+"_640", resizeImage.ThumbWidth640) suite.Equal(url+"_1080", resizeImage.ThumbWidth1080) }
package main import ( "healthybank.com/healthybank/api" "healthybank.com/healthybank/financial_project" ) func main() { // client := clients.New() // if err := client.GetAccountInformation(); err != nil { // fmt.Errorf("%s", err) // } svc := financial_project.New() fpHandler := api.New(svc) fpHandler.Start() }
package main import ( "flag" "fmt" "log" "net/http" "github.com/boltdb/bolt" ) var ( port = flag.Int("port", 8080, "port to run on") db = flag.String("db", "bolt.db", "bolt db file") ) func main() { flag.Parse() db, err := bolt.Open(*db, 0600, nil) if err != nil { log.Fatal(err) } defer db.Close() s := &Server{db} log.Println("server start") log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), s)) }
package orm import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/klogr" "github.com/isutton/orchid/pkg/orchid/config" "github.com/isutton/orchid/test/mocks" ) func TestORM_New(t *testing.T) { logger := klogr.New().WithName("test") config := &config.Config{Username: "postgres", Password: "1", Options: "sslmode=disable"} pgORM := NewORM(logger, "postgres", "public", config) t.Run("Bootstrap", func(t *testing.T) { err := pgORM.Bootstrap() assert.NoError(t, err) }) openAPIV3Schema := mocks.OpenAPIV3SchemaMock() schema := NewSchema(logger, "cr") t.Run("CreateSchemaTables", func(t *testing.T) { err := schema.Generate(&openAPIV3Schema) assert.NoError(t, err) err = pgORM.CreateTables(schema) assert.NoError(t, err) }) // t.Run("Create", func(t *testing.T) { // arguments := mocks.RepositoryArgumentsMock() // err := orm.Create(schema, arguments) // require.NoError(t, err) // }) t.Run("Read", func(t *testing.T) { namespacedName := types.NamespacedName{Namespace: "namespace", Name: "testing"} data, err := pgORM.Read(schema, namespacedName) assert.NoError(t, err) t.Logf("data='%+v'", data) }) }
package parser import ( "strings" "testing" ) func TestParser(t *testing.T) { input := "//hello\n D=M;JMP//hello\n@111 // jfajfjfj j" p := New(strings.NewReader(input)) line := 0 p.Advance(&line) t.Logf("p %+v line %d", p, line) p.Advance(&line) t.Logf("p %+v line %d", p, line) p.Advance(&line) t.Logf("p %+v line %d", p, line) }
// Copyright (c) 2022 Target Brands, Inc. All rights reserved. // // Use of this source code is governed by the LICENSE file in this repository. package vela import ( "reflect" "testing" ) func TestVela_Bool(t *testing.T) { // setup types _bool := false want := &_bool // run test got := Bool(_bool) if !reflect.DeepEqual(got, want) { t.Errorf("Bool is %v, want %v", got, want) } } func TestVela_Bytes(t *testing.T) { // setup types _bytes := []byte("foo") want := &_bytes // run test got := Bytes(_bytes) if !reflect.DeepEqual(got, want) { t.Errorf("Bytes is %v, want %v", got, want) } } func TestVela_Int(t *testing.T) { // setup types _int := 1 want := &_int // run test got := Int(_int) if !reflect.DeepEqual(got, want) { t.Errorf("Int is %v, want %v", got, want) } } func TestVela_Int64(t *testing.T) { // setup types _int64 := int64(1) want := &_int64 // run test got := Int64(_int64) if !reflect.DeepEqual(got, want) { t.Errorf("Int64 is %v, want %v", got, want) } } func TestVela_String(t *testing.T) { // setup types _string := "foo" want := &_string // run test got := String(_string) if !reflect.DeepEqual(got, want) { t.Errorf("String is %v, want %v", got, want) } } func TestVela_Strings(t *testing.T) { // setup types _strings := []string{"foo"} want := &_strings // run test got := Strings(_strings) if !reflect.DeepEqual(got, want) { t.Errorf("Strings is %v, want %v", got, want) } }
package validation import "regexp" const ( usernamePattern = `^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$` passwordPattern = `^[a-z0-9A-Z@._\-]{8,20}$` ) // IsUsername 檢驗是否為合法用戶名,合法字符有 0-9, A-Z, a-z,合法字符長度{8,20} func IsUsername(name string) bool { changeNameType := []byte(name) usernameRegexp := regexp.MustCompile(usernamePattern) return usernameRegexp.Match(changeNameType) } // IsPassword 檢驗是否為合法密碼,合法字符有 0-9, A-Z, a-z,合法字符長度{8,20} func IsPassword(Password string) bool { changePasswordType := []byte(Password) userPasswordRegexp := regexp.MustCompile(passwordPattern) return userPasswordRegexp.Match(changePasswordType) }
package sound import ( "context" "database/sql" "errors" "fmt" "log" "mime/multipart" "net/http" "os" "path" "strconv" "strings" "github.com/volatiletech/null" "github.com/ericlagergren/decimal" "github.com/gin-gonic/gin" "github.com/satori/go.uuid" "github.com/volatiletech/sqlboiler/boil" "github.com/volatiletech/sqlboiler/queries" "github.com/volatiletech/sqlboiler/queries/qm" "github.com/volatiletech/sqlboiler/types" "github.com/javiercbk/jayoak/api/sound/spectrum" "github.com/javiercbk/jayoak/files" "github.com/javiercbk/jayoak/http/response" "github.com/javiercbk/jayoak/http/session" "github.com/javiercbk/jayoak/models" ) // ErrInstrumentNotFound is an error thrown when an instrument was not found in the database var ErrInstrumentNotFound = errors.New("instrument was not found in the database") // ErrUnexpectedRowsAffectedCount is an error thrown when updating a sound and rows affected count is not expected var ErrUnexpectedRowsAffectedCount = errors.New("unexpected rows affected count") // soundProcessingStrategy is a function that process an audio files and stores the frequencies in the database type soundProcessingStrategy func(userID, instrumentID, soundUUID, extension string, soundID int64) error type open interface { Open() (multipart.File, error) } type soundSearch struct { ID int64 `uri:"soundID" binding:"required,numeric"` } type prospectSound struct { Name *string `json:"name,omitempty" binding:"length(1,256),optional"` AudioFileName string `json:"audioFileName" binding:"length(1,256)"` FileFactory open `json:"-"` InstrumentID *int64 `json:"instrumentId,omitempty" binding:"numeric,optional"` Note *string `json:"note,omitempty" binding:"in(a,b,c,d,e,f,g,a#,b#,c#,d#,e#,f#,g#,ab,bb,cb,db,eb,fb,gb),optional"` } // Handlers defines a handler for sound type Handlers struct { logger *log.Logger db *sql.DB repository files.Repository } // NewHandlers creates a new handler for sound func NewHandlers(logger *log.Logger, db *sql.DB, repository files.Repository) *Handlers { return &Handlers{ logger: logger, db: db, repository: repository, } } // FindSound find an audio clip in the database func (h *Handlers) Retrieve(c *gin.Context) { var search soundSearch user := session.RetrieveUser(c) err := c.ShouldBind(&search) if err != nil { response.NewErrorResponse(c, http.StatusBadRequest, "error binding sound search params") return } sound, err := models.Sounds(qm.Where("id = ? AND organization_id", search.ID, user.OrganizationID)).One(c, h.db) if err != nil { h.logger.Printf("error retriving sound %d: %v\n", search.ID, err) response.NewErrorResponse(c, http.StatusInternalServerError, "error retrieving sound from the database") return } response.NewSuccessResponse(c, *sound) } // PostSound creates an audio, analizes it and stores it in the database func (h *Handlers) PostSound(c *gin.Context) { var pSound prospectSound user := session.RetrieveUser(c) err := c.ShouldBindJSON(&pSound) if err != nil { response.NewErrorResponse(c, http.StatusBadRequest, err.Error()) return } if pSound.InstrumentID == nil && pSound.Note != nil { response.NewErrorResponse(c, http.StatusBadRequest, "note was provided with no instrument") return } if pSound.InstrumentID != nil && pSound.Note == nil { response.NewErrorResponse(c, http.StatusBadRequest, "instrument was provided with no note") return } file, err := c.FormFile("audio") if err != nil { h.logger.Printf("error retrieving uploaded file: %s\n", err) response.NewErrorResponse(c, http.StatusBadRequest, "no sound file provided") return } pSound.FileFactory = file sound, err := h.CreateSound(c, user, pSound, h.processSound) if err != nil { h.logger.Printf("error creating sound: %s\n", err) response.NewErrorResponse(c, http.StatusBadRequest, "no sound file provided") return } response.NewSuccessResponse(c, *sound) } // Routes initializes the routes for the audio handlers func (h *Handlers) Routes(rg *gin.RouterGroup) { rg.GET("/sound/:soundId", h.Retrieve) rg.POST("/sound", h.PostSound) } // non HTTP Handlers // CreateSound creates a sound with a validated prospect audio. func (h *Handlers) CreateSound(ctx context.Context, user session.User, pSound prospectSound, strategy soundProcessingStrategy) (*models.Sound, error) { var instrumentStr string isNote := false extension := path.Ext(pSound.AudioFileName) if pSound.InstrumentID != nil { isNote = true instrumentStr = strconv.FormatInt(*pSound.InstrumentID, 10) } h.logger.Println("will write audio file") file, err := pSound.FileFactory.Open() if err != nil { h.logger.Printf("error opening uploaded file: %s\n", err) } defer file.Close() soundUUID := uuid.NewV4().String() soundFile, err := h.repository.SoundFile(strconv.FormatInt(user.ID, 10), instrumentStr, soundUUID, extension, os.O_WRONLY|os.O_CREATE|os.O_TRUNC) if err != nil { h.logger.Printf("error retrieving sound file: %s\n", err) return nil, err } wi, err := files.WriteWithMetadata(soundFile, file, files.Checksum|files.MIME) if err != nil { h.logger.Printf("error writing sound with metadata: %s\n", err) return nil, err } // we cannot defer this call in the case we have to delete the file // if the sound fails to be stored in the db err = soundFile.Close() if err != nil { h.logger.Printf("error closing sound file: %s\n", err) return nil, err } h.logger.Printf("%d bytes were written to the audio file with MIME %s and checksum %s\n", wi.Written, wi.MimeType, wi.Checksum) sound := &models.Sound{ AudioFileName: pSound.AudioFileName, MD5File: fmt.Sprintf("%x", wi.Checksum), MimeType: wi.MimeType, AudioUUID: soundUUID, OrganizationID: user.OrganizationID, CreatorID: user.ID, } if isNote { instrument, err := models.Instruments(qm.Where("id = ? AND organization_id = ?", pSound.InstrumentID, user.ID)).One(ctx, h.db) if err != nil { h.logger.Printf("error retrieving instrument %d for user %d: %s\n", pSound.InstrumentID, user.ID, err) return nil, err } if instrument == nil { return nil, ErrInstrumentNotFound } sound.InstrumentID = null.Int64FromPtr(pSound.InstrumentID) sound.Note = null.StringFromPtr(pSound.Note) } else { sound.Name = null.StringFromPtr(pSound.Name) } err = sound.Insert(ctx, h.db, boil.Infer()) if err != nil { h.logger.Printf("error saving sound: %s\n", err) errFile := h.repository.RemoveSound(strconv.FormatInt(user.ID, 10), instrumentStr, soundUUID, extension) if errFile != nil { h.logger.Printf("error removing sound file after failing to save soun in the db: %s\n", errFile) } return nil, err } err = strategy(strconv.FormatInt(user.ID, 10), instrumentStr, soundUUID, extension, sound.ID) if err != nil { h.logger.Printf("error retrieving instrument %d for user %d: %s\n", pSound.InstrumentID, user.ID, err) } // if an error was thrown when processing the audio then return both the sound and the error // FIXME: implement a transaction commit here return sound, err } // ProcessSound finds a sound file and reads it to extract the frequencies with the intensity and saves it to the frequency table func (h *Handlers) ProcessSound(userID, instrumentID, soundUUID, extension string, soundID int64) error { return h.processSound(userID, instrumentID, soundUUID, extension, soundID, false) } // ProcessSoundNoFK does the same that ProcessSound but disables the foreign key for faster insertion func (h *Handlers) ProcessSoundNoFK(userID, instrumentID, soundUUID, extension string, soundID int64) error { return h.processSound(userID, instrumentID, soundUUID, extension, soundID, false) } func (h *Handlers) analyzeFrequencies(userID, instrumentID, soundUUID, extension string) (spectrum.FrequenciesAnalysis, error) { var freqAnalysis spectrum.FrequenciesAnalysis soundFile, err := h.repository.SoundFile(userID, instrumentID, soundUUID, extension, os.O_RDONLY) if err != nil { h.logger.Printf("error while processing. Could not retrieve sound file: %s\n", err) return freqAnalysis, err } defer soundFile.Close() pcm, sampleRate, err := spectrum.PCMFromWav(soundFile) if err != nil { h.logger.Printf("error extracting PCM from wav file %s: %s\n", soundUUID, err) return freqAnalysis, err } return spectrum.FrequenciesSpectrumAnalysis(pcm, sampleRate) } // processSound process a wav file and stores the frequencies in a separated table func (h *Handlers) processSound(userID, instrumentID, soundUUID, extension string, soundID int64, disableForeignKey bool) error { ctx := context.Background() freqAnalysis, err := h.analyzeFrequencies(userID, instrumentID, soundUUID, extension) if err != nil { h.logger.Printf("error building spectrum for wav file %s: %s\n", soundUUID, err) return err } updateCols := models.M{ models.SoundColumns.MaxFrequency: freqAnalysis.MaxFreq, models.SoundColumns.MinFrequency: freqAnalysis.MinFreq, models.SoundColumns.MaxPowerFreq: freqAnalysis.MaxPower.Freq, models.SoundColumns.MaxPowerValue: freqAnalysis.MaxPower.Value, } rowsAff, err := models.Sounds(qm.Where("id = ?", soundID)).UpdateAll(ctx, h.db, updateCols) if err != nil { h.logger.Printf("error updating sound %s: %s\n", soundUUID, err) return err } if rowsAff != 1 { h.logger.Printf("unexpected rows affected count %d for sound %s\n", rowsAff, soundUUID) return ErrUnexpectedRowsAffectedCount } var bigInsert strings.Builder if disableForeignKey { fmt.Fprintf(&bigInsert, "ALTER TABLE frequencies DISABLE TRIGGER ALL;\n") } fmt.Fprintf(&bigInsert, "INSERT INTO frequencies (sound_id, frequency, spl) VALUES ") first := true for freq, val := range freqAnalysis.Spectrum { if first { first = false } else { bigInsert.WriteString(",") } fmt.Fprintf(&bigInsert, "(%d, %d, %f)", soundID, freq, val) } bigInsert.WriteString(";") if disableForeignKey { fmt.Fprintf(&bigInsert, "\nALTER TABLE frequencies ENABLE TRIGGER ALL;") } result, err := queries.Raw(bigInsert.String()).ExecContext(ctx, h.db) if err != nil { h.logger.Printf("error inserting all frequencies for sound %s: %s\n", soundUUID, err) return err } h.logger.Printf("inserted all frequencies for sound %s:%v\n", soundUUID, result) return nil }
/**************************************************************************** * Copyright 2019, Optimizely, Inc. and contributors * * * * 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 evaluator // package evaluator import ( "github.com/optimizely/go-sdk/pkg/entities" ) // AudienceEvaluator evaluates an audience against the given user's attributes type AudienceEvaluator interface { Evaluate(audience entities.Audience, condTreeParams *entities.TreeParameters) bool } // TypedAudienceEvaluator evaluates typed audiences type TypedAudienceEvaluator struct { conditionTreeEvaluator TreeEvaluator } // NewTypedAudienceEvaluator creates a new instance of the TypedAudienceEvaluator func NewTypedAudienceEvaluator() *TypedAudienceEvaluator { conditionTreeEvaluator := NewMixedTreeEvaluator() return &TypedAudienceEvaluator{ conditionTreeEvaluator: *conditionTreeEvaluator, } } // Evaluate evaluates the typed audience against the given user's attributes func (a TypedAudienceEvaluator) Evaluate(audience entities.Audience, condTreeParams *entities.TreeParameters) (evalResult, isValid bool) { return a.conditionTreeEvaluator.Evaluate(audience.ConditionTree, condTreeParams) }
package poly2tri type AdvancingFront struct { head *Node tail *Node search_node *Node } func NewAdvancingFront(head, tail *Node) *AdvancingFront { af := &AdvancingFront{} af.Init(head, tail) return af } func (this *AdvancingFront) Init(head, tail *Node) { /** @type {Node} */ this.head = head /** @type {Node} */ this.tail = tail /** @type {Node} */ this.search_node = head } func (this *AdvancingFront) locateNode(x float32) *Node { node := this.search_node if x < node.value { for node = node.prev; node != nil; node = node.prev { if x >= node.value { this.search_node = node return node } } } else { for node = node.next; node != nil; node = node.next { if x < node.value { this.search_node = node.prev return node.prev } } } return nil } func (this *AdvancingFront) locatePoint(point *Point) *Node { px := point.x node := this.search_node nx := node.point.x if px == nx { // Here we are comparing point references, not values if point != node.point { // We might have two nodes with same x value for a short time if point == node.prev.point { node = node.prev } else if point == node.next.point { node = node.next } else { panic("poly2tri Invalid AdvancingFront.locatePoint() call") } } } else if px < nx { /* jshint boss:true */ for node = node.prev; node != nil; node = node.prev { if point == node.point { break } } } else { for node = node.next; node != nil; node = node.next { if point == node.point { break } } } if node != nil { this.search_node = node } return node }
// Scrape `sys_m_license`. package collector import ( "context" "database/sql" _ "github.com/SAP/go-hdb/driver" "go.opencensus.io/stats" "go.opencensus.io/stats/view" "go.opencensus.io/tag" "go.opencensus.io/trace" "log" ) const ( // Scrape query. licenseStatusQuery = `select hardware_key,system_id,product_limit,days_between(TO_SECONDDATE(CURRENT_TIMESTAMP),TO_SECONDDATE(expiration_date)) as expire_days from sys.m_license` // Subsystem. licenseStatus = "sys_m_license" ) var ( hardwareKeyTag, _ = tag.NewKey("hardwareKey") systemIdTag, _ = tag.NewKey("systemId") productLimitTag, _ = tag.NewKey("productLimit") expire_days_measure = stats.Int64("expire_days", "Expired Days.", "Days") expireDaysView = &view.View{ Name: "sys_m_license/expire_days", Description: "License Expired Days.", TagKeys: []tag.Key{hardwareKeyTag, systemIdTag, productLimitTag}, Measure: expire_days_measure, Aggregation: view.LastValue(), } LicenseCollectorViews = []*view.View{ expireDaysView, } ) // ScrapeserviceStatistics collects from `sys.m_service_statistics`. type LicenseCollector struct{} func (LicenseCollector) CollectorName() string { return "LicenseCollector" } func (LicenseCollector) Views() []*view.View { return LicenseCollectorViews } func (LicenseCollector) Scrape(ctx context.Context, db *sql.DB) { ctx, span := trace.StartSpan(ctx, "sql_query_sys_m_license") span.Annotate([]trace.Attribute{trace.StringAttribute("step", "excute_sql_query_sys_m_license")}, "excuting sql_query_sys_m_license sql to get the license info and exported as metrics") //get the sql data defer span.End() // if muliple row returned licenseRow := db.QueryRowContext(ctx, licenseStatusQuery) var hardware_key string var system_id string var product_limit string var expire_days int64 sqlRowsScanCtx, sqlRowsScanSpan := trace.StartSpan(ctx, "sql_row_scan") sqlRowsScanSpan.Annotate([]trace.Attribute{trace.StringAttribute("step", "get the value from sql returns and update it to variables")}, "get the value from sql returns and update it to variables") err := licenseRow.Scan(&hardware_key, &system_id, &product_limit, &expire_days) switch { case err == sql.ErrNoRows: log.Printf("No value returend") sqlRowsScanSpan.Annotate([]trace.Attribute{}, "no rows returned") case err != nil: log.Fatal(err) sqlRowsScanSpan.Annotate([]trace.Attribute{}, err.Error()) } defer sqlRowsScanSpan.End() measureSetCtx, measureSetCtxSpan := trace.StartSpan(sqlRowsScanCtx, "measure_value_set") measureSetCtxSpan.Annotate([]trace.Attribute{trace.StringAttribute("step", "update_the_measurement")}, "use the variables to update the measurements") licensectx, err := tag.New(measureSetCtx, tag.Insert(hardwareKeyTag, hardware_key), tag.Insert(systemIdTag, system_id), tag.Insert(productLimitTag, product_limit), ) if err != nil { log.Fatalf("Failed to insert tag: %v", err) measureSetCtxSpan.Annotate([]trace.Attribute{}, err.Error()) } stats.Record(licensectx, expire_days_measure.M(expire_days)) measureSetCtxSpan.End() }