text
stringlengths
11
4.05M
package file_service import ( "fmt" "github.com/akrylysov/pogreb" "log" "ms/sun/servises/file_service/file_common" "ms/sun/servises/file_service/file_disk_cache" "ms/sun/shared/helper" "net/http" ) type retryHttp struct { cat file_common.FileCategory w http.ResponseWriter r *http.Request row *file_common.RowReq tryed int fileStoredIdLoaded bool success bool handelded bool markForRetry bool wrap *httpWirterWrapper } func (t *retryHttp) ServeHTTP(w http.ResponseWriter, r *http.Request) { t.r = r t.w = w t.wrap = &httpWirterWrapper{ w: t.w, r: t.r, } if _row, ok := RowCache.Get(r.URL.Path); ok { if row2, ok := _row.(*file_common.RowReq); ok { t.wrap.req = *row2 defer func() { httpMonitorChan <- t.wrap }() //fmt.Println("memory", row2.MemoryCacheFinalFullPathFile, r.URL.Path) http.ServeFile(t.wrap, r, row2.MemoryCacheFinalFullPathFile) return } } //load real loacal db t.row = file_common.NewRowReq(t.cat, r.URL) t.wrap.req = *t.row defer func() { httpMonitorChan <- t.wrap }() if t.row.Err != nil { t.httpError(t.row.Err.Error(), http.StatusBadRequest) return } fileSoteIdStr, err := localdb.Get([]byte(fmt.Sprintf("%d", t.row.FileRefId))) fileSoteId := helper.StrToInt(string(fileSoteIdStr), 0) if err == nil && fileSoteId > 0 { t.fileStoredIdLoaded = true t.row.SetNewFileDataStoreId(fileSoteId) t.tryServerMore() } else { //load from cassandra //todo can improve this if file existes on disk loadOriginalFromStore(t) t.tryServerMore() } if t.markForRetry && !t.handelded { //t.tryServerMore() } if !t.handelded { http.NotFound(t.wrap, t.r) } } func (t *retryHttp) httpError(err string, code int) { t.success = false t.handelded = true http.Error(t.wrap, err, code) } func (t *retryHttp) httpServeFile(filePath string) { t.success = true t.handelded = true //cache it RowCache.Set(t.row.FullUrlPath, t.row, 0) t.row.MemoryCacheFinalFullPathFile = filePath http.ServeFile(t.wrap, t.r, filePath) } func (t *retryHttp) tryServerMore() { t.wrap = &httpWirterWrapper{ w: t.w, r: t.r, } //row := file_common.NewRowReq(category, r.URL) row := t.row file_disk_cache.SelectDisk(row, config) //t.wrap.req = row //fmt.Println("111111111111***************************") //defer func() { // //fmt.Println("***************************") // httpMonitorChan <- t.wrap //}() //helper.PertyPrint(t.row) if row == nil { t.handelded = true http.NotFound(t.wrap, t.r) return } if row.Err != nil { t.httpError(row.Err.Error(), http.StatusBadRequest) return } switch { case row.RequestedImageSize > 0: serveResizeHTTP(t) case row.IsThumb: serveThumbHTTP(t) default: serveOriginalHTTP(t) } } var localdb *pogreb.DB func openLoaclDb() { //ooption := pogreb.Options{ // BackgroundSyncInterval: //} connected := false var err error for i := 1; i < 10; i++ { if connected { break } name := fmt.Sprintf("local_file_ref%d.localdb", i) localdb, err = pogreb.Open(name, nil) if err == nil { //log.Fatal(err) connected = true } } if !connected { log.Fatal(err) } }
package models import ( "encoding/json" "github.com/astaxie/beego/orm" "github.com/imsilence/gocmdb/server/cloud" ) type Asset struct { Model Id int `orm:"column(id);" json:"id"` Name string `orm:"column(name);size(64);" json:"name"` IP string `orm:"column(ip);size(256);" json:"ip"` Type string `orm:"column(type);size(32);" json:"type"` Application string `orm:"column(application);size(256);" json:"application"` Manager int `orm:"column(manager);" json:"manager"` Remark string `orm:"column(remark);size(1024);" json:"remark"` Agent string `orm:"column(agent);size(64);" json:"uuid"` Instance string `orm:"column(instance);size(64);" json:"instance"` InstanceDesc string `orm:"column(instance_desc); type(text);" json:"instance_desc"` CreateUser int `orm:"column(create_user);default(0);" json:"create_user"` } func (a *Asset) CreateOrReplace(instances []*cloud.Instance) { ormer := orm.NewOrm() for _, instance := range instances { obj := &Asset{Instance: instance.UUID} if _, _, err := ormer.ReadOrCreate(obj, "Instance"); err != nil { continue } obj.Name = instance.Name ip := "" if len(instance.PublicAddrs) > 0 { ip = instance.PublicAddrs[0] } else if len(instance.PrivateAddrs) > 0 { ip = instance.PrivateAddrs[0] } obj.IP = ip obj.Type = "虚拟机" if desc, err := json.Marshal(instance); err != nil { obj.InstanceDesc = string(desc) } ormer.Update(obj) } } func init() { orm.RegisterModel(new(Asset)) }
// Copyright 2013 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //Echo writes its arguments separated by blanks and terminated by a newline on the standard output. package main import ( "flag" "fmt" "io" "os" "strings" ) var nonewline = flag.Bool("n", false, "suppress newline") func echo(w io.Writer, s ...string) error { _, err := fmt.Fprintf(w, "%s", strings.Join(s, " ")) if !*nonewline { fmt.Fprint(w, "\n") } return err } func main() { flag.Parse() echo(os.Stdout, flag.Args()...) }
package solo import ( "github.com/iotaledger/wasp/packages/coretypes/requestargs" "github.com/iotaledger/wasp/packages/hashing" "github.com/stretchr/testify/require" "testing" ) func TestPutBlobData(t *testing.T) { env := New(t, false, false) data := []byte("data-datadatadatadatadatadatadatadata") h := env.PutBlobDataIntoRegistry(data) require.EqualValues(t, h, hashing.HashData(data)) p := requestargs.New(nil) h1 := p.AddAsBlobRef("dataName", data) require.EqualValues(env.T, h, h1) sargs, ok, err := p.SolidifyRequestArguments(env.registry) require.NoError(env.T, err) require.True(env.T, ok) require.Len(env.T, sargs, 1) require.EqualValues(env.T, data, sargs.MustGet("dataName")) }
package database import ( "go.mongodb.org/mongo-driver/mongo" ) var Client *mongo.Client
package main import ( "fmt" "time" ) //单向通道多用于函数参数里 var ch1 chan<- int //表示通道ch1只可以用来写的,只可以往ch1放值 var ch2 <-chan int //表示通道ch2只可以用来读的,只可以往ch2取值 func worker(id int,jobs<-chan int,result chan<- int){ for j:=range jobs{ //遍历用于读取数据的通道 fmt.Printf("WORKER:%d start job:%d\n",id,j) time.Sleep(time.Second) fmt.Printf("WORKER:%d start job:%d\n",id,j) result<-j*2 } } //work_pool func main(){ jobs:=make(chan int,100) result:=make(chan int,100) //开启3个goroutine for w:=1;w<3;w++{ go worker(w,jobs,result) } //5个任务 for j:=1;j<=5;j++{ jobs<-j //等到结果,写通道,将结果写入通道jobs } close(jobs) for a:=1;a<=5;a++{ <-result } }
/* An interface is an abstract type. It is a set of method signatures. A value of interface type can hold any value that implements thos methods A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword. Under the hood, interface values can be thought of as a tuple of a value and a concrete type: (value, type) An interface value holds a value of a specific underlying concrete type. Calling a method on an interface value executes the method of the same name on its underlying type. If the concrete value inside the interface itself is nil, the method will be called with a nil receiver. In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.) Note that an interface value that holds a nil concrete value is itself non-nil. A nil interface value holds neither value nor concrete type. Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call. */ package main import ( "fmt" "math" ) type impl interface { abs() float64 } type Vertex1 struct { x float64 y float64 } func (v *Vertex1) abs() float64 { return math.Abs(v.x) + math.Abs(v.y) } func main() { var im impl v := &Vertex1{x: 1.1, y: 2.1} describe(im) // im.abs()// invalid memory address or pointer dereference im = v describe(im) // A tuple of Type and value // Value can be nil v1 := &Vertex1{} im = v1 describe(im) fmt.Println(im.abs()) // An empty interface // It is an interface with no method signatures // it takes any values that implements no methods // It is used to hold any type of values best example is fmt.println var empty interface{} empty = 42 describe(empty) empty = "Hi" describe(empty) //Type assertion is used to provide access to interface value's //underlying concrete value variable, ok := empty.(int) fmt.Println("Value: ", variable, "IsPresent", ok) // type switch typeCheck(40) typeCheck(50.55) } func describe(im interface{}) { fmt.Printf("\n%T & %v\n", im, im) } func typeCheck(im interface{}) { switch v := im.(type) { // type keyword case int: fmt.Println("Integer: ", v) case float64: fmt.Println("Float: ", v) } }
package main import "fmt" func main() { var n = 100 //打印类型 fmt.Printf("%T\n", n) //打印值 fmt.Printf("%v\n", n) //打印转换为二进制 fmt.Printf("%b\n", n) //打印数字 fmt.Printf("%d\n", n) //打印转换为八进制 fmt.Printf("%o\n", n) //打印转换为十六进制 fmt.Printf("%x\n", n) var s = "helo world!" //打印字符串 fmt.Printf("%s\n", s) //打印值 fmt.Printf("%v\n", s) //打印如果是字符加双引号 fmt.Printf("字符串:%#v\n", s) fmt.Printf("数字:%#v\n", n) }
package utils import ( "testing" ) func TestIsPalindromeString(t *testing.T) { var tests = []struct { input string want bool }{ {"eatae", true}, {"tea", false}, {"tat", true}, } for _, test := range tests { got := IsPalindromeString(test.input) if got != test.want { t.Errorf("Got not same as want") } } } func TestReverseString(t *testing.T) { var tests = []struct { input string want string }{ {"eatae", "eatae"}, {"tea", "aet"}, {"etat", "tate"}, } for _, test := range tests { got := ReverseString(test.input) if got != test.want { t.Errorf("Got not same as want") } } }
// 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 error //nolint: predeclared import ( stderrs "errors" "github.com/pingcap/errors" "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/util/dbterror" tikverr "github.com/tikv/client-go/v2/error" pderr "github.com/tikv/pd/client/errs" ) // tikv error instance var ( // ErrTokenLimit is the error that token is up to the limit. ErrTokenLimit = dbterror.ClassTiKV.NewStd(errno.ErrTiKVStoreLimit) // ErrTiKVServerTimeout is the error when tikv server is timeout. ErrTiKVServerTimeout = dbterror.ClassTiKV.NewStd(errno.ErrTiKVServerTimeout) ErrTiFlashServerTimeout = dbterror.ClassTiKV.NewStd(errno.ErrTiFlashServerTimeout) // ErrGCTooEarly is the error that GC life time is shorter than transaction duration ErrGCTooEarly = dbterror.ClassTiKV.NewStd(errno.ErrGCTooEarly) // ErrTiKVStaleCommand is the error that the command is stale in tikv. ErrTiKVStaleCommand = dbterror.ClassTiKV.NewStd(errno.ErrTiKVStaleCommand) // ErrQueryInterrupted is the error when the query is interrupted. ErrQueryInterrupted = dbterror.ClassTiKV.NewStd(errno.ErrQueryInterrupted) // ErrTiKVMaxTimestampNotSynced is the error that tikv's max timestamp is not synced. ErrTiKVMaxTimestampNotSynced = dbterror.ClassTiKV.NewStd(errno.ErrTiKVMaxTimestampNotSynced) // ErrLockAcquireFailAndNoWaitSet is the error that acquire the lock failed while no wait is setted. ErrLockAcquireFailAndNoWaitSet = dbterror.ClassTiKV.NewStd(errno.ErrLockAcquireFailAndNoWaitSet) ErrResolveLockTimeout = dbterror.ClassTiKV.NewStd(errno.ErrResolveLockTimeout) // ErrLockWaitTimeout is the error that wait for the lock is timeout. ErrLockWaitTimeout = dbterror.ClassTiKV.NewStd(errno.ErrLockWaitTimeout) // ErrTiKVServerBusy is the error when tikv server is busy. ErrTiKVServerBusy = dbterror.ClassTiKV.NewStd(errno.ErrTiKVServerBusy) // ErrTiFlashServerBusy is the error that tiflash server is busy. ErrTiFlashServerBusy = dbterror.ClassTiKV.NewStd(errno.ErrTiFlashServerBusy) // ErrPDServerTimeout is the error when pd server is timeout. ErrPDServerTimeout = dbterror.ClassTiKV.NewStd(errno.ErrPDServerTimeout) // ErrRegionUnavailable is the error when region is not available. ErrRegionUnavailable = dbterror.ClassTiKV.NewStd(errno.ErrRegionUnavailable) // ErrResourceGroupNotExists is the error when resource group does not exist. ErrResourceGroupNotExists = dbterror.ClassTiKV.NewStd(errno.ErrResourceGroupNotExists) // ErrResourceGroupConfigUnavailable is the error when resource group configuration is unavailable. ErrResourceGroupConfigUnavailable = dbterror.ClassTiKV.NewStd(errno.ErrResourceGroupConfigUnavailable) // ErrResourceGroupThrottled is the error when resource group is exceeded quota limitation ErrResourceGroupThrottled = dbterror.ClassTiKV.NewStd(errno.ErrResourceGroupThrottled) // ErrUnknown is the unknow error. ErrUnknown = dbterror.ClassTiKV.NewStd(errno.ErrUnknown) ) // Registers error returned from TiKV. var ( _ = dbterror.ClassTiKV.NewStd(errno.ErrDataOutOfRange) _ = dbterror.ClassTiKV.NewStd(errno.ErrTruncatedWrongValue) _ = dbterror.ClassTiKV.NewStd(errno.ErrDivisionByZero) ) // ToTiDBErr checks and converts a tikv error to a tidb error. func ToTiDBErr(err error) error { if err == nil { return nil } if tikverr.IsErrNotFound(err) { return kv.ErrNotExist } var writeConflictInLatch *tikverr.ErrWriteConflictInLatch if stderrs.As(err, &writeConflictInLatch) { return kv.ErrWriteConflictInTiDB.FastGenByArgs(writeConflictInLatch.StartTS) } var txnTooLarge *tikverr.ErrTxnTooLarge if stderrs.As(err, &txnTooLarge) { return kv.ErrTxnTooLarge.GenWithStackByArgs(txnTooLarge.Size) } if stderrs.Is(err, tikverr.ErrCannotSetNilValue) { return kv.ErrCannotSetNilValue } var entryTooLarge *tikverr.ErrEntryTooLarge if stderrs.As(err, &entryTooLarge) { return kv.ErrEntryTooLarge.GenWithStackByArgs(entryTooLarge.Limit, entryTooLarge.Size) } if stderrs.Is(err, tikverr.ErrInvalidTxn) { return kv.ErrInvalidTxn } if stderrs.Is(err, tikverr.ErrTiKVServerTimeout) { return ErrTiKVServerTimeout } var pdServerTimeout *tikverr.ErrPDServerTimeout if stderrs.As(err, &pdServerTimeout) { return ErrPDServerTimeout.GenWithStackByArgs(pdServerTimeout.Error()) } if stderrs.Is(err, tikverr.ErrTiFlashServerTimeout) { return ErrTiFlashServerTimeout } if stderrs.Is(err, tikverr.ErrQueryInterrupted) { return ErrQueryInterrupted } if stderrs.Is(err, tikverr.ErrTiKVServerBusy) { return ErrTiKVServerBusy } if stderrs.Is(err, tikverr.ErrTiFlashServerBusy) { return ErrTiFlashServerBusy } var gcTooEarly *tikverr.ErrGCTooEarly if stderrs.As(err, &gcTooEarly) { return ErrGCTooEarly.GenWithStackByArgs(gcTooEarly.TxnStartTS, gcTooEarly.GCSafePoint) } if stderrs.Is(err, tikverr.ErrTiKVStaleCommand) { return ErrTiKVStaleCommand } if stderrs.Is(err, tikverr.ErrTiKVMaxTimestampNotSynced) { return ErrTiKVMaxTimestampNotSynced } if stderrs.Is(err, tikverr.ErrLockAcquireFailAndNoWaitSet) { return ErrLockAcquireFailAndNoWaitSet } if stderrs.Is(err, tikverr.ErrResolveLockTimeout) { return ErrResolveLockTimeout } if stderrs.Is(err, tikverr.ErrLockWaitTimeout) { return ErrLockWaitTimeout } if stderrs.Is(err, tikverr.ErrRegionUnavailable) { return ErrRegionUnavailable } var tokenLimit *tikverr.ErrTokenLimit if stderrs.As(err, &tokenLimit) { return ErrTokenLimit.GenWithStackByArgs(tokenLimit.StoreID) } if stderrs.Is(err, tikverr.ErrUnknown) { return ErrUnknown } if tikverr.IsErrorUndetermined(err) { return terror.ErrResultUndetermined } var errGetResourceGroup *pderr.ErrClientGetResourceGroup if stderrs.As(err, &errGetResourceGroup) { return ErrResourceGroupNotExists.FastGenByArgs(errGetResourceGroup.ResourceGroupName) } if stderrs.Is(err, pderr.ErrClientResourceGroupConfigUnavailable) { return ErrResourceGroupConfigUnavailable } if stderrs.Is(err, pderr.ErrClientResourceGroupThrottled) { return ErrResourceGroupThrottled } return errors.Trace(err) }
package mobiles import () type Mobile struct { } func New() *Mobile { return &Mobile{} }
package controllers import ( "io" "os" "strconv" "time" "Perekoter/models" "Perekoter/utility" "github.com/gin-gonic/gin" ) func GetAllThreads(c *gin.Context) { var threads []models.Thread db := models.DB() defer db.Close() db.Preload("Board").Find(&threads) c.JSON(200, gin.H{ "status": 0, "body": threads, }) } func GetThread(c *gin.Context) { var request utility.NumRequest c.Bind(&request) db := models.DB() defer db.Close() var thread models.Thread db.First(&thread, request.Num) c.JSON(200, gin.H{ "status": 0, "body": thread, }) } func AddThread(c *gin.Context) { title := c.PostForm("title") numbering := c.PostForm("numbering") != "" numberingSymbol := c.PostForm("numbering_symbol") roman := c.PostForm("roman") != "" currentNum, _ := strconv.Atoi(c.PostForm("current_num")) currentThread, _ := strconv.Atoi(c.PostForm("current_thread")) header := c.PostForm("header") headerLink := c.PostForm("header_link") != "" boardNum, _ := strconv.Atoi(c.PostForm("board_num")) redirect := c.PostForm("redirect") != "" db := models.DB() defer db.Close() var targetBoard models.Board db.First(&targetBoard, boardNum) imageName := strconv.FormatInt(time.Now().Unix(), 10) + ".png" img, _, errImg := c.Request.FormFile("cover") out, errFile := os.Create("./covers/" + imageName) if (errFile != nil) || (errImg != nil) { go utility.NewError("Failed to create thread - image not opened") go utility.NewHistoryPoint("ERROR: Thread \"" + title + "\" was not created - image not opened") c.JSON(200, gin.H{ "status": 2, }) return } defer out.Close() _, errWriting := io.Copy(out, img) if errWriting != nil { go utility.NewError("Failed to creating thread - image not created") go utility.NewHistoryPoint("ERROR: Thread \"" + title + "\" was not created - image not created") c.JSON(200, gin.H{ "status": 3, }) return } db.Create(&models.Thread{ Numbering: numbering, NumberingSymbol: numberingSymbol, Roman: roman, CurrentNum: currentNum, CurrentThread: currentThread, Title: title, HeaderLink: headerLink, Header: header, Image: imageName, BoardID: targetBoard.ID, Active: true, }) go utility.NewHistoryPoint("Thread \"" + title + "\" was created") if redirect { c.Redirect(301, "/threads") } else { c.JSON(200, gin.H{ "status": 0, }) } } func EditThread(c *gin.Context) { var request utility.ThreadRequest c.Bind(&request) db := models.DB() defer db.Close() var targetBoard models.Board db.First(&targetBoard, request.BoardNum) var thread models.Thread db.First(&thread, request.ID) thread.Numbering = request.Numbering thread.NumberingSymbol = request.NumberingSymbol thread.Roman = request.Roman thread.CurrentNum = request.CurrentNum thread.CurrentThread = request.CurrentThread thread.Title = request.Title thread.HeaderLink = request.HeaderLink thread.Header = request.Header thread.Board = targetBoard thread.BoardID = targetBoard.ID db.Save(&thread) go utility.NewHistoryPoint("Thread \"" + request.Title + "\" was edited") c.JSON(200, gin.H{ "status": 0, }) } func UploadImage(c *gin.Context) { num := c.PostForm("num") redirect := c.PostForm("redirect") != "" db := models.DB() defer db.Close() var thread models.Thread db.First(&thread, num) imageName := strconv.FormatInt(time.Now().Unix(), 10) + ".png" img, _, errImg := c.Request.FormFile("cover") out, errFile := os.Create("./covers/" + imageName) if (errFile != nil) || (errImg != nil) { go utility.NewError("Failed to upload new thread image - image not opened") go utility.NewHistoryPoint("ERROR: Thread image \"" + thread.Title + "\" was not changed - image not opened") c.JSON(200, gin.H{ "status": 2, }) return } defer out.Close() _, errWriting := io.Copy(out, img) if errWriting != nil { go utility.NewError("Failed to upload new thread image - image not created") go utility.NewHistoryPoint("ERROR: Thread image \"" + thread.Title + "\" was not changed - image not created") c.JSON(200, gin.H{ "status": 3, }) return } thread.Image = imageName db.Save(&thread) go utility.NewHistoryPoint("Image of thread \"" + thread.Title + "\" was changed") if redirect { c.Redirect(301, "/threads") } else { c.JSON(200, gin.H{ "status": 0, }) } } func SwitchThreadActivity(c *gin.Context) { var request utility.NumRequest c.Bind(&request) db := models.DB() defer db.Close() var thread models.Thread db.First(&thread, request.Num) thread.Active = !thread.Active db.Save(&thread) var status string if thread.Active { status = "has been activated" } else { status = "has been deactivated" } go utility.NewHistoryPoint("Thread \"" + thread.Title + "\" " + status) c.JSON(200, gin.H{ "status": 0, }) } func DeleteThread(c *gin.Context) { var request utility.NumRequest c.Bind(&request) db := models.DB() defer db.Close() var thread models.Thread db.First(&thread, request.Num) errFile := os.Remove("./covers/" + thread.Image) if errFile != nil { go utility.NewError("Failed to delete thread image") go utility.NewHistoryPoint("ERROR: Thread \"" + thread.Title + "\" was not deleted") c.JSON(200, gin.H{ "status": 1, }) return } go utility.NewHistoryPoint("Thread \"" + thread.Title + "\" was deleted") db.Delete(&thread) c.JSON(200, gin.H{ "status": 0, }) }
package navigator_test import ( "testing" "github.com/olliephillips/gofencer/navigator" ) func TestSetOrigin(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) // Point inside err := n.SetOrigin(33.52401, -111.94064) if err != nil { t.Error("Point inside geofence rejected for origin") } // Point Outside err = n.SetOrigin(33.53131, -111.91135) if err == nil { t.Error("Point outside geofence accepted for origin") } } func TestToOrigin(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) // Test origin not set _, err := n.ToOrigin(33.53131, -111.91135) if err == nil { t.Error("Expected an error as origin is not set, did not get error") } // Test distance between two points, and actual result _ = n.SetOrigin(33.52401, -111.94064) res, err := n.ToOrigin(33.53131, -111.91135) if err != nil { t.Error("Origin has been correctly set, did not expect error") } // Test result distance, for the above coordinates it should be 2.833km expectedDistance := float64(2.833) if res.Distance != expectedDistance { t.Error("Expected", expectedDistance, "as result of distance calculation. Got", res.Distance) } // Test result bearing, for the above coordinates it should be 253 expectedBearing := float64(253) if res.Bearing != expectedBearing { t.Error("Expected", expectedBearing, "as result of bearing calculation. Got", res.Bearing) } } func TestEnterGeofence(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) _ = n.SetOrigin(33.52401, -111.94064) // Test from point known to be outside the geofence res, err := n.EnterGeofence(33.53131, -111.91135) if err != nil { t.Error("Error returned ", err) } // Test result distance, for the above coordinates it should be 0.397km expectedDistance := float64(0.397) if res.Distance != expectedDistance { t.Error("Expected", expectedDistance, "as result of EnterGeofence distance calculation. Got", res.Distance) } // Test result bearing, for the above coordinates it should be 253 expectedBearing := float64(253) if res.Bearing != expectedBearing { t.Error("Expected", expectedBearing, "as result of EnterGeofence bearing calculation. Got", res.Bearing) } } func TestExitGeofence(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) // Test from point known to be inside the geofence res, err := n.ExitGeofence(33.52401, -111.94064) if err != nil { t.Error("Error returned ", err) } // Test result distance, for the above coordinates it should be 0.549km expectedDistance := float64(0.549) if res.Distance != expectedDistance { t.Error("Expected", expectedDistance, "as result of ExitGeofence distance calculation. Got", res.Distance) } // Test result bearing, for the above coordinates it should be 286 expectedBearing := float64(288) if res.Bearing != expectedBearing { t.Error("Expected", expectedBearing, "as result of ExitGeofence bearing calculation. Got", res.Bearing) } } func TestEnterGeofencefromInside(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) // Test from point known to be inside the geofence _, err := n.EnterGeofence(33.52401, -111.94064) if err == nil { t.Error("Expected an error. Should not be able to enter geofence, point already inside, but nil error returned") } } func TestExitGeofencefromOutside(t *testing.T) { n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) n.AddPoint(33.52416, -111.94408) n.AddPoint(33.51049, -111.96279) n.AddPoint(33.52566, -111.92331) n.AddPoint(33.50047, -111.90271) n.AddPoint(33.51872, -111.90657) n.AddPoint(33.52323, -111.90219) // Test from point known to be outside the geofence _, err := n.ExitGeofence(33.53131, -111.91135) if err == nil { t.Error("Expected an error. Should not be able to exit geofence, point already outside, but nil error returned") } } func TestEnterGeofenceNoFence(t *testing.T) { // Incomplete or no geofence n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) // Test from point known to be outside the geofence _, err := n.EnterGeofence(33.53131, -111.91135) if err == nil { t.Error("Incomplete geofence, expected an error, which was not returned.") } } func TestExitGeofenceNoFence(t *testing.T) { // Incomplete or no geofence n := new(navigator.Navigator) // Create Geofence with this data n.AddPoint(33.53625, -111.92674) n.AddPoint(33.53038, -111.95352) // Test from point known to be inside the geofence _, err := n.ExitGeofence(33.52401, -111.94064) if err == nil { t.Error("Incomplete geofence, expected an error, which was not returned.") } }
package request import "net/http" // AddHeader Add header to Request func (options) AddHeader(k, v string) Option { return func(r *Request) { if r.requestHeader == nil { r.requestHeader = http.Header{} } r.requestHeader.Add(k, v) } } // SetHeader Set header to Request func (options) SetHeader(k, v string) Option { return func(r *Request) { if r.requestHeader == nil { r.requestHeader = http.Header{} } r.requestHeader.Set(k, v) } } // ReplaceHeader can replace whole request header by f's returned value // can used to Del header func (options) ReplaceHeader(f func(oldHeader http.Header) http.Header) Option { return func(r *Request) { r.requestHeader = f(r.requestHeader) } } // GetResponseHeader get response's header, add it into given header // happen before CheckResponseBeforeUnmarshalFunc be called func (options) GetResponseHeader(header http.Header) Option { if header == nil { panic("header must not nil") } return func(r *Request) { r.responseHeaders = append(r.responseHeaders, header) } }
package main import "fmt" /* Go supports methods defined on structs */ type rect struct { width, height int } /* The area method has a receiver type of rect */ func (r *rect) area() int{ return r.width * r.height } /* Methods can be defined for either pointer or value receiver types. Here's an example of value receiver */ func (r rect) perim() int { return 2*r.width + 2*r.height } /* Go Automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on the method calls or to allow the method to mutate the receivign struct */ func main() { r:= rect{width: 10, height: 5} fmt.Println("Area: ", r.area()) fmt.Println("Perim: ", r.perim()) rp := &r fmt.Println("Area: ", rp.area()) fmt.Println("Perim: ", rp.perim()) }
package main import "leetcode/dushengchen" func main() { //dushengchen.LargestRectangleArea([]int{12,11,10,9,8,7,6,5,4,3,2,1})、 head := &dushengchen.ListNode{} cur := head for _, v := range []int{1,4,3,2,5,2} { cur.Next = &dushengchen.ListNode{Val: v} cur = cur.Next } dushengchen.Partition(head.Next, 3) }
package accesstoken import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestGetNewAccessToken(t *testing.T) { at := GetNewAccessToken(1) assert.Equal(t, false, at.IsExpired(), "new access token should not be expired") assert.Equal(t, "", at.AccessToken, "new access token should not have defined access token id") assert.Equal(t, int64(0), at.UserID, "new access token should not have defined user id") } func TestAccessTokenIsExpired(t *testing.T) { at := AccessToken{} assert.Equal(t, true, at.IsExpired(), "access token created 3 hours from now should not be expired") at.Expires = time.Now().UTC().Add(3 * time.Hour).Unix() assert.Equal(t, false, at.IsExpired(), "access token created 3 hours from now should not be expired") } func TestExpirationTimeConstant(t *testing.T) { assert.Equal(t, 24, expirationTime, "Expiration time should be 24 hours") }
package memory_cache import ( "time" ) func New() *Cache { return &Cache{cacheMap: map[string]*cacheData{}} } type Cache struct { cacheMap map[string]*cacheData } func (c *Cache) Set(key string, data interface{}, sec ...int) { var expire *time.Time if len(sec) == 1 && sec[0] > 0 { t := time.Now().Add(time.Duration(sec[0]) * time.Second) expire = &t } c.cacheMap[key] = &cacheData{ expire, data, } } func (c *Cache) Get(key string) interface{} { data := c.cacheMap[key] // key为空 if data == nil { return nil } // 没有过期时间 或 没有超时,正常返回数据 if data.expire == nil || time.Now().Before(*data.expire) { return data.Value } // 超时删除数据 delete(c.cacheMap, key) return nil } func (c *Cache) Delete(key string) { delete(c.cacheMap, key) } func (c *Cache) GetInt(key string) (i int, ok bool) { value := c.Get(key) switch i := value.(type) { case int: return i, true case int32: return int(i), true default: return 0, false } } func (c *Cache) GetInt64(key string) (i int64, ok bool) { value := c.Get(key) switch i := value.(type) { case int64: return i, true case int: return int64(i), true case int32: return int64(i), true default: return 0, false } } func (c *Cache) GetFloat(key string) (f float64, ok bool) { value := c.Get(key) switch f := value.(type) { case float64: return f, true case float32: return float64(f), true case int: return float64(f), true case int64: return float64(f), true case int32: return float64(f), true default: return 0, false } } func (c *Cache) GetFloat64(key string) (f float64, ok bool) { return c.GetFloat(key) } func (c *Cache) GetString(key string) (s string, ok bool) { value := c.Get(key) s, ok = value.(string) return s, ok } func (c *Cache) GetBool(key string) (b bool, ok bool) { value := c.Get(key) b, ok = value.(bool) return b, ok } type cacheData struct { expire *time.Time Value interface{} }
package main import ( "testing" ) func TestToCFriend(t *testing.T) { ts := []struct { f Friend } { { f: Friend{ ID: 1, Age: 10, }, }, { f: Friend{ ID: 2, Age: 20, }, }, } for _, tc := range ts { f := tc.f cf := toCFriend(f) goID, cID := f.ID, cf.id if goID != int(cID) { t.Errorf("go id=%d c id=%d", goID, cID) } goAge, cAge := f.Age, cf.age if goAge != int(cAge) { t.Errorf("go age=%d c age=%d", goAge, cAge) } } }
package autobatch import ( "bytes" "fmt" "testing" ds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore" dstest "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/test" ) func TestAutobatch(t *testing.T) { dstest.SubtestAll(t, NewAutoBatching(ds.NewMapDatastore(), 16)) } func TestFlushing(t *testing.T) { child := ds.NewMapDatastore() d := NewAutoBatching(child, 16) var keys []ds.Key for i := 0; i < 16; i++ { keys = append(keys, ds.NewKey(fmt.Sprintf("test%d", i))) } v := []byte("hello world") for _, k := range keys { err := d.Put(k, v) if err != nil { t.Fatal(err) } } _, err := child.Get(keys[0]) if err != ds.ErrNotFound { t.Fatal("shouldnt have found value") } err = d.Put(ds.NewKey("test16"), v) if err != nil { t.Fatal(err) } // should be flushed now, try to get keys from child datastore for _, k := range keys { val, err := child.Get(k) if err != nil { t.Fatal(err) } if !bytes.Equal(val, v) { t.Fatal("wrong value") } } }
package models import ( "fmt" "strings" "time" "github.com/google/uuid" "github.com/lib/pq" ) type APIKey struct { ID uuid.UUID `json:"id"` Created time.Time `json:"created"` LastUsed pq.NullTime `json:"last_used"` PermissionLevel PermissionLevel `json:"permission_level"` Description string `json:"description"` GitHubUser string `json:"github_user"` Token uuid.UUID `json:"token"` } func (apik APIKey) Columns() string { return strings.Join([]string{"id", "created", "last_used", "permission_level", "description", "github_user", "token"}, ",") } func (apik APIKey) InsertColumns() string { return strings.Join([]string{"id", "created", "last_used", "permission_level", "description", "github_user", "token"}, ",") } func (apik *APIKey) ScanValues() []interface{} { return []interface{}{&apik.ID, &apik.Created, &apik.LastUsed, &apik.PermissionLevel, &apik.Description, &apik.GitHubUser, &apik.Token} } func (apik *APIKey) InsertValues() []interface{} { return []interface{}{&apik.ID, &apik.Created, &apik.LastUsed, &apik.PermissionLevel, &apik.Description, &apik.GitHubUser, &apik.Token} } func (apik APIKey) InsertParams() string { params := []string{} for i := range strings.Split(apik.InsertColumns(), ",") { params = append(params, fmt.Sprintf("$%v", i+1)) } return strings.Join(params, ", ") } //go:generate stringer -type=PermissionLevel type PermissionLevel int const ( UnknownPermission PermissionLevel = iota ReadOnlyPermission WritePermission AdminPermission )
//go:build test // +build test // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "encoding/json" "fmt" "log" "os" "path/filepath" "strconv" "strings" "github.com/Azure/go-autorest/autorest/to" "github.com/kelseyhightower/envconfig" "github.com/pkg/errors" "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/aks-engine/pkg/api/common" "github.com/Azure/aks-engine/pkg/api/vlabs" "github.com/Azure/aks-engine/pkg/helpers" "github.com/Azure/aks-engine/pkg/i18n" "github.com/Azure/aks-engine/test/e2e/config" ) // Config represents the configuration values of a template stored as env vars type Config struct { ClientID string `envconfig:"CLIENT_ID" required:"true"` ClientSecret string `envconfig:"CLIENT_SECRET" required:"true"` ClientObjectID string `envconfig:"CLIENT_OBJECTID" default:""` LogAnalyticsWorkspaceKey string `envconfig:"LOG_ANALYTICS_WORKSPACE_KEY" default:""` MasterDNSPrefix string `envconfig:"DNS_PREFIX" default:""` AgentDNSPrefix string `envconfig:"DNS_PREFIX" default:""` MSIUserAssignedID string `envconfig:"MSI_USER_ASSIGNED_ID" default:""` UseManagedIdentity bool `envconfig:"USE_MANAGED_IDENTITY" default:"true"` PublicSSHKey string `envconfig:"PUBLIC_SSH_KEY" default:""` WindowsAdminPasssword string `envconfig:"WINDOWS_ADMIN_PASSWORD" default:""` WindowsNodeImageGallery string `envconfig:"WINDOWS_NODE_IMAGE_GALLERY" default:""` WindowsNodeImageName string `envconfig:"WINDOWS_NODE_IMAGE_NAME" default:""` WindowsNodeImageResourceGroup string `envconfig:"WINDOWS_NODE_IMAGE_RESOURCE_GROUP" default:""` WindowsNodeImageSubscriptionID string `envconfig:"WINDOWS_NODE_IMAGE_SUBSCRIPTION_ID" default:""` WindowsNodeImageVersion string `envconfig:"WINDOWS_NODE_IMAGE_VERSION" default:""` WindowsNodeVhdURL string `envconfig:"WINDOWS_NODE_VHD_URL" default:""` LinuxNodeImageGallery string `envconfig:"LINUX_NODE_IMAGE_GALLERY" default:""` LinuxNodeImageName string `envconfig:"LINUX_NODE_IMAGE_NAME" default:""` LinuxNodeImageResourceGroup string `envconfig:"LINUX_NODE_IMAGE_RESOURCE_GROUP" default:""` LinuxNodeImageSubscriptionID string `envconfig:"LINUX_NODE_IMAGE_SUBSCRIPTION_ID" default:""` LinuxNodeImageVersion string `envconfig:"LINUX_NODE_IMAGE_VERSION" default:""` OSDiskSizeGB string `envconfig:"OS_DISK_SIZE_GB" default:""` ContainerRuntime string `envconfig:"CONTAINER_RUNTIME" default:""` OrchestratorRelease string `envconfig:"ORCHESTRATOR_RELEASE" default:""` OrchestratorVersion string `envconfig:"ORCHESTRATOR_VERSION" default:""` OutputDirectory string `envconfig:"OUTPUT_DIR" default:"_output"` CreateVNET bool `envconfig:"CREATE_VNET" default:"false"` EnableKMSEncryption bool `envconfig:"ENABLE_KMS_ENCRYPTION" default:"false"` Distro string `envconfig:"DISTRO" default:""` SubscriptionID string `envconfig:"SUBSCRIPTION_ID" required:"true"` InfraResourceGroup string `envconfig:"INFRA_RESOURCE_GROUP" default:""` Location string `envconfig:"LOCATION" default:""` TenantID string `envconfig:"TENANT_ID" required:"true"` ImageName string `envconfig:"IMAGE_NAME" default:""` ImageResourceGroup string `envconfig:"IMAGE_RESOURCE_GROUP" default:""` DebugCrashingPods bool `envconfig:"DEBUG_CRASHING_PODS" default:"false"` CustomHyperKubeImage string `envconfig:"CUSTOM_HYPERKUBE_IMAGE" default:""` CustomKubeProxyImage string `envconfig:"CUSTOM_KUBE_PROXY_IMAGE" default:""` CustomKubeAPIServerImage string `envconfig:"CUSTOM_KUBE_APISERVER_IMAGE" default:""` CustomKubeSchedulerImage string `envconfig:"CUSTOM_KUBE_SCHEDULER_IMAGE" default:""` CustomKubeControllerManagerImage string `envconfig:"CUSTOM_KUBE_CONTROLLER_MANAGER_IMAGE" default:""` CustomKubeBinaryURL string `envconfig:"CUSTOM_KUBE_BINARY_URL" default:""` CustomWindowsPackageURL string `envconfig:"CUSTOM_WINDOWS_PACKAGE_URL" default:""` EnableTelemetry bool `envconfig:"ENABLE_TELEMETRY" default:"true"` KubernetesImageBase string `envconfig:"KUBERNETES_IMAGE_BASE" default:""` KubernetesImageBaseType string `envconfig:"KUBERNETES_IMAGE_BASE_TYPE" default:""` LinuxContainerdURL string `envconfig:"LINUX_CONTAINERD_URL"` WindowsContainerdURL string `envconfig:"WINDOWS_CONTAINERD_URL"` LinuxMobyURL string `envconfig:"LINUX_MOBY_URL"` LinuxRuncURL string `envconfig:"LINUX_RUNC_URL"` WindowsProvisioningScriptsURL string `envconfig:"WINDOWS_PROVISIONING_SCRIPTS_URL" default:""` ArcClientID string `envconfig:"ARC_CLIENT_ID" default:""` ArcClientSecret string `envconfig:"ARC_CLIENT_SECRET" default:""` ArcSubscriptionID string `envconfig:"ARC_SUBSCRIPTION_ID" default:""` ArcLocation string `envconfig:"ARC_LOCATION" default:""` ArcTenantID string `envconfig:"ARC_TENANT_ID" default:""` RunVMSSNodePrototype bool `envconfig:"RUN_VMSS_NODE_PROTOTYPE" default:"false"` Eth0MTU int `envconfig:"ETH0_MTU"` ClusterDefinitionPath string // The original template we want to use to build the cluster from. ClusterDefinitionTemplate string // This is the template after we splice in the environment variables GeneratedDefinitionPath string // Holds the contents of running aks-engine generate OutputPath string // This is the root output path DefinitionName string // Unique cluster name GeneratedTemplatePath string // azuredeploy.json path GeneratedParametersPath string // azuredeploy.parameters.json path } // Engine holds necessary information to interact with aks-engine cli type Engine struct { Config *Config ClusterDefinition *api.VlabsARMContainerService // Holds the parsed ClusterDefinition ExpandedDefinition *api.ContainerService // Holds the expanded ClusterDefinition } // ParseConfig will return a new engine config struct taking values from env vars func ParseConfig(cwd, clusterDefinition, name string) (*Config, error) { c := new(Config) if err := envconfig.Process("config", c); err != nil { return nil, err } clusterDefinitionTemplate := fmt.Sprintf("%s/%s.json", c.OutputDirectory, name) generatedDefinitionPath := fmt.Sprintf("%s/%s", c.OutputDirectory, name) c.DefinitionName = name c.ClusterDefinitionPath = filepath.Join(cwd, clusterDefinition) c.ClusterDefinitionTemplate = filepath.Join(cwd, clusterDefinitionTemplate) c.OutputPath = filepath.Join(cwd, c.OutputDirectory) c.GeneratedDefinitionPath = filepath.Join(cwd, generatedDefinitionPath) c.GeneratedTemplatePath = filepath.Join(cwd, generatedDefinitionPath, "azuredeploy.json") c.GeneratedParametersPath = filepath.Join(cwd, generatedDefinitionPath, "azuredeploy.parameters.json") return c, nil } // Build takes a template path and will inject values based on provided environment variables // it will then serialize the structs back into json and save it to outputPath func Build(cfg *config.Config, masterSubnetID string, agentSubnetIDs []string, isVMSS bool) (*Engine, error) { config, err := ParseConfig(cfg.CurrentWorkingDir, cfg.ClusterDefinition, cfg.Name) if err != nil { log.Printf("Error while trying to build Engine Configuration:%s\n", err) } cs, err := ParseInput(config.ClusterDefinitionPath) if err != nil { return nil, err } if cs.Location == "" { cs.Location = config.Location } prop := cs.ContainerService.Properties var hasWindows bool if prop.HasWindows() { hasWindows = true } var isAzureStackCloud bool if prop.IsAzureStackCloud() { isAzureStackCloud = true } if prop.OrchestratorProfile == nil { prop.OrchestratorProfile = &vlabs.OrchestratorProfile{ KubernetesConfig: &vlabs.KubernetesConfig{}, } } else if prop.OrchestratorProfile.KubernetesConfig == nil { prop.OrchestratorProfile.KubernetesConfig = &vlabs.KubernetesConfig{} } if config.MSIUserAssignedID != "" { prop.OrchestratorProfile.KubernetesConfig.UseManagedIdentity = to.BoolPtr(true) prop.OrchestratorProfile.KubernetesConfig.UserAssignedID = config.MSIUserAssignedID } if prop.OrchestratorProfile.KubernetesConfig.UseManagedIdentity == nil && !prop.IsAzureStackCloud() { prop.OrchestratorProfile.KubernetesConfig.UseManagedIdentity = to.BoolPtr(config.UseManagedIdentity) } if config.ClientID != "" && config.ClientSecret != "" && !(prop.OrchestratorProfile.KubernetesConfig != nil && to.Bool(prop.OrchestratorProfile.KubernetesConfig.UseManagedIdentity)) { if !prop.IsAzureStackCloud() { prop.ServicePrincipalProfile = &vlabs.ServicePrincipalProfile{ ClientID: config.ClientID, Secret: config.ClientSecret, } } } if config.MasterDNSPrefix != "" { prop.MasterProfile.DNSPrefix = config.MasterDNSPrefix } if prop.LinuxProfile != nil { if config.PublicSSHKey != "" { prop.LinuxProfile.SSH.PublicKeys[0].KeyData = config.PublicSSHKey if prop.OrchestratorProfile.KubernetesConfig != nil && prop.OrchestratorProfile.KubernetesConfig.PrivateCluster != nil && prop.OrchestratorProfile.KubernetesConfig.PrivateCluster.JumpboxProfile != nil { prop.OrchestratorProfile.KubernetesConfig.PrivateCluster.JumpboxProfile.PublicKey = config.PublicSSHKey } } if config.RunVMSSNodePrototype { // In order to better determine the time it takes for nodes to come online let's eliminate any VM reboot considerations prop.LinuxProfile.RunUnattendedUpgradesOnBootstrap = to.BoolPtr((false)) } } if config.KubernetesImageBase != "" { prop.OrchestratorProfile.KubernetesConfig.KubernetesImageBase = config.KubernetesImageBase } if config.KubernetesImageBaseType != "" { prop.OrchestratorProfile.KubernetesConfig.KubernetesImageBaseType = config.KubernetesImageBaseType } if config.WindowsAdminPasssword != "" { prop.WindowsProfile.AdminPassword = config.WindowsAdminPasssword } if config.WindowsNodeVhdURL != "" { prop.WindowsProfile.WindowsImageSourceURL = config.WindowsNodeVhdURL log.Printf("Windows nodes will use image at %s for test pass", config.WindowsNodeVhdURL) } else if config.WindowsNodeImageName != "" && config.WindowsNodeImageResourceGroup != "" { prop.WindowsProfile.ImageRef = &vlabs.ImageReference{ Name: config.WindowsNodeImageName, ResourceGroup: config.WindowsNodeImageResourceGroup, } if config.WindowsNodeImageGallery != "" && config.WindowsNodeImageSubscriptionID != "" && config.WindowsNodeImageVersion != "" { prop.WindowsProfile.ImageRef.Gallery = config.WindowsNodeImageGallery prop.WindowsProfile.ImageRef.SubscriptionID = config.WindowsNodeImageSubscriptionID prop.WindowsProfile.ImageRef.Version = config.WindowsNodeImageVersion } log.Printf("Windows nodes will use image reference name:%s, rg:%s, sub:%s, gallery:%s, version:%s for test pass", config.WindowsNodeImageName, config.WindowsNodeImageResourceGroup, config.WindowsNodeImageSubscriptionID, config.WindowsNodeImageGallery, config.WindowsNodeImageVersion) } if config.WindowsProvisioningScriptsURL != "" { prop.WindowsProfile.ProvisioningScriptsPackageURL = config.WindowsProvisioningScriptsURL log.Printf("Windows nodes will use provisioning scripts from: %s", config.WindowsProvisioningScriptsURL) } if config.LinuxNodeImageName != "" && config.LinuxNodeImageResourceGroup != "" { prop.MasterProfile.ImageRef = &vlabs.ImageReference{ Name: config.LinuxNodeImageName, ResourceGroup: config.LinuxNodeImageResourceGroup, } prop.MasterProfile.ImageRef.Gallery = config.LinuxNodeImageGallery prop.MasterProfile.ImageRef.SubscriptionID = config.LinuxNodeImageSubscriptionID prop.MasterProfile.ImageRef.Version = config.LinuxNodeImageVersion if len(prop.AgentPoolProfiles) == 1 { prop.AgentPoolProfiles[0].ImageRef = &vlabs.ImageReference{ Name: config.LinuxNodeImageName, ResourceGroup: config.LinuxNodeImageResourceGroup, } if config.LinuxNodeImageGallery != "" && config.LinuxNodeImageSubscriptionID != "" && config.LinuxNodeImageVersion != "" { prop.AgentPoolProfiles[0].ImageRef.Gallery = config.LinuxNodeImageGallery prop.AgentPoolProfiles[0].ImageRef.SubscriptionID = config.LinuxNodeImageSubscriptionID prop.AgentPoolProfiles[0].ImageRef.Version = config.LinuxNodeImageVersion } } } if config.OSDiskSizeGB != "" { if osDiskSizeGB, err := strconv.Atoi(config.OSDiskSizeGB); err == nil { prop.MasterProfile.OSDiskSizeGB = osDiskSizeGB for _, pool := range prop.AgentPoolProfiles { pool.OSDiskSizeGB = osDiskSizeGB } } } if config.ContainerRuntime != "" { prop.OrchestratorProfile.KubernetesConfig.ContainerRuntime = config.ContainerRuntime } // If the parsed api model input has no expressed version opinion, we check if ENV does have an opinion if prop.OrchestratorProfile.OrchestratorRelease == "" && prop.OrchestratorProfile.OrchestratorVersion == "" { // First, prefer the release string if ENV declares it if config.OrchestratorRelease != "" { prop.OrchestratorProfile.OrchestratorRelease = config.OrchestratorRelease // Or, choose the version string if ENV declares it } else if config.OrchestratorVersion != "" { prop.OrchestratorProfile.OrchestratorVersion = config.OrchestratorVersion // If ENV similarly has no version opinion, we will rely upon the aks-engine default } else { prop.OrchestratorProfile.OrchestratorVersion = common.GetDefaultKubernetesVersion(hasWindows, isAzureStackCloud) } } if config.CreateVNET { if isVMSS { prop.MasterProfile.VnetSubnetID = masterSubnetID prop.MasterProfile.AgentVnetSubnetID = agentSubnetIDs[0] for _, p := range prop.AgentPoolProfiles { p.VnetSubnetID = agentSubnetIDs[0] } } else { prop.MasterProfile.VnetSubnetID = masterSubnetID for i, p := range prop.AgentPoolProfiles { p.VnetSubnetID = agentSubnetIDs[i] } } } if config.ClientObjectID != "" { if prop.ServicePrincipalProfile == nil { prop.ServicePrincipalProfile = &vlabs.ServicePrincipalProfile{} } if prop.ServicePrincipalProfile.ObjectID == "" { prop.ServicePrincipalProfile.ObjectID = config.ClientObjectID } } if config.EnableKMSEncryption && prop.OrchestratorProfile.KubernetesConfig.EnableEncryptionWithExternalKms == nil { prop.OrchestratorProfile.KubernetesConfig.EnableEncryptionWithExternalKms = &config.EnableKMSEncryption } var version string if prop.OrchestratorProfile.OrchestratorRelease != "" { version = prop.OrchestratorProfile.OrchestratorRelease + ".0" } else if prop.OrchestratorProfile.OrchestratorVersion != "" { version = prop.OrchestratorProfile.OrchestratorVersion } if common.IsKubernetesVersionGe(version, "1.12.0") { if prop.OrchestratorProfile.KubernetesConfig == nil { prop.OrchestratorProfile.KubernetesConfig = &vlabs.KubernetesConfig{} } if prop.OrchestratorProfile.KubernetesConfig.ControllerManagerConfig == nil { prop.OrchestratorProfile.KubernetesConfig.ControllerManagerConfig = map[string]string{} } prop.OrchestratorProfile.KubernetesConfig.ControllerManagerConfig["--horizontal-pod-autoscaler-downscale-stabilization"] = "30s" prop.OrchestratorProfile.KubernetesConfig.ControllerManagerConfig["--horizontal-pod-autoscaler-cpu-initialization-period"] = "30s" } if config.LogAnalyticsWorkspaceKey != "" && len(prop.OrchestratorProfile.KubernetesConfig.Addons) > 0 { for _, addOn := range prop.OrchestratorProfile.KubernetesConfig.Addons { if addOn.Name == "container-monitoring" { if addOn.Config == nil { addOn.Config = make(map[string]string) } addOn.Config["workspaceKey"] = config.LogAnalyticsWorkspaceKey break } } } if len(prop.OrchestratorProfile.KubernetesConfig.Addons) > 0 { for _, addon := range prop.OrchestratorProfile.KubernetesConfig.Addons { if addon.Name == common.AzureArcOnboardingAddonName && to.Bool(addon.Enabled) { if addon.Config == nil { addon.Config = make(map[string]string) } if addon.Config["tenantID"] == "" { if config.ArcTenantID != "" { addon.Config["tenantID"] = config.ArcTenantID } else { addon.Config["tenantID"] = config.TenantID } } if addon.Config["subscriptionID"] == "" { if config.ArcSubscriptionID != "" { addon.Config["subscriptionID"] = config.ArcSubscriptionID } else { addon.Config["subscriptionID"] = config.SubscriptionID } } if addon.Config["clientID"] == "" { if config.ArcClientID != "" { addon.Config["clientID"] = config.ArcClientID } else { addon.Config["clientID"] = config.ClientID } } if addon.Config["clientSecret"] == "" { if config.ArcClientSecret != "" { addon.Config["clientSecret"] = config.ArcClientSecret } else { addon.Config["clientSecret"] = config.ClientSecret } } if addon.Config["location"] == "" { if config.ArcLocation != "" { addon.Config["location"] = config.ArcLocation } else { addon.Config["location"] = "eastus" } } addon.Config["clusterName"] = cfg.Name addon.Config["resourceGroup"] = fmt.Sprintf("%s-arc", cfg.Name) // set to config.Name once Arc is supported in all regions break } } } if config.CustomHyperKubeImage != "" { prop.OrchestratorProfile.KubernetesConfig.CustomHyperkubeImage = config.CustomHyperKubeImage } if config.CustomKubeProxyImage != "" { prop.OrchestratorProfile.KubernetesConfig.CustomKubeProxyImage = config.CustomKubeProxyImage } if config.CustomKubeAPIServerImage != "" { prop.OrchestratorProfile.KubernetesConfig.CustomKubeAPIServerImage = config.CustomKubeAPIServerImage } if config.CustomKubeSchedulerImage != "" { prop.OrchestratorProfile.KubernetesConfig.CustomKubeSchedulerImage = config.CustomKubeSchedulerImage } if config.CustomKubeControllerManagerImage != "" { prop.OrchestratorProfile.KubernetesConfig.CustomKubeControllerManagerImage = config.CustomKubeControllerManagerImage } if config.CustomKubeBinaryURL != "" { prop.OrchestratorProfile.KubernetesConfig.CustomKubeBinaryURL = config.CustomKubeBinaryURL } if config.CustomWindowsPackageURL != "" { prop.OrchestratorProfile.KubernetesConfig.CustomWindowsPackageURL = config.CustomWindowsPackageURL } if config.EnableTelemetry == true { if prop.FeatureFlags == nil { prop.FeatureFlags = new(vlabs.FeatureFlags) } prop.FeatureFlags.EnableTelemetry = true } for _, pool := range prop.AgentPoolProfiles { if pool.DiskEncryptionSetID != "" { str := strings.Replace(pool.DiskEncryptionSetID, "SUB_ID", config.SubscriptionID, 1) str = strings.Replace(str, "RESOURCE_GROUP", config.InfraResourceGroup, 1) pool.DiskEncryptionSetID = str } if pool.ProximityPlacementGroupID != "" { str := strings.Replace(pool.ProximityPlacementGroupID, "SUB_ID", config.SubscriptionID, 1) str = strings.Replace(str, "RESOURCE_GROUP", config.InfraResourceGroup, 1) pool.ProximityPlacementGroupID = str } } if config.Distro != "" { prop.MasterProfile.Distro = vlabs.Distro(config.Distro) for _, pool := range prop.AgentPoolProfiles { if !pool.IsWindows() && pool.Distro == "" { pool.Distro = vlabs.Distro(config.Distro) } } } if config.LinuxContainerdURL != "" { prop.OrchestratorProfile.KubernetesConfig.LinuxContainerdURL = config.LinuxContainerdURL } if config.WindowsContainerdURL != "" { prop.OrchestratorProfile.KubernetesConfig.WindowsContainerdURL = config.WindowsContainerdURL } if config.LinuxMobyURL != "" { prop.OrchestratorProfile.KubernetesConfig.LinuxMobyURL = config.LinuxMobyURL } if config.LinuxRuncURL != "" { prop.OrchestratorProfile.KubernetesConfig.LinuxRuncURL = config.LinuxRuncURL } if config.Eth0MTU != 0 { if prop.LinuxProfile == nil { prop.LinuxProfile = &vlabs.LinuxProfile{} } prop.LinuxProfile.Eth0MTU = config.Eth0MTU } return &Engine{ Config: config, ClusterDefinition: cs, }, nil } // NodeCount returns the number of nodes that should be provisioned for a given cluster definition func (e *Engine) NodeCount() int { expectedCount := e.ExpandedDefinition.Properties.MasterProfile.Count for _, pool := range e.ExpandedDefinition.Properties.AgentPoolProfiles { expectedCount += pool.Count } return expectedCount } // AnyAgentIsLinux will return true if there is at least 1 linux agent pool func (e *Engine) AnyAgentIsLinux() bool { for _, ap := range e.ExpandedDefinition.Properties.AgentPoolProfiles { if ap.OSType == "" || ap.OSType == "Linux" { return true } } return false } // HasWindowsAgents will return true is there is at least 1 windows agent pool func (e *Engine) HasWindowsAgents() bool { return e.ExpandedDefinition.Properties.HasWindows() } // WindowsTestImages holds the Windows container image names used in this test pass type WindowsTestImages struct { IIS string ServerCore string } // GetWindowsTestImages will return the right list of container images for the Windows version used func (e *Engine) GetWindowsTestImages() (*WindowsTestImages, error) { if !e.HasWindowsAgents() { return nil, errors.New("Can't guess a Windows version without Windows nodes in the cluster") } windowsSku := e.ExpandedDefinition.Properties.WindowsProfile.GetWindowsSku() // tip: curl -L https://mcr.microsoft.com/v2/windows/servercore/tags/list // curl -L https://mcr.microsoft.com/v2/windows/servercore/iis/tags/list switch { case strings.Contains(windowsSku, "2004"): return &WindowsTestImages{IIS: "mcr.microsoft.com/windows/servercore/iis:windowsservercore-2004", ServerCore: "mcr.microsoft.com/windows/servercore:2004"}, nil case strings.Contains(windowsSku, "1909"): return &WindowsTestImages{IIS: "mcr.microsoft.com/windows/servercore/iis:windowsservercore-1909", ServerCore: "mcr.microsoft.com/windows/servercore:1909"}, nil case strings.Contains(windowsSku, "1903"): return &WindowsTestImages{IIS: "mcr.microsoft.com/windows/servercore/iis:windowsservercore-1903", ServerCore: "mcr.microsoft.com/windows/servercore:1903"}, nil case strings.Contains(windowsSku, "1809"), strings.Contains(windowsSku, "2019"): return &WindowsTestImages{IIS: "mcr.microsoft.com/windows/servercore/iis:20191112-windowsservercore-ltsc2019", ServerCore: "mcr.microsoft.com/windows/servercore:ltsc2019"}, nil case strings.Contains(windowsSku, "1803"): return nil, errors.New("Windows Server version 1803 is out of support") case strings.Contains(windowsSku, "1709"): return nil, errors.New("Windows Server version 1709 is out of support") } return nil, errors.New("Unknown Windows version. GetWindowsSku() = " + windowsSku) } // HasAddon will return true if an addon is enabled func (e *Engine) HasAddon(name string) (bool, api.KubernetesAddon) { for _, addon := range e.ExpandedDefinition.Properties.OrchestratorProfile.KubernetesConfig.Addons { if addon.Name == name { return to.Bool(addon.Enabled), addon } } return false, api.KubernetesAddon{} } // HasNetworkPolicy will return true if the specified network policy is enabled func (e *Engine) HasNetworkPolicy(name string) bool { return strings.Contains(e.ExpandedDefinition.Properties.OrchestratorProfile.KubernetesConfig.NetworkPolicy, name) } // HasNetworkPolicy will return true if the specified network policy is enabled func (e *Engine) HasNetworkPlugin(name string) bool { return strings.Contains(e.ExpandedDefinition.Properties.OrchestratorProfile.KubernetesConfig.NetworkPlugin, name) } // Write will write the cluster definition to disk func (e *Engine) Write() error { json, err := helpers.JSONMarshal(e.ClusterDefinition, false) if err != nil { log.Printf("Error while trying to serialize Container Service object to json:%s\n%+v\n", err, e.ClusterDefinition) return err } err = os.WriteFile(e.Config.ClusterDefinitionTemplate, json, 0777) if err != nil { log.Printf("Error while trying to write container service definition to file (%s):%s\n%s\n", e.Config.ClusterDefinitionTemplate, err, string(json)) } return nil } // ParseInput takes a template path and will parse that into a api.VlabsARMContainerService func ParseInput(path string) (*api.VlabsARMContainerService, error) { contents, err := os.ReadFile(path) if err != nil { log.Printf("Error while trying to read cluster definition at (%s):%s\n", path, err) return nil, err } cs := api.VlabsARMContainerService{} if err = json.Unmarshal(contents, &cs); err != nil { log.Printf("Error while trying to unmarshal container service json:%s\n%s\n", err, string(contents)) return nil, err } return &cs, nil } // ParseOutput takes the generated api model and will parse that into a api.ContainerService func ParseOutput(path string, validate, isUpdate bool) (*api.ContainerService, error) { locale, err := i18n.LoadTranslations() if err != nil { return nil, errors.Errorf(fmt.Sprintf("error loading translation files: %s", err.Error())) } apiloader := &api.Apiloader{ Translator: &i18n.Translator{ Locale: locale, }, } containerService, _, err := apiloader.LoadContainerServiceFromFile(path, validate, isUpdate, nil) if err != nil { return nil, err } return containerService, nil }
package main import ( "fmt" "github.com/gorilla/mux" "golang-http-server/config" "golang-http-server/controller" "golang-http-server/models" "net/http" "os" ) func main() { db := config.Init() db.Debug().AutoMigrate(&models.Employee{}) router := mux.NewRouter() router.HandleFunc("/api/employee/create", controller.CreateEmployee).Methods("POST") router.HandleFunc("/api/employee/getAll", controller.GetAllEmployees).Methods("GET") port := os.Getenv("PORT") if port == "" { port = "8000" } fmt.Println(port) error := http.ListenAndServe(":"+port, router) if error != nil { fmt.Print(error) } }
package main import ( "fmt" "github.com/google/uuid" ) func main() { x := uuid.New().URN() fmt.Println("UUID ", x) }
package redisRepository import ( "time" "github.com/go-redis/redis" ) type RedisRepository struct { db *redis.Client } func tryConnect(addr, password string) (*RedisRepository, error) { client := redis.NewClient(&redis.Options{ Addr: addr, Password: password, DialTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, PoolSize: 10, PoolTimeout: 30 * time.Second, }) _, err := client.Ping().Result() return &RedisRepository{ db: client, }, err } func (r *RedisRepository) Close() { r.db.Close() } func (r *RedisRepository) Set(key string, value interface{}, duration time.Duration) error { return r.db.Set(key, value, duration).Err() } func (r *RedisRepository) Get(key string) (string, error) { return r.db.Get(key).Result() } func (r *RedisRepository) Delete(key string) error { return r.db.Del(key).Err() }
package common import ( "github.com/micro/go-micro/client" "mix/test/utils/dispatcher" ) var Dispatcher *dispatcher.Dispatcher func initDispatcher(cli client.Client) { Dispatcher = dispatcher.NewDispatcher(cli) }
package password import ( "reflect" "strings" "github.com/aghape/auth" "github.com/aghape/auth/auth_identity" "github.com/aghape/auth/claims" "github.com/aghape/core/utils" "github.com/aghape/session" ) // DefaultAuthorizeHandler default authorize handler var DefaultAuthorizeHandler = func(context *auth.Context) (*claims.Claims, error) { var ( authInfo auth_identity.Basic req = context.Request db = context.DB provider, _ = context.Provider.(*Provider) ) req.ParseForm() authInfo.Provider = provider.GetName() authInfo.UID = strings.TrimSpace(req.Form.Get("login")) if db.Model(context.Auth.AuthIdentityModel).Where(authInfo).Scan(&authInfo).RecordNotFound() { return nil, auth.ErrInvalidAccount } if provider.Config.Confirmable && authInfo.ConfirmedAt == nil { currentUser, _ := context.Auth.UserStorer.Get(authInfo.ToClaims(), context) provider.Config.ConfirmMailer(authInfo.UID, context, authInfo.ToClaims(), currentUser) return nil, ErrUnconfirmed } if err := provider.Encryptor.Compare(authInfo.EncryptedPassword, strings.TrimSpace(req.Form.Get("password"))); err == nil { return authInfo.ToClaims(), nil } return nil, auth.ErrInvalidPassword } // DefaultRegisterHandler default register handler var DefaultRegisterHandler = func(context *auth.Context) (*claims.Claims, error) { var ( err error currentUser interface{} schema auth.Schema authInfo auth_identity.Basic req = context.Request db = context.DB provider, _ = context.Provider.(*Provider) ) req.ParseForm() if req.Form.Get("login") == "" { return nil, auth.ErrInvalidAccount } if req.Form.Get("password") == "" { return nil, auth.ErrInvalidPassword } authInfo.Provider = provider.GetName() authInfo.UID = strings.TrimSpace(req.Form.Get("login")) if !db.Model(context.Auth.AuthIdentityModel).Where(authInfo).Scan(&authInfo).RecordNotFound() { return nil, auth.ErrInvalidAccount } if authInfo.EncryptedPassword, err = provider.Encryptor.Digest(strings.TrimSpace(req.Form.Get("password"))); err == nil { schema.Provider = authInfo.Provider schema.UID = authInfo.UID schema.Email = authInfo.UID schema.RawInfo = req currentUser, authInfo.UserID, err = context.Auth.UserStorer.Save(&schema, context) if err != nil { return nil, err } // create auth identity authIdentity := reflect.New(utils.ModelType(context.Auth.Config.AuthIdentityModel)).Interface() if err = db.Where(authInfo).FirstOrCreate(authIdentity).Error; err == nil { if provider.Config.Confirmable { context.SessionStorer.Flash(context.SessionManager(), session.Message{Message: ConfirmFlashMessage, Type: "success"}) err = provider.Config.ConfirmMailer(schema.Email, context, authInfo.ToClaims(), currentUser) } return authInfo.ToClaims(), err } } return nil, err }
package parser import ( "encoding/xml" "fmt" "io/ioutil" "os" "strings" ) // the root <mule> tags type Mule struct { XMLName xml.Name `xml:"mule"` // <mule> defined as root to structure TestList []Test `xml:"test"` // <munit:test>s add an instance to TestList } // each <munit:test> tag // test's naming conventions should be Flow_Case_Result // Flow - the flow the case is testing // Case - the condition which the test is executing // Result - the expected behavior of the test type Test struct { XMLName xml.Name `xml:"test"` RawXML string `xml:",innerxml"` // capture all message processers within a test Name string `xml:"name,attr"` // name attribute within munit test. Naming syntax is Flow_Case_Result Flow string // parsed name's Flow value Case string // parsed name's Case value Result string // parsed name's Result value Description string `xml:"description,attr"` // description attribute within munit test. } // reads a file and parses it into a Mule struct func Read(inputFile string) *Mule { xmlFile, err := os.Open(inputFile) defer xmlFile.Close() ingestedXML, err := ioutil.ReadAll(xmlFile) if err != nil { fmt.Println(err) } mtest := loadMuleStruct(ingestedXML) return mtest } // splits name field of Flow_Case_Result into seperate fields func parseName(testList []Test) { for index, test := range testList { nameFields := strings.Split(test.Name, "_") testList[index].Flow = nameFields[0] testList[index].Case = nameFields[1] testList[index].Result = nameFields[2] } } // loads file contents in Mule struct func loadMuleStruct(ingestedXML []byte) *Mule { var mtest *Mule xml.Unmarshal(ingestedXML, &mtest) parseName(mtest.TestList) return mtest }
package main import ( //"log" "net/http" "regexp" "strings" "github.com/codegangsta/martini" "github.com/coopernurse/gorp" "github.com/zachlatta/southbayfession/misc" "github.com/zachlatta/southbayfession/models" "github.com/zachlatta/southbayfession/routes" ) // The one and only martini instance. var m *martini.Martini func init() { m = martini.New() // Setup middleware m.Use(martini.Recovery()) m.Use(martini.Logger()) m.Use(misc.Prerender) m.Use(martini.Static("public")) m.Use(MapEncoder) // Setup routes r := martini.NewRouter() r.Get(`/southbayfession/schools`, routes.GetSchools) r.Get(`/southbayfession/schools/:id`, routes.GetSchool) r.Get(`/southbayfession/tweets`, routes.GetTweets) // Inject database m.MapTo(models.Dbm, (*gorp.SqlExecutor)(nil)) // Add the router action m.Action(r.Handle) } // The regex to check for the requested format (allows an optional trailing // slash). var rxExt = regexp.MustCompile(`(\.(?:xml|text|json))\/?$`) // MapEncoder intercepts the request's URL, detects the requested format, // and injects the correct encoder dependency for this request. It rewrites // the URL to remove the format extension, so that routes can be defined // without it. func MapEncoder(c martini.Context, w http.ResponseWriter, r *http.Request) { // Get the format extension matches := rxExt.FindStringSubmatch(r.URL.Path) ft := ".json" if len(matches) > 1 { // Rewrite the URL without the format extension l := len(r.URL.Path) - len(matches[1]) if strings.HasSuffix(r.URL.Path, "/") { l-- } r.URL.Path = r.URL.Path[:l] ft = matches[1] } // Inject the requested encoder switch ft { case ".xml": c.MapTo(routes.XmlEncoder{}, (*routes.Encoder)(nil)) w.Header().Set("Content-Type", "application/xml") case ".text": c.MapTo(routes.TextEncoder{}, (*routes.Encoder)(nil)) w.Header().Set("Content-Type", "text/plain; charset=utf-8") default: c.MapTo(routes.JsonEncoder{}, (*routes.Encoder)(nil)) w.Header().Set("Content-Type", "application/json") } } func main() { go misc.FetchLatestTweetsManager() m.Run() }
package v1alpha1 type KafkaAutoCommit struct { Enable bool `json:"enable" protobuf:"varint,1,opt,name=enable"` }
package main import "fmt" func main() { var answer1, answer2, answer3 string fmt.Println("Your Name: ") _, err := fmt.Scan(&answer1) if err != nil { fmt.Println(err) } fmt.Println("Favourite Food: ") _, err = fmt.Scan(&answer2) if err != nil { fmt.Println(err) } fmt.Println("Favourite drink: ") _, err = fmt.Scan(&answer3) if err != nil { fmt.Println(err) } fmt.Println(answer1, answer2, answer3) }
/* Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. */ package main import ( "fmt" ) func pos_neg(a int, b int, negative bool) bool { /* multiplication of a negative and positive number will always return a negative number. This guarantees that the two parameters have opposite sign. Similarly two negative numbers will always return a positive number when multiplied. */ return (a * b) < 0 && ! negative || negative && ((a * b) > 0) } func main(){ var status int = 0 if pos_neg(1, -1, false) { status += 1 } if pos_neg(-1, 1, false) { status += 1 } if pos_neg(-4, -5, true) { status += 1 } if ! pos_neg(4, -5, true) { status += 1 } if status == 4 { fmt.Println("OK") } else { fmt.Println("NOT OK") } }
package bbir type Callback func(*CallbackOptions) func NewDefaultCallbackOptions() *CallbackOptions { return &CallbackOptions{ Each: func() {}, Before: func() {}, After: func() {}, } } type CallbackOptions struct { Each func() Before func() After func() } func Before(f func()) Callback { return func(c *CallbackOptions) { c.Before = f } } func Each(f func()) Callback { return func(c *CallbackOptions) { c.Each = f } } func After(f func()) Callback { return func(c *CallbackOptions) { c.After = f } }
package main import ( "net/http" "net/http/httptest" "testing" "fmt" "encoding/json" "gopkg.in/h2non/gock.v1" "io/ioutil" "github.com/Bobochka/thumbnail_service/lib/service" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" ) func Test(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Suite") } var _ = Describe("App", func() { var app *App BeforeSuite(func() { cfg, err := ReadConfig() Expect(err).NotTo(HaveOccurred()) app = &App{service: service.New(cfg)} }) Describe("/thumbnail", func() { DescribeTable("Invalid Params", func(url, width, height, desc string) { query := fmt.Sprintf("?url=%s&width=%s&height=%s", url, width, height) rr, err := Request(app, query) Expect(err).NotTo(HaveOccurred()) resp := struct{ Error string }{} err = json.Unmarshal(rr.Body.Bytes(), &resp) Expect(err).NotTo(HaveOccurred()) Expect(resp.Error).To(Equal(desc)) Expect(rr.Code).To(Equal(400)) }, Entry("url invalid", "malformed.com", "", "", "url malformed.com is not valid"), Entry("width NaN", "http://google.com", "width", "", "width width is not valid: should be positive integer"), Entry("width < 0", "http://google.com", "-42", "", "width -42 is not valid: should be positive integer"), Entry("width = 0", "http://google.com", "0", "", "width 0 is not valid: should be positive integer"), Entry("height NaN", "http://google.com", "42", "height", "height height is not valid: should be positive integer"), Entry("height < 0", "http://google.com", "42", "-42", "height -42 is not valid: should be positive integer"), Entry("height = 0", "http://google.com", "42", "0", "height 0 is not valid: should be positive integer"), Entry("too big", "http://google.com", "42000", "42000", "requested size of 42000 x 42000 is too big"), ) Context("Presumably Valid params", func() { var rr *httptest.ResponseRecorder BeforeEach(func() { gock.EnableNetworking() // in order to access s3 }) AfterEach(func() { gock.Off() }) JustBeforeEach(func() { query := "?url=http://foo.com/sample.jpg&width=200&height=200" var err error rr, err = Request(app, query) Expect(err).NotTo(HaveOccurred()) }) Context("When valid indeed params", func() { BeforeEach(func() { gock.New("http://foo.com"). Get("/sample.jpg"). Reply(200). File("./testdata/sample.jpg") }) AfterEach(func() { Expect(gock.IsDone()).To(BeTrue()) }) It("Renders thumbnail", func() { data, err := ioutil.ReadFile("./testdata/result.jpg") Expect(err).NotTo(HaveOccurred()) Expect(rr.Code).To(Equal(200)) Expect(rr.Body.Bytes()).To(Equal(data)) }) }) Context("When actually not an image", func() { BeforeEach(func() { gock.New("http://foo.com"). Get("/sample.jpg"). Reply(200). JSON("trap") }) AfterEach(func() { Expect(gock.IsDone()).To(BeTrue()) }) It("Responds with error", func() { resp := struct{ Error string }{} err := json.Unmarshal(rr.Body.Bytes(), &resp) Expect(err).NotTo(HaveOccurred()) Expect(resp.Error).To(Equal("Content type is not supported, supported formats: jpeg, gif, png")) Expect(rr.Code).To(Equal(400)) }) }) }) }) }) func Request(app *App, query string) (*httptest.ResponseRecorder, error) { req, err := http.NewRequest("GET", "/thumbnail"+query, nil) if err != nil { return nil, err } rr := httptest.NewRecorder() handler := http.HandlerFunc(app.thumbnail) handler.ServeHTTP(rr, req) return rr, nil }
package models import ( "time" ) //GetGraphByHostID by id func GetGraphByHostID(hostid int, start, end int64) ([]GraphInfo, int64, error) { rep, err := API.CallWithError("graph.get", Params{"output": "extend", "hostids": hostid, "sortfiled": "name"}) if err != nil { return []GraphInfo{}, 0, err } hba, err := json.Marshal(rep.Result) if err != nil { return []GraphInfo{}, 0, err } EndTime := time.Unix(end, 0).Format("2006-01-02 15:04:05") StartTime := time.Unix(start, 0).Format("2006-01-02 15:04:05") var hb []GraphInfo err = json.Unmarshal(hba, &hb) if err != nil { return []GraphInfo{}, 0, err } var bb GraphInfo var cc []GraphInfo for _, v := range hb { bb.GraphID = "/v1/images/" + v.GraphID + "?from=" + StartTime + "?to=" + EndTime bb.Name = v.Name cc = append(cc, bb) } return cc, int64(len(hb)), err }
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) type Instruction struct { operation int value int visited bool } func main() { file, _ := os.Open("input/day08.txt") defer file.Close() scanner := bufio.NewScanner(file) executable := make([]Instruction, 0) jumps := make([]int, 0) i := 0 for scanner.Scan() { text := scanner.Text() split := strings.Split(text, " ") op := split[0] val64, _ := strconv.ParseInt(split[1], 10, 64) val := int(val64) instruction := Instruction{} instruction.value = val instruction.visited = false if op == "nop" { instruction.operation = 0 } else if op == "acc" { instruction.operation = 1 } else { instruction.operation = 2 jumps = append(jumps, i) } executable = append(executable, instruction) i += 1 } executablePart2 := make([]Instruction, len(executable)) copy(executablePart2, executable) part1(executable) part2(executablePart2, jumps) } func part1(executable []Instruction) { pc := 0 acc := 0 for true { instruction := &executable[pc] if instruction.visited { fmt.Printf("Part1: %d \n", acc) break } else { instruction.visited = true if instruction.operation == 0 { pc += 1 } else if instruction.operation == 1 { acc += instruction.value pc += 1 } else { pc += instruction.value } } } } func part2(executable []Instruction, jumps []int) { for _, jump := range jumps { executableCopy := make([]Instruction, len(executable)) copy(executableCopy, executable) pc := 0 acc := 0 for true { if pc >= len(executableCopy) { fmt.Printf("Part2: %d \n", acc) break } instruction := &executableCopy[pc] if pc > len(executableCopy) { fmt.Printf("Part2: %d \n", acc) } if instruction.visited { break } else { instruction.visited = true if pc == jump || instruction.operation == 0 { pc += 1 } else if instruction.operation == 1 { acc += instruction.value pc += 1 } else { jumps = append(jumps, pc) pc += instruction.value } } } } }
package parser import ( "errors" "fmt" "strings" "github.com/josa42/go-xcode-project/pbxproj/ast" "github.com/josa42/go-xcode-project/pbxproj/lexer" "github.com/josa42/go-xcode-project/pbxproj/token" ) type Parser struct { l *lexer.Lexer curToken token.Token peekToken token.Token } func New(l *lexer.Lexer) *Parser { p := &Parser{} p.l = l p.nextToken() p.nextToken() return p } func (p *Parser) Parse() (ast.Node, error) { if p.curTokenIs(token.LBRACE) { return p.parseDict() } else if p.curTokenIs(token.LPAREN) { return p.parseList() } else { return nil, errors.New("Invalid Start Token") } } func (p *Parser) parseList() (*ast.ListNode, error) { if err := p.expectTokenIs(token.LPAREN); err != nil { return nil, err } p.nextToken() list := &ast.ListNode{} for !p.curTokenIs(token.EOF) { switch p.curToken.Type { case token.RPAREN: p.nextToken() return list, nil case token.COMMA: p.nextToken() default: v, err := p.parseValue() if err != nil { return nil, err } list.Append(v) if err := p.expectTokenIs(token.COMMA, token.RPAREN); err != nil { return nil, err } } } return nil, errors.New("Syntax Error: Missing }") } func (p *Parser) parseDict() (*ast.DictNode, error) { if err := p.expectTokenIs(token.LBRACE); err != nil { return nil, err } p.nextToken() dict := &ast.DictNode{} for !p.curTokenIs(token.EOF) { switch p.curToken.Type { case token.KEY: key := p.curToken p.nextToken() if err := p.expectTokenIs(token.ASSIGN); err != nil { return nil, err } p.nextToken() v, err := p.parseValue() if err != nil { return nil, err } dict.Set(key.Literal, v) if err := p.expectTokenIs(token.SEMICOLON, token.RBRACE); err != nil { return nil, err } case token.SEMICOLON: p.nextToken() case token.RBRACE: p.nextToken() return dict, nil default: return nil, fmt.Errorf("Syntax Error: Unexpected '%s' [%s]", p.curToken.Literal, p.curToken.Type) } } return nil, errors.New("Syntax Error: Missing }") } func (p *Parser) parseValue() (ast.Node, error) { switch p.curToken.Type { case token.LBRACE: return p.parseDict() case token.LPAREN: return p.parseList() case token.STRING: s := ast.StringNode{Value: p.curToken.Literal} p.nextToken() return s, nil default: return nil, fmt.Errorf("Syntax Error: Unxpected %s", p.curToken.Type) } } func (p *Parser) nextToken() { p.curToken = p.peekToken p.peekToken = p.l.NextToken() // fmt.Printf("curToken = '%s' [%s]\n", p.curToken.Literal, p.curToken.Type) } func (p *Parser) curTokenIs(t token.TokenType) bool { return p.curToken.Type == t } func (p *Parser) peekTokenIs(t token.TokenType) bool { return p.peekToken.Type == t } func (p *Parser) expectTokenIs(ts ...token.TokenType) error { for _, t := range ts { if p.curToken.Type == t { return nil } } exp := "" if len(ts) == 1 { exp = string(ts[0]) } else if len(ts) > 1 { l := ts[len(ts)-1] r := []string{} for _, t := range ts[:len(ts)-1] { r = append(r, string(t)) } exp = fmt.Sprintf("%s or %s", strings.Join(r, ", "), l) } return fmt.Errorf("Syntax Error: Expected %s | Not: %s", exp, p.curToken.Literal) }
package connector import ( "sync" ) type Statistics interface { Requests() uint TokenCacheHitsAtApiLevel() uint TokenCacheMissesAtApiLevel() uint TokenCacheFailsAtApiLevel() uint TokenCacheHitsAtAuthLevel() uint TokenCacheMissesAtAuthLevel() uint TokenCacheFailsAtAuthLevel() uint } type statistics struct { requests uint cacheMissesAtApiLevel uint cacheHitsAtApiLevel uint cacheFailsAtApiLevel uint cacheHitsAtAuthLevel uint cacheMissesAtAuthLevel uint cacheFailsAtAuthLevel uint mutex sync.RWMutex } func (s *statistics) Requests() (r uint) { s.mutex.RLock() r = s.requests s.mutex.RUnlock() return } func (s *statistics) TokenCacheMissesAtApiLevel() (r uint) { s.mutex.RLock() r = s.cacheMissesAtApiLevel s.mutex.RUnlock() return } func (s *statistics) TokenCacheHitsAtApiLevel() (r uint) { s.mutex.RLock() r = s.cacheHitsAtApiLevel s.mutex.RUnlock() return } func (s *statistics) TokenCacheFailsAtApiLevel() (r uint) { s.mutex.RLock() r = s.cacheFailsAtApiLevel s.mutex.RUnlock() return } func (s *statistics) TokenCacheHitsAtAuthLevel() (r uint) { s.mutex.RLock() r = s.cacheHitsAtAuthLevel s.mutex.RUnlock() return } func (s *statistics) TokenCacheMissesAtAuthLevel() (r uint) { s.mutex.RLock() r = s.cacheMissesAtAuthLevel s.mutex.RUnlock() return } func (s *statistics) TokenCacheFailsAtAuthLevel() (r uint) { s.mutex.RLock() r = s.cacheFailsAtAuthLevel s.mutex.RUnlock() return } func (s *statistics) Request() { s.mutex.Lock() s.requests++ s.mutex.Unlock() } func (s *statistics) CacheHitAtApiLevel() { s.mutex.Lock() s.cacheHitsAtApiLevel++ s.mutex.Unlock() } func (s *statistics) CacheMissAtApiLevel() { s.mutex.Lock() s.cacheMissesAtApiLevel++ s.mutex.Unlock() } func (s *statistics) CacheFailAtApiLevel() { s.mutex.Lock() s.cacheFailsAtApiLevel++ s.mutex.Unlock() } func (s *statistics) CacheHitAtAuthLevel() { s.mutex.Lock() s.cacheHitsAtAuthLevel++ s.mutex.Unlock() } func (s *statistics) CacheMissAtAuthLevel() { s.mutex.Lock() s.cacheMissesAtAuthLevel++ s.mutex.Unlock() } func (s *statistics) CacheFailAtAuthLevel() { s.mutex.Lock() s.cacheFailsAtAuthLevel++ s.mutex.Unlock() }
package main import ( "fmt" "log" "os" "sync" ) // CacheEvent type CacheEvent struct { Key string File string Op CacheOp } type CacheOp uint8 const ( UPDATE = 1 DELETE = 2 ) func (event CacheEvent) String() string { switch (event.Op) { case UPDATE: return fmt.Sprintf("[Event] UPDATE \n\tFile: %s\n\tKey: %s", event.File, event.Key) case DELETE: return fmt.Sprintf("[Event] DELETE \n\tFile: %s\n\tKey: %s", event.File, event.Key) } return "" } // /CacheEvent type CacheItem struct { Key string File string } /* wrap items in concurrency safe lock */ type itemIndex struct { sync.RWMutex items map[string]string } type Cache struct { Events chan CacheEvent items *itemIndex done chan bool } func NewCache() *Cache { cache := Cache{} cache.done = make(chan bool, 1) cache.Listen() return &cache } func (cache *Cache) Close() { log.Println("Closing cache...") cache.done <- true close(cache.Events) } /* * Listen for cache events */ func (cache *Cache) Listen() { cache.Events = make(chan CacheEvent) cache.items = &itemIndex{items: make(map[string]string)} go func() { for { select { case <- cache.done: return case event := <- cache.Events: log.Println("Event received...") if event.Op == UPDATE { cache.updateCache(event.File, event.Key) } if event.Op == DELETE { if event.File != "" { cache.deleteCacheItemByFile(event.File) } else { cache.deleteCacheItem(event.Key) } } } } }() } // set the item in the index func (cache *Cache) updateCache(file string, key string) { log.Println("Update: ", file, " ", key) cache.items.Lock() cache.items.items[key] = file cache.items.Unlock() } func (cache *Cache) deleteCacheItemByFile(file string) { log.Println("deleting by filename: " + file) cache.items.Lock() defer cache.items.Unlock() for key := range cache.items.items { if cache.items.items[key] == file { delete(cache.items.items, key) return } } } // delete the file and remove from index func (cache *Cache) deleteCacheItem(key string) { log.Println("REMOVE: ", key) file, exists := cache.items.items[key] if !exists { log.Println("Key not found in cache: " + key) log.Println(cache.items.items) return } cache.items.Lock() delete(cache.items.items, key) cache.items.Unlock() _, err := os.Stat(file) if os.IsNotExist(err) { log.Println("File does not exist") } else { os.Remove(file) } }
package template import ( "github.com/TuiBianWuLu/samplewechat/config" "github.com/TuiBianWuLu/samplewechat/token" "fmt" "github.com/TuiBianWuLu/samplewechat/util/request" "encoding/json" "github.com/TuiBianWuLu/samplewechat/util/response" ) const ( SendTemplateUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send" SetIndustryUrl = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry" GetIndustryUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry" GetTmpIDUrl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template" GetTmpListUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template" DelTemplateUrl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template" ) type Template struct { *config.Config } var m = new(Template) func New(c *config.Config) *Template { m.Config = c return m } func (t *Template) Send(content Template) (sendTemplateRes SendTemplateRes, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", SendTemplateUrl, accessToken) res, err := request.Post(url, content) if err != nil { return } json.Unmarshal(res, &sendTemplateRes) return } func (t *Template) SetIndustry(industry Industry) (resMsg response.CommonError, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", SetIndustryUrl, accessToken) res, err := request.Post(url, industry) if err != nil { return } json.Unmarshal(res, &resMsg) return } func (t *Template) GetIndustry() (industryRes GetIndustryRes, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", GetIndustryUrl, accessToken) res, err := request.Get(url) if err != nil { return } json.Unmarshal(res, &industryRes) return } func (t *Template) GetTmpID(templateID GetTemplateID) (templateIdRes GetTemplateIdRes, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", GetTmpIDUrl, accessToken) res, err := request.Post(url, templateID) if err != nil { return } json.Unmarshal(res, &templateIdRes) return } func (t *Template) GetTmpList() (tmpListRes GetTemplateListRes, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", GetTmpListUrl, accessToken) res, err := request.Get(url) if err != nil { return } json.Unmarshal(res, &tmpListRes) return } func (t *Template) DelTemplate(templateID DelTemplateID) (resMsg response.CommonError, err error) { accessToken, err := token.NewAccessToken(t.Config).AccessToken() if err != nil { return } url := fmt.Sprintf("%s?access_token=%s", DelTemplateUrl, accessToken) res, err := request.Post(url, templateID) if err != nil { return } json.Unmarshal(res, &resMsg) return }
package main type VictoryState int const ( Ongoing = VictoryState(iota) Lost Won )
package basic import "fmt" // 声明一个包含10个元素的int类型数组,数组不能改变大小 var a [10]int func ArrayDemo() { a[0] = 1 a[1] = 2 a[3] = 3 a[4] = 4 fmt.Println(a) // 初始化数组,注意:数组的初始化需要指定大小或者通过 ... 让编译器推断大小(大小根据初始化的元素确定) array := [3]int{1, 2, 3} array2 := [...]int{1, 2, 3, 4, 5} array3 := [...]int{4: 2} // 长度为5,原因是最后一个元素的下标为4,值为2 fmt.Println(array) fmt.Println(array2) fmt.Println(array3) // 数组的切片,半开区间,前闭后开的区间,下面的操作得到的是a[1],a[2],a[3] 3个元素 // 注意:切片并不会创建新的空间,只是展示原数组的数据,修改切片的数据会导致原数组的数据被修改(其他包含相同元素的切片也可以 // 观察到相应的修改) // len(s) 可以得到切片s的长度(即切片中的元素个数),cap(s)得到切片的容量,切片容量是指是从它的第一个元素开始数, // 到其底层数组元素末尾的个数。参考下面的sliceOfa,此切片从数组的第1个元素开始,所以其容量是9(数组长度为10) sliceOfa := a[1:4] slice2 := a[2:6] fmt.Printf("第一个切片,类型: %T, %v 长度: %v, 容量: %v , 另一个切片:%v\n", sliceOfa, sliceOfa, len(sliceOfa), cap(sliceOfa), slice2) sliceOfa[0] = 100 sliceOfa[1] = 200 fmt.Printf("修改切片的内容,导致原数组的数据被修改: %v 另一个切片观察到的值:%v \n", a, slice2) // 切片的方式创建一个数组,注意与数组创建时的区别(不指定长度),下面的过程是创建了一个数组,然后构建一个切片,此切片引用了该数组 slince3 := []int{1, 2, 3, 4, 5} fmt.Println(slince3) // 切片上下界的默认值,下界默认值为0,上界默认值为数组长度 defaultSlice0 := a[:] // 0~9 (下界为0,数组a长度为10,所以上界为10) defaultSlice1 := a[:2] // 0~1 (上界是开区间,故不包括2) defaultSlice2 := a[3:] // 3~9 fmt.Printf("slice0: %v, slice1: %v, slice2: %v \n", defaultSlice0, defaultSlice1, defaultSlice2) } // 内建函数make可以用来创建切片,可通过make来创建动态数组 func MakeDemo() { // make 函数会分配一个元素为零值的数组并返回一个引用了它的切片 s := make([]int, 5) // 创建一个长度为5的切片(底层数组长度为5) s2 := make([]int, 5, 10) // 创建一个长度为5,容量为10的切片(底层数组长度为10) fmt.Printf("切片s的长度 %v, 容量 %v ", len(s), cap(s)) fmt.Printf("切片s2的长度 %v, 容量 %v\n", len(s2), cap(s2)) fmt.Printf("append前,s的地址:%p, 长度%v, 容量 %v ", s, len(s), cap(s)) s = append(s, 1, 2, 3) fmt.Printf("append后,s的地址:%p, 长度%v, 容量 %v\n", s, len(s), cap(s)) // 切片的切片 sliceOfSlice := [][]string{ []string{"a", "b", "c"}, []string{"1", "2", "3"}, } fmt.Println(sliceOfSlice) appendSlice := []int{1, 2, 3, 4, 5} fmt.Printf("%p ,length: %v, capacity: %v, content %v \n", appendSlice, len(appendSlice), cap(appendSlice), appendSlice) appendSlice = append(appendSlice, 6, 7, 8, 9, 0) fmt.Printf("after append, %p, length: %v, capacity: %v, content %v \n", appendSlice, len(appendSlice), cap(appendSlice), appendSlice) // for range遍历切片,range操作会返回两个值,第一个是元素下标,第二个是元素值, // 和py一样,如果不需要使用元素下标,可以用 _ 来忽略它 for i, v := range appendSlice { fmt.Print("appendSlice[", i, "]=", v, " ") } fmt.Println() }
package cli import ( "encoding/json" "path/filepath" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/gookit/gcli/v3" "github.com/ovrclk/akcmd/client" "github.com/ovrclk/akcmd/flags" "github.com/pkg/errors" tmtypes "github.com/tendermint/tendermint/types" ) const flagGenTxDir = "gentx-dir" var collectGentxOpts = struct { GentxDir string }{} // CollectGenTxsCmd - return the cobra command to collect genesis transactions func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator) *gcli.Command { cmd := &gcli.Command{ Name: "collect-gentxs", Desc: "Collect genesis txs and output a genesis.json file", Config: func(cmd *gcli.Command) { flags.AddHomeFlagToCmd(cmd) cmd.StrOpt(&collectGentxOpts.GentxDir, flagGenTxDir, "", "", "override default \"gentx\" directory from which collect and execute genesis transactions; default [--home]/config/gentx/") }, Func: func(cmd *gcli.Command, _ []string) error { serverCtx := client.GetServerContextFromCmd() config := serverCtx.Config clientCtx, err := client.GetClientContextFromCmd() if err != nil { return err } cdc := clientCtx.Codec config.SetRoot(clientCtx.HomeDir) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config) if err != nil { return errors.Wrap(err, "failed to initialize node validator files") } genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile()) if err != nil { return errors.Wrap(err, "failed to read genesis doc from file") } genTxsDir := collectGentxOpts.GentxDir if genTxsDir == "" { genTxsDir = filepath.Join(config.RootDir, "config", "gentx") } toPrint := newPrintInfo(config.Moniker, genDoc.ChainID, nodeID, genTxsDir, json.RawMessage("")) initCfg := types.NewInitConfig(genDoc.ChainID, genTxsDir, nodeID, valPubKey) appMessage, err := genutil.GenAppStateFromConfig(cdc, clientCtx.TxConfig, config, initCfg, *genDoc, genBalIterator) if err != nil { return errors.Wrap(err, "failed to get genesis app state from config") } toPrint.AppMessage = appMessage return displayInfo(toPrint) }, } return cmd }
package main import ( "bytes" "go-postgres/middleware" "net/http" "net/http/httptest" "strings" "testing" _ "github.com/lib/pq" ) func TestSetUp(t *testing.T) { //Deletes all entries in book table and resets primary key sequence middleware.PrepForTesting() } func TestCreateBook(t *testing.T) { //tests adding a new book var jsonStr = []byte(`{"Title":"Crime and Punishment","Author":"Fyodor Dostoyevsky","Publisher":"The Russian Messenger","Publish_Date":"1886-02-15","Rating":2.8,"Status":false}`) //create new POST request using api route for adding a new book req, err := http.NewRequest("POST", "/api/newbook", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } //set required headers req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.CreateBook) handler.ServeHTTP(rr, req) //check to see if connected properly if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should return success message expected := `"message":"Book added successfully"` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") //check to see if correct message was returned successfully if !strings.Contains(data, expected) { t.Errorf("Handler response %v did not contain %v", data, expected) } //Test adding another book jsonStr = []byte(`{"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":3,"Status":false}`) req, err = http.NewRequest("POST", "/api/newbook", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr = httptest.NewRecorder() handler = http.HandlerFunc(middleware.CreateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected = `"message":"Book added successfully"` expected = strings.TrimRight(expected, "\r\n") data = strings.TrimRight(rr.Body.String(), "\r\n") if !strings.Contains(data, expected) { t.Errorf("Handler response %v did not contain %v", data, expected) } } func TestCreateBookFailed(t *testing.T) { //First test checks if user tries to update book with rating above the accepted range var jsonStr = []byte(`{"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":5,"Status":true}`) req, err := http.NewRequest("POST", "/api/newbook", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.CreateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should show message correct rating range to user expected := `{"id":-1,"message":"Rating needs to be in range 1-3"}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } //Third test checks if user tries to update book with rating bellow the accepted range jsonStr = []byte(`{"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":0,"Status":true}`) req, err = http.NewRequest("POST", "/api/newbook", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr = httptest.NewRecorder() handler = http.HandlerFunc(middleware.CreateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should show message correct rating range to user expected = `{"id":-1,"message":"Rating needs to be in range 1-3"}` expected = strings.TrimRight(expected, "\r\n") data = strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestGetBooks(t *testing.T) { req, err := http.NewRequest("GET", "/api/book", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.GetAllBooks) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `[{"ID":1,"Title":"Crime and Punishment","Author":"Fyodor Dostoyevsky","Publisher":"The Russian Messenger","Publish_Date":"1886-02-15T00:00:00Z","Rating":2.8,"Status":false},{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":3,"Status":false}]` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", data, expected) } } func TestGetBook(t *testing.T) { req, err := http.NewRequest("GET", "/api/book/2", nil) //req, err := http.NewRequest("GET", "/api/book/1", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.GetBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":3,"Status":false}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestGetBookFailed(t *testing.T) { req, err := http.NewRequest("GET", "/api/book/3", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.GetBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected := `{"ID":0,"Title":"","Author":"","Publisher":"","Publish_Date":"","Rating":0,"Status":false}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestEditEntry(t *testing.T) { var jsonStr = []byte(`{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":2.65,"Status":true}`) req, err := http.NewRequest("PUT", "/api/book/2", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.UpdateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected := `{"id":2,"message":"User updated successfully. Total rows/record affected 1 "}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestEditEntryFailed(t *testing.T) { //first test for trying to edit book that doesnt exist var jsonStr = []byte(`{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":2.65,"Status":true}`) req, err := http.NewRequest("PUT", "/api/book/3", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.UpdateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should show that 0 rows/records were affected because book with id 3 does not exist expected := `{"id":3,"message":"User updated successfully. Total rows/record affected 0 "}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } //Second test checks if user tries to update book with rating above the accepted range jsonStr = []byte(`{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":5,"Status":true}`) req, err = http.NewRequest("PUT", "/api/book/2", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr = httptest.NewRecorder() handler = http.HandlerFunc(middleware.UpdateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should show message correct rating range to user expected = `{"id":2,"message":"Rating needs to be in range 1-3"}` expected = strings.TrimRight(expected, "\r\n") data = strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } //Third test checks if user tries to update book with rating bellow the accepted range jsonStr = []byte(`{"ID":2,"Title":"Harry Potter and the Chamber of Secrets","Author":"J.K. Rowling","Publisher":"Bloomsbury","Publish_Date":"1998-07-02T00:00:00Z","Rating":0,"Status":true}`) req, err = http.NewRequest("PUT", "/api/book/2", bytes.NewBuffer(jsonStr)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr = httptest.NewRecorder() handler = http.HandlerFunc(middleware.UpdateBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //should show message correct rating range to user expected = `{"id":2,"message":"Rating needs to be in range 1-3"}` expected = strings.TrimRight(expected, "\r\n") data = strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestDeleteBook(t *testing.T) { req, err := http.NewRequest("DELETE", "/api/deletebook/1", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.DeleteBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected := `{"id":1,"message":"User updated successfully. Total rows/record affected 1"}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } } func TestDeleteBookFailed(t *testing.T) { req, err := http.NewRequest("DELETE", "/api/deletebook/3", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(middleware.DeleteBook) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } expected := `{"id":3,"message":"User updated successfully. Total rows/record affected 0"}` expected = strings.TrimRight(expected, "\r\n") data := strings.TrimRight(rr.Body.String(), "\r\n") if data != expected { t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected) } }
package main import ( "time" "log" //"errors" //"sync/atomic" "github.com/liujianping/consumer" ) type context struct{ main chan bool count int32 } func (c *context) Do(req interface{}) error { r, _ := req.(*MyProduct) return r.Do(c) } func (c *context) Encode(request interface{}) ([]byte, error) { return nil,nil } func (c *context) Decode(data []byte) (interface{}, error) { return nil,nil } func (p *MyProduct) Do(c *context) error { log.Printf("product No(%d) do", p.No) time.Sleep(time.Millisecond * 250) if p.No == 30 { c.main <- true } log.Printf("product No(%d) Done", p.No) return nil } type MyProduct struct{ No int } func main() { core := &context{ main: make(chan bool, 0), count:0} consumer := consumer.NewMemoryConsumer("sleepy", 10) consumer.Resume(core, 4) for i:= 1; i <= 30; i++ { consumer.Put(&MyProduct{i}) } log.Printf("consumer running %v", consumer.Running()) consumer.Close() log.Printf("consumer running %v", consumer.Running()) }
/** * constants * @author liuzhen * @Description * @version 1.0.0 2021/1/28 16:56 */ package utils import "testing" func TestGeneratePrivateAndPublicKey(t *testing.T) { } func TestParsingRsaPublicKey(t *testing.T) { } func TestParsingRsaPrivateKey(t *testing.T) { }
package widget import ( "image" "image/color" "gioui.org/f32" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" "gioui.org/op/paint" "gioui.org/text" "gioui.org/unit" ) // SliderStyle is a multi-slider widget. type SliderStyle struct { Shaper text.Shaper Font text.Font ThumbRadius unit.Value TrackWidth unit.Value FingerSize unit.Value TrackColor func(int) color.NRGBA ThumbColor func(int) color.NRGBA Min, Max float32 Range *Range } func (ss SliderStyle) Layout(gtx layout.Context) layout.Dimensions { thumbRadius := gtx.Px(ss.ThumbRadius) trackWidth := gtx.Px(ss.TrackWidth) fingerSize := gtx.Px(ss.FingerSize) width := gtx.Constraints.Max.X height := max(thumbRadius*2, max(trackWidth, fingerSize*2)) size := image.Pt(width, height) br := image.Rectangle{Max: size} defer op.Save(gtx.Ops).Load() clip.Rect(br).Add(gtx.Ops) gtx.Constraints.Min = image.Pt(width, br.Dy()) ss.Range.Layout(gtx, thumbRadius, fingerSize, ss.Min, ss.Max) op.Offset(f32.Pt(float32(thumbRadius), float32(height)/2)).Add(gtx.Ops) tr := image.Rect(0, -trackWidth/2, width-2*thumbRadius, trackWidth/2) var prevV float32 for i, v := range ss.Range.Values { v = (v - ss.Min) / (ss.Max - ss.Min) if v != prevV { drawTrack(gtx.Ops, ss.TrackColor(i), tr, prevV, v) } prevV = v } if prevV != 1 { drawTrack(gtx.Ops, ss.TrackColor(len(ss.Range.Values)), tr, prevV, 1) } for i, v := range ss.Range.Values { v = (v - ss.Min) / (ss.Max - ss.Min) drawThumb(gtx.Ops, ss.ThumbColor(i), tr, float32(fingerSize), float32(thumbRadius), v) } return layout.Dimensions{Size: size} } func max(a, b int) int { if a > b { return a } return b } // drawTrack draws track segment betwee a and b. Both a and b values are // normalized to and must be in range [0, 1]. func drawTrack(ops *op.Ops, c color.NRGBA, tr image.Rectangle, a, b float32) { paint.FillShape(ops, c, clip.Rect{ Min: image.Pt(int(float32(tr.Max.X)*a), tr.Min.Y), Max: image.Pt(int(float32(tr.Max.X)*b), tr.Max.Y), }.Op()) } func drawThumb(ops *op.Ops, c color.NRGBA, tr image.Rectangle, finger, rad, a float32) { center := f32.Pt(float32(tr.Dx())*a, float32(tr.Min.Y+tr.Dy()/2)) if finger > rad { c := c c.A /= 2 paint.FillShape(ops, c, clip.Circle{ Center: center, Radius: finger, }.Op(ops)) } paint.FillShape(ops, c, clip.Circle{ Center: center, Radius: rad, }.Op(ops)) }
package hash import ( "crypto/md5" "io/ioutil" "network" "os" "reflect" "strings" ) func InitializeUserAuthenticationMap(filePathToUserAuthenticationTxt string) (userAuthenticationMap map[string][16]byte) { content, err := ioutil.ReadFile(filePathToUserAuthenticationTxt) if network.ErrorHandler(err, "Error encountered while parsing user authentication data: %v") { os.Exit(1) } username, password := GetUserNameAndPasswordFromFile(string(content)) userAuthenticationMap = make(map[string][16]byte) userAuthenticationMap[username] = CreateHashFromString(password) return } func GetUserNameAndPasswordFromFile(fileContent string) (username, password string) { lines := strings.Split(string(fileContent), "\n") username = lines[0] password = lines[1] return } func CreateHashFromString(inputString string) (outputHash [16]byte) { data := []byte(inputString) outputHash = md5.Sum(data) return } func IsHashMatchInUserAuthenticationMap(inputUsername, inputPassword string, userAuthenticationMap map[string][16]byte) (hashMatch bool) { targetHash := CreateHashFromString(inputPassword) return reflect.DeepEqual(userAuthenticationMap[inputUsername], targetHash) }
package config const LastCommitLog = " " const BuildDate = "Sun Apr 5 05:41:34 2020" const Version = "0.0.1_SNAPSHOT"
package main import ( "flag" "fmt" "log" "math" "os/exec" "runtime" "strconv" "time" "github.com/alex023/clock" "github.com/ghostiam/systray" "github.com/webview/webview" ) func makeTimestamp() int64 { return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)) } func fmtDuration(d time.Duration) string { h := d / time.Hour d -= h * time.Hour m := d / time.Minute d -= m * time.Minute s := d / time.Second return fmt.Sprintf("%02d:%02d:%02d", h, m, s) } // LogPrintf Log func LogPrintf(format string, v ...interface{}) { log.Printf(format, v...) broadcast(fmt.Sprintf(format, v...)) } // LogPrint Log func LogPrint(v ...interface{}) { log.Print(v...) broadcast(fmt.Sprint(v...)) } var startTime int64 var offset int64 var oldOffset int64 = -1 var gui bool var version = "0.11.0" func reset(newOffsetMilliseconds int64) { offset = newOffsetMilliseconds if offset < 0 { offset = 0 } broadcast("time=" + strconv.Itoa(int(offset))) log.Printf("Reset %d", offset) if gui { systray.SetTitle(fmtDuration(time.Duration(offset))) } } func start() { if startTime == 0 { startTime = makeTimestamp() - offset log.Print("Clock started") } } func stop() { if startTime > 0 { startTime = 0 log.Print("Clock stopped") } } func incrementTime(secondes int64) { if startTime == 0 { reset(offset + secondes*1000) } } func main() { host := flag.String("h", GetLocalIP(), "network host to serve on") port := flag.String("p", "8811", "http port to serve on") osc := flag.String("o", "8812", "osc port to serve on") g := flag.Bool("g", true, "launch native gui") flag.Parse() gui = *g if gui { go serveHTTP(*host, *port) } go serveOSC(*host, *osc) myClock := clock.NewClock() job, ok := myClock.AddJobRepeat(time.Duration(100*time.Millisecond), 0, func() { if startTime > 0 { broadcast("time=" + strconv.FormatInt(offset, 10)) offset = makeTimestamp() - startTime } if math.Floor(float64(oldOffset)/1000) != math.Floor(float64(offset)/1000) { if gui { systray.SetTitle(fmtDuration(time.Duration(offset) * time.Millisecond)) } oldOffset = offset } }) if !ok { log.Println("Fail to start timer") } defer job.Cancel() if !gui { serveHTTP(*host, *port) } else { // needs to be on the main thread w := webview.New(false) defer w.Destroy() w.SetSize(480, 620, webview.HintFixed) w.SetTitle("Chronono " + version) url := "http://" + *host + ":" + *port systray.Register(func() { systray.SetTitle(fmtDuration(0)) systray.SetIcon(TrayIcon) systray.SetTooltip("Chronono") mLink := systray.AddMenuItem("Chronono", "Launch browser page") systray.AddSeparator() mQuit := systray.AddMenuItem("Quit", "Quit the whole app") go func() { for { select { case <-mLink.ClickedCh: switch runtime.GOOS { case "linux": _ = exec.Command("xdg-open", url).Start() case "windows", "darwin": _ = exec.Command("open", url).Start() } case <-mQuit.ClickedCh: log.Println("Requesting quit") w.Terminate() log.Println("Finished quitting") } } }() }) w.Navigate(url) w.Run() w.Destroy() } }
package main type Secret struct { Secret string Passphrase string TTL string Recipient string }
package gateway import ( "context" "errors" "time" "github.com/MagalixCorp/magalix-agent/v3/agent" "github.com/MagalixCorp/magalix-agent/v3/client" "github.com/MagalixTechnologies/core/logger" "github.com/MagalixTechnologies/uuid-go" "go.uber.org/zap/zapcore" ) const auditResultsBatchSize = 1000 type MagalixGateway struct { MgxAgentGatewayUrl string AccountID uuid.UUID ClusterID uuid.UUID ClientSecret []byte AgentVersion string AgentID string K8sServerVersion string AgentPermissions string ClusterProvider string ProtoHandshake time.Duration ProtoWriteTime time.Duration ProtoReadTime time.Duration ProtoReconnectTime time.Duration ProtoBackoff time.Duration ShouldSendLogs bool gwClient *client.Client connectedChan chan bool cancelWorkers context.CancelFunc addConstraints agent.ConstraintsHandler handleAuditCommand agent.AuditCommandHandler triggerRestart agent.RestartHandler changeLogLevel agent.ChangeLogLevelHandler auditResultsBuffer []*agent.AuditResult auditResultChan chan *agent.AuditResult } func New( gatewayUrl string, accountID uuid.UUID, clusterID uuid.UUID, secret []byte, agentVersion string, agentID string, k8sServerVersion string, agentPermissions string, clusterProvider string, protoHandshake time.Duration, protoWriteTime time.Duration, protoReadTime time.Duration, protoReconnectTime time.Duration, protoBackoff time.Duration, sendLogs bool, ) *MagalixGateway { connected := make(chan bool) return &MagalixGateway{ MgxAgentGatewayUrl: gatewayUrl, AccountID: accountID, ClusterID: clusterID, ClientSecret: secret, AgentVersion: agentVersion, AgentID: agentID, K8sServerVersion: k8sServerVersion, AgentPermissions: agentPermissions, ClusterProvider: clusterProvider, ProtoHandshake: protoHandshake, ProtoWriteTime: protoWriteTime, ProtoReadTime: protoReadTime, ProtoReconnectTime: protoReconnectTime, ProtoBackoff: protoBackoff, ShouldSendLogs: sendLogs, connectedChan: connected, gwClient: client.InitClient( agentVersion, agentID, accountID, clusterID, secret, k8sServerVersion, agentPermissions, clusterProvider, gatewayUrl, protoHandshake, protoWriteTime, protoReadTime, protoReconnectTime, protoBackoff, sendLogs, ), auditResultsBuffer: make([]*agent.AuditResult, 0, auditResultsBatchSize), auditResultChan: make(chan *agent.AuditResult, 50), } } func (g *MagalixGateway) Start(ctx context.Context) error { if g.cancelWorkers != nil { g.cancelWorkers() } cancelCtx, cancel := context.WithCancel(ctx) g.cancelWorkers = cancel defer g.gwClient.Recover() go g.SendAuditResultsWorker(cancelCtx) return g.gwClient.Connect(cancelCtx, g.connectedChan) } func (g *MagalixGateway) Stop() error { g.cancelWorkers() return nil } func (g *MagalixGateway) WaitAuthorization(timeout time.Duration) error { logger.Info("waiting for connection and authorization") if g.gwClient.IsReady() { return nil } select { case <-g.connectedChan: logger.Info("Connected and authorized") return nil case <-time.After(timeout): err := errors.New("authorization timeout") logger.Error(err) return err } } func (g *MagalixGateway) GetLogsWriteSyncer() zapcore.WriteSyncer { return g.gwClient }
package collectors import ( "time" "github.com/cloudfoundry-community/go-cfclient" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" ) type ServicesCollector struct { namespace string environment string deployment string cfClient *cfclient.Client serviceInfoMetric *prometheus.GaugeVec servicesScrapesTotalMetric prometheus.Counter servicesScrapeErrorsTotalMetric prometheus.Counter lastServicesScrapeErrorMetric prometheus.Gauge lastServicesScrapeTimestampMetric prometheus.Gauge lastServicesScrapeDurationSecondsMetric prometheus.Gauge } func NewServicesCollector( namespace string, environment string, deployment string, cfClient *cfclient.Client, ) *ServicesCollector { serviceInfoMetric := prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: namespace, Subsystem: "service", Name: "info", Help: "Labeled Cloud Foundry Service information with a constant '1' value.", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, []string{"service_id", "service_label"}, ) servicesScrapesTotalMetric := prometheus.NewCounter( prometheus.CounterOpts{ Namespace: namespace, Subsystem: "services_scrapes", Name: "total", Help: "Total number of scrapes for Cloud Foundry Services.", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, ) servicesScrapeErrorsTotalMetric := prometheus.NewCounter( prometheus.CounterOpts{ Namespace: namespace, Subsystem: "services_scrape_errors", Name: "total", Help: "Total number of scrape error of Cloud Foundry Services.", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, ) lastServicesScrapeErrorMetric := prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: namespace, Subsystem: "", Name: "last_services_scrape_error", Help: "Whether the last scrape of Services metrics from Cloud Foundry resulted in an error (1 for error, 0 for success).", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, ) lastServicesScrapeTimestampMetric := prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: namespace, Subsystem: "", Name: "last_services_scrape_timestamp", Help: "Number of seconds since 1970 since last scrape of Services metrics from Cloud Foundry.", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, ) lastServicesScrapeDurationSecondsMetric := prometheus.NewGauge( prometheus.GaugeOpts{ Namespace: namespace, Subsystem: "", Name: "last_services_scrape_duration_seconds", Help: "Duration of the last scrape of Services metrics from Cloud Foundry.", ConstLabels: prometheus.Labels{"environment": environment, "deployment": deployment}, }, ) return &ServicesCollector{ namespace: namespace, environment: environment, deployment: deployment, cfClient: cfClient, serviceInfoMetric: serviceInfoMetric, servicesScrapesTotalMetric: servicesScrapesTotalMetric, servicesScrapeErrorsTotalMetric: servicesScrapeErrorsTotalMetric, lastServicesScrapeErrorMetric: lastServicesScrapeErrorMetric, lastServicesScrapeTimestampMetric: lastServicesScrapeTimestampMetric, lastServicesScrapeDurationSecondsMetric: lastServicesScrapeDurationSecondsMetric, } } func (c ServicesCollector) Collect(ch chan<- prometheus.Metric) { var begun = time.Now() errorMetric := float64(0) if err := c.reportServicesMetrics(ch); err != nil { errorMetric = float64(1) c.servicesScrapeErrorsTotalMetric.Inc() } c.servicesScrapeErrorsTotalMetric.Collect(ch) c.servicesScrapesTotalMetric.Inc() c.servicesScrapesTotalMetric.Collect(ch) c.lastServicesScrapeErrorMetric.Set(errorMetric) c.lastServicesScrapeErrorMetric.Collect(ch) c.lastServicesScrapeTimestampMetric.Set(float64(time.Now().Unix())) c.lastServicesScrapeTimestampMetric.Collect(ch) c.lastServicesScrapeDurationSecondsMetric.Set(time.Since(begun).Seconds()) c.lastServicesScrapeDurationSecondsMetric.Collect(ch) } func (c ServicesCollector) Describe(ch chan<- *prometheus.Desc) { c.serviceInfoMetric.Describe(ch) c.servicesScrapesTotalMetric.Describe(ch) c.servicesScrapeErrorsTotalMetric.Describe(ch) c.lastServicesScrapeErrorMetric.Describe(ch) c.lastServicesScrapeTimestampMetric.Describe(ch) c.lastServicesScrapeDurationSecondsMetric.Describe(ch) } func (c ServicesCollector) reportServicesMetrics(ch chan<- prometheus.Metric) error { c.serviceInfoMetric.Reset() services, err := c.cfClient.ListServices() if err != nil { log.Errorf("Error while listing services: %v", err) return err } for _, service := range services { c.serviceInfoMetric.WithLabelValues( service.Guid, service.Label, ).Set(float64(1)) } c.serviceInfoMetric.Collect(ch) return nil }
package handler import ( "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // SubmitMeasurementStatusTestSuite 是 SubmitMeasurementStatus rpc 的单元测试的 Test Suite type SubmitMeasurementStatusTestSuite struct { suite.Suite jinmuHealth *JinmuHealth } // SetupSuite 设置测试环境 func (suite *SubmitMeasurementStatusTestSuite) SetupSuite() { suite.jinmuHealth = new(JinmuHealth) envFilepath := filepath.Join("testdata", "local.svc-biz-core.env") suite.jinmuHealth.datastore, _ = newTestingDbClientFromEnvFile(envFilepath) suite.jinmuHealth.mailClient, _ = newTestingMailClientFromEnvFile(envFilepath) } // TestMeasurementStatus测试提交测量时状态 func (suite *SubmitMeasurementStatusTestSuite) TestMeasurementStatus() { t := suite.T() // mock 一次登录 var password = "release1" var testRecordID int32 = 1 ctx, _ := mockLogin(suite.jinmuHealth, testUsername, password) req, resp := new(proto.SubmitMeasurementStatusRequest), new(proto.SubmitMeasurementStatusResponse) req.RecordId = testRecordID req.Lactation = proto.Status_STATUS_UNSELECTED_STATUS req.Pregnancy = proto.Status_STATUS_SELECTED_STATUS assert.NoError(t, suite.jinmuHealth.SubmitMeasurementStatus(ctx, req, resp)) // 查找这个 record } func TestSubmitMeasurementStatusTestSuite(t *testing.T) { suite.Run(t, new(SubmitMeasurementStatusTestSuite)) }
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { query() } func check(err error) { if err != nil { fmt.Println(err) panic(err) } } func query() { db, err := sql.Open("mysql", "root:!QAZ2wsx@tcp(127.0.0.1:3306)/jdbc") check(err) rows, err := db.Query("select * from myuser s") check(err) for rows.Next() { columns, _ := rows.Columns() scanArgs := make([]interface{}, len(columns)) values := make([]interface{}, len(columns)) for i := range values { scanArgs[i] = &values[i] } //将数据保存到 record 字典 err = rows.Scan(scanArgs...) record := make(map[string]string) for i, col := range values { if col != nil { record[columns[i]] = string(col.([]byte)) } } fmt.Println(record) } rows.Close() }
package controllers import ( "BitcoinWeb/models/user" "github.com/astaxie/beego" ) type MainController struct { beego.Controller } type RegisterController struct { beego.Controller } func (c *MainController) Get() { c.TplName = "login_and_register.html" } func (c *MainController) Post(){ c.TplName = "login_and_register.html" } func (r *RegisterController) Get() { var user user.NewUser err :=r.ParseForm(&user) if err != nil { r.Ctx.WriteString("对不起,解析数据错误") return } _,err =user.SaveUser() if err !=nil { r.Ctx.WriteString("对不起,用户注册失败") return } r.TplName ="login_and_register.html" } func (r *RegisterController) Post() { var user user.NewUser err :=r.ParseForm(&user) if err != nil { r.Ctx.WriteString("对不起,解析数据错误") return } _,err =user.SaveUser() if err !=nil { r.Ctx.WriteString("对不起,用户注册失败") return } r.TplName ="login_and_register.html" }
package main import "fmt" func main() { printEveryDivisibleRange(10, 35, 3) } func printEveryDivisibleRange(n int, m int, x int) { for i := n ; i <= m ; i++ { if i % x == 0 { fmt.Println(i) } } }
package slashing import ( "testing" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestHookOnValidatorBonded(t *testing.T) { ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) addr := sdk.ConsAddress(addrs[0]) keeper.onValidatorBonded(ctx, addr, nil) period := keeper.getValidatorSlashingPeriodForHeight(ctx, addr, ctx.BlockHeight()) require.Equal(t, ValidatorSlashingPeriod{addr, ctx.BlockHeight(), 0, sdk.ZeroDec()}, period) } func TestHookOnValidatorBeginUnbonding(t *testing.T) { ctx, _, _, _, keeper := createTestInput(t, DefaultParams()) addr := sdk.ConsAddress(addrs[0]) keeper.onValidatorBonded(ctx, addr, nil) keeper.onValidatorBeginUnbonding(ctx, addr, addrs[0]) period := keeper.getValidatorSlashingPeriodForHeight(ctx, addr, ctx.BlockHeight()) require.Equal(t, ValidatorSlashingPeriod{addr, ctx.BlockHeight(), ctx.BlockHeight(), sdk.ZeroDec()}, period) }
package main import ( "fmt" ) func main() { dst := []int{1, 2, 3, 4} src := []int{5, 6, 7} count := copy(dst[2:], src) fmt.Println(dst, count) }
/** * 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 test import ( _ "msb2pilot/routers" "net/http" "net/http/httptest" "path/filepath" "runtime" "testing" "github.com/astaxie/beego" . "github.com/smartystreets/goconvey/convey" ) func init() { _, file, _, _ := runtime.Caller(1) apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator)))) beego.TestBeegoInit(apppath) } // TestBeego is a sample to run an endpoint test func TestBeego(t *testing.T) { r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() beego.BeeApp.Handlers.ServeHTTP(w, r) beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String()) Convey("Subject: Test Station Endpoint\n", t, func() { Convey("Status Code Should Be 200", func() { So(w.Code, ShouldEqual, 200) }) Convey("The Result Should Not Be Empty", func() { So(w.Body.Len(), ShouldBeGreaterThan, 0) }) }) }
package main import ( "io/ioutil" "encoding/json" "bytes" "flag" "fmt" "github.com/perriv/go-tasker" "os" "os/exec" "sort" "strings" ) var version = "0.3.1" func is_visible_dir(fi os.FileInfo) bool { return fi.Mode().IsDir() && !strings.HasPrefix(fi.Name(), ".") } func list_visible_dirs(path string) ([]string, error) { f, err := os.Open(path) if err != nil { return nil, err } fis, err := f.Readdir(0) f.Close() if err != nil { return nil, err } dirs := make([]string, 0) for _, fi := range fis { if is_visible_dir(fi) { dirs = append(dirs, fi.Name()) } } dirs = dirs[:len(dirs)] sort.Strings(dirs) return dirs, nil } // Read a file line-by-line with \n (linux) line endings. Returns a list of // lines with line endings removed. // Read the JSON configuration provided. If c is an empty string, just return // the default configuration (the list of visible directories in the current // working directory). func read_config(c string) ([]string, error) { if c == "" { return list_visible_dirs(".") } data, err := ioutil.ReadFile(c) if err != nil { return nil, err } config := make([]string, 0) err = json.Unmarshal(data, &config) if err != nil { return nil, err } return config, nil } func cmd_task(cmd *exec.Cmd, l *logger, data map[string][]byte) tasker.Task { return func() error { prefix := fmt.Sprintf("%s: %s", cmd.Dir, strings.Join(cmd.Args, " ")) l.ok("%s: started\n", prefix) // Create the directory if it does not exist. if _, err := os.Stat(cmd.Dir); err != nil { l.ok("%s: creating directory\n", prefix) err = os.Mkdir(cmd.Dir, 0755) if err != nil { l.bad("%s: failed to create directory: %s\n", prefix, err) os.Exit(-1) } } dat, err := cmd.CombinedOutput() if err == nil { l.good("%s: finished\n", prefix) } else { l.bad("%s: failed: %s\n", prefix, err) } data[cmd.Dir] = dat return err } } func main() { var j int var v bool var c string flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [options] [--] <command>...\n\n", os.Args[0]) fmt.Fprintln(os.Stderr, "Options:") flag.PrintDefaults() } flag.StringVar(&c, "c", "", "Configuration file") flag.IntVar(&j, "j", -1, "Number of concurrent subprocesses") flag.BoolVar(&v, "v", false, "Print out the version and exit") flag.Parse() if v { fmt.Println(version) os.Exit(0) } // 1 or more arguments are required. cmd_format := flag.Args() if len(cmd_format) == 0 { flag.Usage() os.Exit(2) } config, err := read_config(c) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(-1) } if len(config) == 0 { fmt.Println("Nothing to do") os.Exit(0) } sort.Strings(config) // Create the Tasker that runs all of the commands. tr, err := tasker.NewTasker(j) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(-1) } // This logger coordinates printed among the tasks. l := new_logger() data := make(map[string][]byte) for _, dir := range config { // A command may include {} to interpolate the current directory. name := strings.Replace(cmd_format[0], "{}", dir, -1) args := make([]string, 0) for _, arg_f := range cmd_format[1:] { args = append(args, strings.Replace(arg_f, "{}", dir, -1)) } // Add a task that runs the interpolated command in dir. cmd := exec.Command(name, args...) cmd.Dir = dir tr.Add(dir, nil, cmd_task(cmd, l, data)) } err = tr.Run() for _, dir := range config { if len(data[dir]) == 0 { continue } lines := bytes.Split(data[dir], []byte{10}) for _, line := range lines { os.Stdout.WriteString(dir) os.Stdout.WriteString(": ") os.Stdout.Write(line) os.Stdout.WriteString("\n") } } if err != nil { os.Exit(-1) } }
// sqliteToMysql package main import ( //"crypto/md5" //"crypto/rand" "database/sql" "os" "strconv" "time" //"encoding/base64" //"encoding/hex" //"encoding/json" //"fmt" //"io" //"io/ioutil" "log" //"net/http" //"path" sw "sqliteToMysql/switcher" "strings" //xupload "xinlanAdminTest/xinlanUpload" //"github.com/codegangsta/negroni" _ "github.com/go-sql-driver/mysql" //"github.com/julienschmidt/httprouter" _ "github.com/mattn/go-sqlite3" ) type Announcement struct { Id int Video_id int Announcement string Announcementdatatime string } type VideosAddclicks struct { Id int Video_id int Add_clicks int } type VideosClicks struct { Id int Ip string Video_id int } type Reply struct { Id int Comment_id int Reply string } type Video struct { Id int `json:"id"` Title string `json:"title"` Introduction string `json:"introduction"` VideoStream string `json:"videostream"` } type VideoComment struct { Id int `json:"id"` Video_id int `json:"videoid"` Comment string `json:"comment"` Logdate string `json:"logdate"` User_id int `json:"userid"` User_img string `json:"userimg"` User_name string `json:"username"` IsChecked int `json:"ischecked"` } func main() { //直播 //Videos() //Videos_Comments() //Videos_Addclicks() //Videos_Announcement() //Videos_Clicks() //Videos_Reply() //投票 //sw.Vote() //sw.Votes_App_User() //sw.Votes_Candidate() sw.Votes_Clicks() //sw.Votes_Comments() //sw.Votes_Info() //sw.Votes_Seq() //热点 //sw.Hot_clicks() //sw.Hot_comments() //sw.Hot_events() //sw.Hotsall() //sw.User_info() //sw.Hot_zans() } func Videos_Reply() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v Reply var str string rows, err := db.Query("select * from videos_reply") if err != nil { log.Println(err) } f, err2 := os.Create("videosReply.txt") if err2 != nil { panic(err2) } defer f.Close() for rows.Next() { rows.Scan(&v.Id, &v.Comment_id, &v.Reply) str += strconv.Itoa(v.Id) + "," + strconv.Itoa(v.Comment_id) + "," + v.Reply + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videosReply.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") _, err = db.Exec("insert into videos_reply(id,comment_id,reply) values(?,?,?)", s1[0], s1[1], s1[2]) if err != nil { log.Println(err) } } } } func Videos_Clicks() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v VideosClicks var str string rows, err := db.Query("select * from videos_clicks") if err != nil { log.Println(err) } f, err2 := os.Create("videosClicks.txt") if err2 != nil { panic(err2) } defer f.Close() for rows.Next() { rows.Scan(&v.Id, &v.Ip, &v.Video_id) str += strconv.Itoa(v.Id) + "," + v.Ip + "," + strconv.Itoa(v.Video_id) + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videosClicks.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") _, err = db.Exec("insert into videos_clicks(id,ip,video_id) values(?,?,?)", s1[0], s1[1], s1[2]) if err != nil { log.Println(err) } } } } func Videos_Announcement() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v Announcement var str string var t time.Time rows, err := db.Query("select * from videos_announcement") if err != nil { log.Println(err) } f, err2 := os.Create("videosAnnouncement.txt") if err2 != nil { panic(err2) } defer f.Close() for rows.Next() { rows.Scan(&v.Id, &v.Video_id, &v.Announcement, &t) v.Announcementdatatime = t.Format("2006-01-02 15:04:05") str += strconv.Itoa(v.Id) + "," + strconv.Itoa(v.Video_id) + "," + v.Announcement + "," + v.Announcementdatatime + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videosAnnouncement.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") _, err = db.Exec("insert into videos_announcement(id,video_id,announcement,announcement_datatime) values(?,?,?,?)", s1[0], s1[1], s1[2], s1[3]) if err != nil { log.Println(err) } } } } func Videos_Addclicks() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v VideosAddclicks var str string rows, err := db.Query("select * from videos_addclicks") if err != nil { log.Println(err) } f, err2 := os.Create("videosAddclicks.txt") if err2 != nil { panic(err2) } defer f.Close() for rows.Next() { rows.Scan(&v.Id, &v.Video_id, &v.Add_clicks) str += strconv.Itoa(v.Id) + "," + strconv.Itoa(v.Video_id) + "," + strconv.Itoa(v.Add_clicks) + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videosAddclicks.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") _, err = db.Exec("insert into videos_addclicks(id,video_id,add_clicks) values(?,?,?)", s1[0], s1[1], s1[2]) if err != nil { log.Println(err) } } } } func Videos_Comments() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v VideoComment var str string rows, err := db.Query("select * from videos_comments") if err != nil { log.Println(err) } f, err2 := os.Create("videosComments.txt") if err2 != nil { panic(err2) } defer f.Close() var t time.Time for rows.Next() { rows.Scan(&v.Id, &v.Video_id, &v.Comment, &t, &v.User_id, &v.User_img, &v.User_name, &v.IsChecked) v.Logdate = t.Format("2006-01-02 15:04:05") str += strconv.Itoa(v.Id) + "," + strconv.Itoa(v.Video_id) + "," + v.Comment + "," + v.Logdate + "," + strconv.Itoa(v.User_id) + "," + v.User_img + "," + v.User_name + "," + strconv.Itoa(v.IsChecked) + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videosComments.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") //log.Println(s1[0], s1[1], s1[2], s1[3], s1[4], s1[5], s1[6], s1[7]) _, err = db.Exec("insert into videos_comments(id,video_id,comment,logdate,user_id,user_img,user_name,is_checked) values(?,?,?,?,?,?,?,?)", s1[0], s1[1], s1[2], s1[3], s1[4], s1[5], s1[6], s1[7]) if err != nil { log.Println(err) } } } } func Videos() { //读取sqlite数据,写入到txt db := ConnectDB("./middle_video.db") defer func() { db.Close() err := recover() if err != nil { log.Println(err) } }() var v Video var str string rows, err := db.Query("select * from videos") if err != nil { log.Println(err) } f, err2 := os.Create("videos.txt") if err2 != nil { panic(err2) } defer f.Close() for rows.Next() { rows.Scan(&v.Id, &v.Title, &v.Introduction, &v.VideoStream) str += strconv.Itoa(v.Id) + "," + v.Title + "," + v.Introduction + "," + v.VideoStream + "\n" } f.WriteString(str) //读取txt数据,写入到mysql中 db = ConnectMySql() defer func() { db.Close() err5 := recover() if err5 != nil { log.Println(err5) } }() f2, err3 := os.Open("videos.txt") if err3 != nil { panic(err3) } defer f2.Close() stat, err4 := f2.Stat() if err4 != nil { log.Println(err4) } size := stat.Size() a := make([]byte, size) f2.Read(a) //log.Println(string(a)) arr := strings.Split(string(a), "\n") for _, v := range arr { if v != "" { s1 := strings.Split(v, ",") _, err = db.Exec("insert into videos(id,title,introduction,videostream) values(?,?,?,?)", s1[0], s1[1], s1[2], s1[3]) if err != nil { log.Println(err) } } } } func ConnectDB(dbPath string) *sql.DB { db, err := sql.Open("sqlite3", dbPath) if err != nil { panic(err) } return db } func ConnectMySql() *sql.DB { dbinfo := "root" + ":" + "123" + "@/" + "xinlanAdmin" + "?charset=utf8" db, err := sql.Open("mysql", dbinfo) if err != nil { panic(err) } return db }
package dao import ( "webapp/persistence/bolt" "webapp/persistence/memdb" ) const MEMORY = 1 const BOLTDB = 2 var implementation = MEMORY func SetDAOImplementation(implem int) { if implem == MEMORY || implem == BOLTDB { implementation = implem } else { panic("Cannot set DAO implementation : invalid implementation !") } } //-------------------------------------------------------------------------- // StudentDAO //-------------------------------------------------------------------------- var studentDAOBolt = bolt.NewStudentDAOBolt() var studentDAOMemory = memdb.NewStudentDAOMemory() func GetStudentDAO() StudentDAO { var dao StudentDAO = &studentDAOMemory if implementation == BOLTDB { dao = &studentDAOBolt } return dao } //-------------------------------------------------------------------------- // LanguageDAO //-------------------------------------------------------------------------- var languageDAOBolt = bolt.NewLanguageDAOBolt() var languageDAOMemory = memdb.NewLanguageDAOMemory() func GetLanguageDAO() LanguageDAO { if implementation == BOLTDB { return &languageDAOBolt } return &languageDAOMemory // Default implementation }
package goemetry type BoundingBox struct { BottomLeft Point Height uint Width uint } func (receiver *BoundingBox) IsAboveish(other BoundingBox) bool { yDistance := receiver.BottomLeft.Y - other.BottomLeft.Y if yDistance <= 0 { // receiver is actually below or level with other return false } if yDistance > int(receiver.Height)*2 && yDistance > int(other.Height)*2 { return false } return true }
package main import ( "encoding/json" "flag" "html/template" "net/http" "net/url" "sort" "time" ) var ( addr = flag.String("addr", ":8080", "ui address") apis = flag.String("api", "http://localhost:5000", "api address") tout = flag.Duration("tout", time.Second, "api cache timeout") host string // host:port of api server ) func main() { parseArgs() println("Serving on " + *addr) http.ListenAndServe(*addr, &memory{ tout: time.Now().Add(-*tout), data: func(w http.ResponseWriter, r *http.Request) { http.Error(w, "pending first load", http.StatusOK) }, }) } var htmlTPL = template.Must(template.New("").Parse(`<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Registry Listing</title> </head> <body> <ul> {{- range .}} <li>{{.}}</li> {{- else}}<li>No Repositories Found</li>{{end}} </ul> </body> </html>`)) func parseArgs() { flag.Parse() api, err := url.Parse(*apis) if err != nil { panic(err) } host = api.Host } type memory struct { data http.HandlerFunc tout time.Time } func (mem *memory) update() error { res, err := http.Get(*apis + "/v2/_catalog") if err != nil { return err } // TODO: check status var catalog struct { Repos []string `json:"repositories"` } if err := json.NewDecoder(res.Body).Decode(&catalog); err != nil { return err } if err := res.Body.Close(); err != nil { return err } data := make(map[string][]string, len(catalog.Repos)) for _, name := range catalog.Repos { res, err := http.Get(*apis + "/v2/" + name + "/tags/list") if err != nil { return err } // TODO: check status var tags struct { Name string `json:"name"` Tags []string `json:"tags"` } if err := json.NewDecoder(res.Body).Decode(&tags); err != nil { return err } data[name] = tags.Tags if err := res.Body.Close(); err != nil { return err } } data2 := make([]string, 0, len(catalog.Repos)) for repo, tags := range data { for _, tag := range tags { data2 = append(data2, host+"/"+repo+":"+tag) } } sort.Strings(data2) mem.data = func(w http.ResponseWriter, r *http.Request) { if err := htmlTPL.Execute(w, data2); err != nil { println("causing failure " + err.Error()) } } return nil } func (mem *memory) ServeHTTP(w http.ResponseWriter, r *http.Request) { now := time.Now() if now.After(mem.tout) { mem.tout = now.Add(*tout) if err := mem.update(); err != nil { mem.data = func(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) } } } w.Header().Add("X-BIGN8-TIMEOUT", mem.tout.String()) w.Header().Add("X-BIGN8-NOW", now.String()) mem.data(w, r) }
package main import "sort" const inf = 100000000000 func findMinArrowShots(points [][]int) int { sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) last := -inf count := 0 for i := 0; i < len(points); i++ { // 无重叠区间是>=,这是> if points[i][0] > last { last = points[i][1] count++ } } return count } /* 题目链接: https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/ 用最少数量的箭引爆气球 */ /* 总结 1. 这题和LeetCode_453_无重叠区间是一样的,只是现在[1,2][2,3]认为是覆盖的,所以上面要修改一个地方(已经在上面指出)。 2. 这题目是使用最少的弓箭射爆所有气球,所以要返回的是无覆盖区间的个数。 */
package main import ( "strings" "testing" ) func TestGetMountSource(t *testing.T) { mountinfo := `22 44 0:21 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw 23 44 0:22 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw 24 44 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,size=98841448k,nr_inodes=24710362,mode=755 26 24 0:23 / /dev/shm rw,nosuid,nodev shared:3 - tmpfs tmpfs rw 44 1 253:0 / / rw,relatime shared:1 - xfs /dev/mapper/system-root rw,attr2,inode64,logbufs=8,logbsize=32k,noquota 48 44 9:0 / /boot rw,relatime shared:28 - ext4 /dev/md0 rw 52 44 253:5 / /var rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota # must not be found 49 44 253:2 / /var rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota 3927 49 253:6 /zzz /var/lib/kubelet/pods/0abd8cda-b4fc-4241-bdad-13c3777daf63/volumes/kubernetes.io~csi/xxx/mount rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota # must not be found 3926 49 253:2 /lib/kubelet/plugins/kubernetes.io/csi/pv/xxx/globalmount /var/lib/kubelet/pods/0abd8cda-b4fc-4241-bdad-13c3777daf63/volumes/kubernetes.io~csi/xxx/mount rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota 50 44 253:3 /xxx /yyy rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota 51 44 253:4 / /va rw,relatime shared:29 - xfs /dev/mapper/system-var rw,attr2,inode64,logbufs=8,logbsize=32k,noquota ` r := strings.NewReader(mountinfo) mounts, err := parseMountInfo(r) if err != nil { t.Fatal(err) } source := `/var/lib/kubelet/plugins/kubernetes.io/csi/pv/xxx/globalmount` target := `/var/lib/kubelet/pods/0abd8cda-b4fc-4241-bdad-13c3777daf63/volumes/kubernetes.io~csi/xxx/mount` sourceOnDevice := `/lib/kubelet/plugins/kubernetes.io/csi/pv/xxx/globalmount` mount := mounts.getByMountPoint(target) if mount == nil { t.Errorf("mount not found: %q", target) } else if mount.id != "3926" { t.Errorf("invalid mount found: %q", mount.id) } sm := mounts.findByPath(source) if sm == nil { t.Errorf("source mount not found: %q", source) } else if sm.id != "49" { t.Errorf("invalid source mount found: %q", sm.id) } sod := sm.getPathOnDevice(source) if sod != sourceOnDevice { t.Errorf("invalid source path on device: %q != %q", sod, sourceOnDevice) } if !mounts.verifyMountSource(mount, source) { t.Error("invalid mount source") } mnt := mounts.getByMountPoint("/") path := mnt.getPathOnDevice("/abc/def") if path != "/abc/def" { t.Errorf("invalid path: %q != %q", path, "/abc/def") } mnt = mounts.getByMountPoint("/yyy") path = mnt.getPathOnDevice("/yyy/def") if path != "/xxx/def" { t.Errorf("invalid path: %q != %q", path, "/xxx/def") } }
package controller import "net/http" type AuthController interface { Signin(response http.ResponseWriter, request *http.Request) Signup(response http.ResponseWriter, request *http.Request) }
package util import ( "bufio" "io" "os" "strings" ) // OverlapWriteFile is overlap write data to file once func OverlapWriteFile(fileName, fileData string) { dirPathSlice := strings.Split(fileName, "/") os.MkdirAll(strings.Trim(fileName, dirPathSlice[len(dirPathSlice)-1]), 0755) f, fErr := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0777) if fErr != nil { ErrorLogger(fErr) } _, wErr := f.WriteString(fileData) if wErr != nil { ErrorLogger(wErr) } f.Sync() f.Close() } // MergeFile is merge file func MergeFile(oldFile, newFile string) { fo, foErr := os.OpenFile(oldFile, os.O_RDWR|os.O_APPEND, 0777) if foErr != nil { ErrorLogger(foErr) } // open new file fn, fnErr := os.Open(newFile) if fnErr != nil { ErrorLogger(fnErr) } // read new file rd := bufio.NewReader(fn) for { oneDoc, err := rd.ReadString('\n') if err != nil || io.EOF == err { break } CustomLogger("doc info:", oneDoc) // write old file _, fwErr := fo.WriteString(oneDoc) if fwErr != nil { ErrorLogger(fwErr) } } // clone new file fn.Close() // sync old file fo.Sync() // close old file fo.Close() } // DeleteFile is delete file func DeleteFile(fileName string) { err := os.Remove(fileName) if err != nil { ErrorLogger(err) } } // DeleteDir is delete dir func DeleteDir(dirPath string) { err := os.RemoveAll(dirPath) if err != nil { ErrorLogger(err) } }
package actions import ( "github.com/barrydev/api-3h-shop/src/model" ) func InsertOrderItemByOrderId(orderId int64, body *model.BodyOrderItem) (*model.OrderItem, error) { body.OrderId = &orderId return InsertOrderItem(body) }
package git import ( "errors" "git-get/pkg/git/test" "testing" "github.com/stretchr/testify/assert" ) func TestFinder(t *testing.T) { tests := []struct { name string reposMaker func(*testing.T) string want int }{ { name: "no repos", reposMaker: makeNoRepos, want: 0, }, { name: "single repos", reposMaker: makeSingleRepo, want: 1, }, { name: "single nested repo", reposMaker: makeNestedRepo, want: 1, }, { name: "multiple nested repo", reposMaker: makeMultipleNestedRepos, want: 2, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { root := test.reposMaker(t) finder := NewRepoFinder(root) finder.Find() assert.Len(t, finder.repos, test.want) }) } } // TODO: this test will only work on Linux func TestExists(t *testing.T) { tests := []struct { name string path string want error }{ { name: "dir does not exist", path: "/this/directory/does/not/exist", want: errDirNotExist, }, { name: "dir cant be accessed", path: "/root/some/directory", want: errDirNoAccess, }, { name: "dir exists", path: "/tmp/", want: nil, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { _, err := Exists(test.path) assert.True(t, errors.Is(err, test.want)) }) } } func makeNoRepos(t *testing.T) string { root := test.TempDir(t, "") return root } func makeSingleRepo(t *testing.T) string { root := test.TempDir(t, "") test.RepoEmptyInDir(t, root) return root } func makeNestedRepo(t *testing.T) string { // a repo with single nested repo should still be counted as one beacause finder doesn't traverse inside nested repos root := test.TempDir(t, "") r := test.RepoEmptyInDir(t, root) test.RepoEmptyInDir(t, r.Path()) return root } func makeMultipleNestedRepos(t *testing.T) string { root := test.TempDir(t, "") // create two repos inside root - should be counted as 2 repo1 := test.RepoEmptyInDir(t, root) repo2 := test.RepoEmptyInDir(t, root) // created repos nested inside two parent roots - shouldn't be counted test.RepoEmptyInDir(t, repo1.Path()) test.RepoEmptyInDir(t, repo1.Path()) test.RepoEmptyInDir(t, repo2.Path()) // create a empty dir inside root - shouldn't be counted test.TempDir(t, root) return root }
package model import ( "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/bson/primitive" "github.com/mongodb/mongo-go-driver/mongo" log "github.com/sirupsen/logrus" ) // Log ... type Log struct { Model `bson:",inline"` UserID primitive.ObjectID `bson:"user_id"` Method string `bson:"method"` URL string `bson:"url"` Permission string `bson:"permission"` Err string `bson:"err"` Detail string `bson:"detail"` VisitIP string `bson:"visit_ip"` } // NewLog ... func NewLog() *Log { return &Log{ Model: model(), } } // CreateIfNotExist ... func (l *Log) CreateIfNotExist() error { return CreateIfNotExist(l) } // Create ... func (l *Log) Create() error { return InsertOne(l) } // Update ... func (l *Log) Update() error { return UpdateOne(l) } // Delete ... func (l *Log) Delete() error { return DeleteByID(l) } // Find ... func (l *Log) Find() error { return FindByID(l) } // All ... func (l *Log) All() ([]*Log, error) { var logs []*Log m := bson.M{} err := Find(l, m, func(cursor mongo.Cursor) error { log.Println(cursor.DecodeBytes()) var l Log err := cursor.Decode(&l) if err != nil { return err } logs = append(logs, &l) return nil }) return logs, err } // Pages ... func (l *Log) Pages(order, limit, current int64) ([]*Log, int64) { var logs []*Log m := bson.M{} i, _ := Count(l, m) err := Pages(l, m, order, limit, current, func(cursor mongo.Cursor) error { log.Println(cursor.DecodeBytes()) var l Log err := cursor.Decode(&l) if err != nil { return err } logs = append(logs, &l) return nil }) if err != nil { return nil, 0 } return logs, i } func (l *Log) _Name() string { return "log" }
package cmd import ( "encoding/json" "log" "os" "github.com/spf13/cobra" "github.com/jmhobbs/wordpress-scanner/shared" ) var scanArchiveCmd = &cobra.Command{ Use: "scan-archive <plugin_name> <plugin_version> <plugin_archive>", Short: "Scans a plugin archive for corruption", Long: "", Run: func (cmd *cobra.Command, args []string) { if len(args) < 3 { errorAndExit("You must provide the plugin name, the plugin version, and the archive to scan") } else if len(args) > 3 { errorAndExit("You gave too many arguments") } plugin := args[0] version := args[1] archive := args[2] file, err := os.Open(archive) if err != nil { log.Fatal(err) } defer func() { file.Close() }() scan, err := shared.NewScanFromFile(plugin, version, file) if err != nil { log.Fatal(err) } json.NewEncoder(os.Stdout).Encode(scan) }, }
/* * @lc app=leetcode.cn id=973 lang=golang * * [973] 最接近原点的 K 个点 */ package solution // @lc code=start func kClosest(points [][]int, k int) [][]int { distance := func(p int) int { return points[p][0]*points[p][0] + points[p][1]*points[p][1] } qSort := func(l, r int) int { pivot := distance(l) for l < r { dr := distance(r) for r > l && dr >= pivot { r-- dr = distance(r) } points[l], points[r] = points[r], points[l] dl := distance(l) for l < r && dl <= pivot { l++ dl = distance(l) } points[l], points[r] = points[r], points[l] } return l } pivot := -1 l, r := 0, len(points)-1 for pivot != k-1 { if pivot < k-1 { l = pivot + 1 pivot = qSort(l, r) } else { r = pivot pivot = qSort(l, r) } } return points[:k] } // @lc code=end
// Copyright 2023 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 main import ( "os" "strings" "github.com/bazelbuild/buildtools/build" "github.com/pingcap/tidb/util/set" ) func write(path string, f *build.File) error { build.Rewrite(f) out := build.Format(f) return os.WriteFile(path, out, 0644) } func skipFlaky(path string) bool { var pmap = set.NewStringSet() pmap.Insert("tests/realtikvtest/addindextest/BUILD.bazel") return pmap.Exist(path) } func skipTazel(path string) bool { var pmap = set.NewStringSet() pmap.Insert("build/BUILD.bazel") return pmap.Exist(path) } func skipShardCount(path string) bool { return strings.HasPrefix(path, "tests") || (strings.HasPrefix(path, "util") && !strings.HasPrefix(path, "util/admin") && !strings.HasPrefix(path, "util/chunk") && !strings.HasPrefix(path, "util/stmtsummary")) }
package cosmiccart import ( "fmt" "os" "testing" "regexp" "sync" "github.com/stretchr/testify/assert" ) var md5Regex = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}") var ccApi = NewCosmicCart( "https://staging.cosmiccart.com/api", os.Getenv("COSMIC_CART_CLIENT_ID"), os.Getenv("COSMIC_CART_CLIENT_SECRET")) var atLock sync.Mutex var accessToken string func TestMain(m *testing.M) { resp, _ := ccApi.OAuthToken(Password) atLock.Lock() accessToken = resp.AccessToken atLock.Unlock() os.Exit(m.Run()) } func TestOAuth(t *testing.T) { oauthResponse, err := ccApi.OAuthToken(Password) assert.Nil(t, err) if assert.NotNil(t, oauthResponse) { assert.Regexp(t, md5Regex, oauthResponse.AccessToken) assert.Equal(t, oauthResponse.TokenType, "bearer") assert.Regexp(t, md5Regex, oauthResponse.RefreshToken) assert.True(t, oauthResponse.ExpiresIn > 0, "expires must be a non-negative integer") assert.Equal(t, "read write payments accounts export", oauthResponse.Scope) } } func TestCreateUser(t *testing.T) { atLock.Lock() userResponse, err := ccApi.CreateUser(map[string]interface{} { "name": "Edwin Fuquen", "email": os.Getenv("COSMIC_CART_TEST_EMAIL"), "password": os.Getenv("COSMIC_CART_TEST_PASSWORD"), }, accessToken) atLock.Unlock() assert.Nil(t, err) if assert.NotNil(t, userResponse) { fmt.Printf("%s\n", userResponse) } }
package redis // Config represents the configurations for the redis driver type Config struct { Network string `yaml:"net"` Addr string `yaml:"addr"` Timeout int64 `yaml:"timeout_ms"` Master bool `yaml:"master"` RepairEnabled bool `yaml:"repair_enabled"` RepairFrequency int `yaml:"repair_freq_ms"` TextCompressThreshold int `yaml:"text_compress_threshold"` DeleteChunkSize int `yaml:"del_chunk_size"` } var DefaultConfig = Config{ Network: "tcp", Addr: "localhost:6379", Timeout: 1000, Master: true, RepairEnabled: false, RepairFrequency: 50, TextCompressThreshold: 2048, DeleteChunkSize: 100, }
package main import ( "github.com/kazhuravlev/options-gen/options-gen" ) func main() { for _, params := range []struct { outFname string structName string }{ { outFname: "./example_out_options.go", structName: "Options", }, { outFname: "./example_out_config.go", structName: "Config", }, { outFname: "./example_out_params.go", structName: "Params", }, } { if err := optionsgen.Run( "./example_in.go", params.outFname, params.structName, "main", optionsgen.Defaults{From: optionsgen.DefaultsFromTag, Param: ""}, true, ); err != nil { panic(err) } } }
/* I didn't invent this challenge, but I find it very interesting to solve. For every input number, e.g.: 4 Generate a range from 1 to that number: [1 2 3 4] And then, for every item in that list, generate a list from 1 to that number: [[1] [1 2] [1 2 3] [1 2 3 4]] Then, reverse every item of that list. [[1] [2 1] [3 2 1] [4 3 2 1]] Notes: 1 being a loose item is allowed, since flattening will not matter with this anyway. To preserve the spirit of the challenge, the range has to be 1-indexed. You may flatten the list if your platform doesn't support the concept of nested lists. */ package main import "fmt" func main() { for i := 0; i <= 4; i++ { fmt.Println(riota(i)) } } func riota(n int) [][]int { var r [][]int for i := 0; i < n; i++ { p := make([]int, i+1) for j := 0; j <= i; j++ { p[j] = i - j + 1 } r = append(r, p) } return r }
/* Copyright 2017 The Kubernetes 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 controller_test import ( "log" "github.com/kubernetes-sigs/kubebuilder/pkg/controller" "github.com/kubernetes-sigs/kubebuilder/pkg/controller/types" "k8s.io/api/core/v1" ) func ExampleAddController() { podController := &controller.GenericController{ Reconcile: func(key types.ReconcileKey) error { log.Printf("Reconciling Pod %v\n", key) return nil }, } if err := podController.Watch(&v1.Pod{}); err != nil { log.Fatalf("%v", err) } controller.AddController(podController) }
package main import ( "fmt" "strconv" "strings" ) // CountTheWays is a custom type that // we'll read a flag into type CountTheWays []int func (c *CountTheWays) String() string { result := "" for _, v := range *c { if len(result) > 0 { result += " ... " } result += fmt.Sprint(v) } return result } // Set will be used by the flag package func (c *CountTheWays) Set(value string) error { values := strings.Split(value, ",") for _, v := range values { i, err := strconv.Atoi(v) if err != nil { return err } *c = append(*c, i) } return nil }
// Copyright (c) 2022 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package depgraph_test import ( "fmt" "reflect" "github.com/lf-edge/eve/libs/depgraph" ) type mockItemAttrs struct { intAttr int strAttr string boolAttr bool } type mockItem struct { name string itemType string attrs mockItemAttrs deps []depgraph.Dependency } type mockItemState struct { isCreated bool inTransition bool withErr error } func (m mockItem) Name() string { return m.name } func (m mockItem) Label() string { return m.name } func (m mockItem) Type() string { return m.itemType } func (m mockItem) Equal(m2 depgraph.Item) bool { return reflect.DeepEqual(m.attrs, m2.(mockItem).attrs) && reflect.DeepEqual(m.deps, m2.(mockItem).deps) } func (m mockItem) External() bool { return false } func (m mockItem) String() string { return fmt.Sprintf("item type:%s name:%s with attrs: %v", m.Type(), m.Name(), m.attrs) } func (m mockItem) Dependencies() []depgraph.Dependency { return m.deps } func (m mockItemState) String() string { return "" } func (m mockItemState) IsCreated() bool { return m.isCreated } func (m mockItemState) WithError() error { return m.withErr } func (m mockItemState) InTransition() bool { return m.inTransition }
package public import ( "net/http" "tpay_backend/adminapi/internal/common" _func "tpay_backend/adminapi/internal/handler/func" logic "tpay_backend/adminapi/internal/logic/public" "tpay_backend/adminapi/internal/svc" "github.com/tal-tech/go-zero/rest/httpx" ) func LogoutHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get(common.RequestHeaderLoginedToken) userId, err := _func.GetLoginedUserIdRequestHeader(r) if err != nil { httpx.Error(w, err) return } l := logic.NewLogoutLogic(r.Context(), ctx, userId) resp, err := l.Logout(token) if err != nil { httpx.Error(w, err) } else { common.OkJson(w, resp) } } }
package fraction import ( "math/big" "testing" ) func TestFraction_Reduce(t *testing.T) { f := NewFraction(big.NewInt(22), big.NewInt(33)) f.Reduce() expected := NewFraction(big.NewInt(2), big.NewInt(3)) if !f.Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(2), big.NewInt(3)) f.Reduce() expected = NewFraction(big.NewInt(2), big.NewInt(3)) if !f.Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(0), big.NewInt(3)) f.Reduce() expected = NewFraction(big.NewInt(0), big.NewInt(1)) if !f.Equals(expected) { t.FailNow() } } func TestFraction_Equals(t *testing.T) { f := NewFraction(big.NewInt(0), big.NewInt(3)) expected := NewFraction(big.NewInt(0), big.NewInt(1)) if !f.Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(2), big.NewInt(3)) expected = NewFraction(big.NewInt(4), big.NewInt(6)) if !f.Equals(expected) { t.FailNow() } } func TestFraction_Inverse(t *testing.T) { f := NewFraction(big.NewInt(2), big.NewInt(22)) expected := NewFraction(big.NewInt(22), big.NewInt(2)) if !f.Inverse().Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(0), big.NewInt(22)) if f.Inverse() != nil { t.FailNow() } } func TestFraction_GetIntegerPart(t *testing.T) { f := NewFraction(big.NewInt(2), big.NewInt(22)) expected := big.NewInt(0) if f.GetIntegerPart().Cmp(expected) != 0 { t.FailNow() } f = NewFraction(big.NewInt(23), big.NewInt(22)) expected = big.NewInt(1) if f.GetIntegerPart().Cmp(expected) != 0 { t.FailNow() } } func TestFraction_GetFractionalPart(t *testing.T) { f := NewFraction(big.NewInt(2), big.NewInt(22)) expected := NewFraction(big.NewInt(2), big.NewInt(22)) if !f.GetFractionalPart().Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(23), big.NewInt(22)) expected = NewFraction(big.NewInt(1), big.NewInt(22)) if !f.GetFractionalPart().Equals(expected) { t.FailNow() } f = NewFraction(big.NewInt(23), big.NewInt(1)) expected = NewFraction(big.NewInt(0), big.NewInt(1)) if !f.GetFractionalPart().Equals(expected) { t.FailNow() } }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-09-11 09:07 # @File : lt_147_Insertion_Sort_List.go # @Description : # @Attention : */ package v0 import ( "fmt" "testing" ) func Test_insertionSortList2(t *testing.T) { r := &ListNode{ Val: 4, Next: &ListNode{ Val: 2, Next: &ListNode{ Val: 1, Next: &ListNode{ Val: 3, Next: nil, }, }, }, } insertionSortList2(r) fmt.Println(r) }
package main import ( "fmt" "github.com/spf13/cobra" ) func serveCommand() *cobra.Command { return &cobra.Command{ Use: "serve [ config file ]", Short: "Connect to the storage and begin serving requests.", Long: ``, Example: "dex serve config.yaml", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello World"); }, } }
package main import ( "errors" "fmt" ) var errInvalidInput error = errors.New("Invalid input") type node struct { data int left, right *node } func addToTree(root *node, val int) *node { if root == nil { return &node{data: val} } if val <= root.data { root.left = addToTree(root.left, val) } else { root.right = addToTree(root.right, val) } return root } func getRightMostNode(root *node) *node { if root == nil { return nil } if root.right == nil { return root } return getRightMostNode(root.right) } func secondLargest(root *node) (int, error) { if root == nil || (root.left == nil && root.right == nil) { return 0, errInvalidInput } currNode := root for currNode != nil { if currNode.left != nil && currNode.right == nil { return getRightMostNode(currNode.left).data, nil } if currNode.right != nil && currNode.right.left == nil && currNode.right.right == nil { return currNode.data, nil } currNode = currNode.right } return -1, errInvalidInput } func buildTreeWithNums(nums []int) *node { var root *node for _, num := range nums { root = addToTree(root, num) } return root } func dumpTreeInorder(root *node) { if root == nil { return } dumpTreeInorder(root.left) fmt.Printf("%d ", root.data) dumpTreeInorder(root.right) } func checkSlicesEqual(slc1, slc2 []int) bool { if len(slc1) != len(slc2) { return false } for i := 0; i < len(slc1); i++ { if slc1[i] != slc2[i] { return false } } return true } func testBuildTree() { numss := [][]int{ []int{5, 4, 2, 1, 3}, []int{1, 3, 4, 2, 5}, []int{1, 2, 3, 4, 5}, []int{1, 2, 3, 5, 4}, } for _, nums := range numss { root1 := buildTreeWithNums(nums) dumpTreeInorder(root1) fmt.Println() } } func testSecondLargest() { numss := [][]int{ []int{5, 4, 2, 1, 3}, []int{1, 3, 4, 2, 5}, []int{1, 2, 3, 4, 5}, []int{1, 2, 3, 5, 4}, []int{5, 4, 3, 2, 1}, } for i, nums := range numss { root := buildTreeWithNums(nums) result, err := secondLargest(root) if err != nil { fmt.Printf("Error occurred: %v\n", err) continue } if result != 4 { fmt.Printf("FAILED test %d: Got %d, expected %d\n", i, result, 4) } else { fmt.Printf("PASSED test %d\n", i) } } } func main() { // testBuildTree() testSecondLargest() }
package main import ( "flag" "fmt" "io/ioutil" "net" "net/http" "os" "reflect" "strconv" "sync" "gopkg.in/yaml.v2" mtr "github.com/Shinzu/go-mtr" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" "github.com/prometheus/common/version" ) type Exporter struct { mutex sync.Mutex sent *prometheus.CounterVec received *prometheus.CounterVec dropped *prometheus.CounterVec lost *prometheus.CounterVec latency *prometheus.SummaryVec routeChanges *prometheus.CounterVec destinationChanges *prometheus.CounterVec failed *prometheus.CounterVec lastDest map[string]net.IP lastRoute map[string][]net.IP } type Config struct { Arguments []string `yaml:"args"` Hosts []Host `yaml:"hosts"` } type Host struct { Name string `yaml:"name"` Alias string `yaml:"alias"` } type TargetFeedback struct { Target string Alias string Hosts []*mtr.Host } var config Config const ( Namespace = "mtr" ) func NewExporter() *Exporter { var ( alias = "alias" server = "server" hop_id = "hop_id" hop_ip = "hop_ip" previousDest = "previous" currentDest = "current" ) return &Exporter{ sent: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "sent", Help: "packets sent", }, []string{alias, server, hop_id, hop_ip}, ), received: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "received", Help: "packets received", }, []string{alias, server, hop_id, hop_ip}, ), dropped: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "dropped", Help: "packets dropped", }, []string{alias, server, hop_id, hop_ip}, ), lost: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "lost", Help: "packets lost", }, []string{alias, server, hop_id, hop_ip}, ), latency: prometheus.NewSummaryVec( prometheus.SummaryOpts{ Namespace: Namespace, Name: "latency", Help: "packet latency in microseconds", Objectives: map[float64]float64{ 0.5: 0.05, 0.9: 0.01, 0.99: 0.001, }, MaxAge: prometheus.DefMaxAge, AgeBuckets: prometheus.DefAgeBuckets, BufCap: prometheus.DefBufCap, }, []string{alias, server, hop_id, hop_ip}, ), routeChanges: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "route_changes", Help: "route changes", }, []string{alias, server, hop_id}, ), destinationChanges: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "destination_changes", Help: "Number of times the destination IP has changed", }, []string{alias, server, previousDest, currentDest}, ), failed: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, Name: "failed", Help: "MTR runs failed", }, []string{alias, server}, ), lastDest: make(map[string]net.IP, len(config.Hosts)), lastRoute: make(map[string][]net.IP, len(config.Hosts)), } } func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { e.sent.Describe(ch) e.received.Describe(ch) e.dropped.Describe(ch) e.lost.Describe(ch) e.latency.Describe(ch) e.routeChanges.Describe(ch) e.destinationChanges.Describe(ch) e.failed.Describe(ch) } func min(a int, b int) int { if a > b { return b } return a } func (e *Exporter) collect() error { for { results := make(chan *TargetFeedback) wg := &sync.WaitGroup{} wg.Add(len(config.Hosts)) for w, host := range config.Hosts { go func(w int, host Host) { log.Infoln("worker", w, "processing job", host.Name, "aliased as", host.Alias) err := worker(w, host, results, wg) if err != nil { log.Errorf("worker %d failed job %v aliased as %v: %v\n", w, host.Name, host.Alias, err) e.failed.WithLabelValues(host.Alias, host.Name).Inc() } else { log.Infoln("worker", w, "finished job", host.Name, "aliased as", host.Alias) } }(w, host) } go func() { wg.Wait() close(results) }() for tf := range results { route := make([]net.IP, len(tf.Hosts)) destination := tf.Hosts[len(tf.Hosts)-1].IP for i, host := range tf.Hosts { route[i] = host.IP e.sent.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(host.Hop), host.IP.String()).Add(float64(host.Sent)) e.received.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(host.Hop), host.IP.String()).Add(float64(host.Received)) e.dropped.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(host.Hop), host.IP.String()).Add(float64(host.Dropped)) e.lost.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(host.Hop), host.IP.String()).Add(host.LostPercent * float64(host.Sent)) e.latency.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(host.Hop), host.IP.String()).Observe(host.Mean) } if e.lastRoute[tf.Alias] != nil { m := min(len(route), len(e.lastRoute[tf.Alias])) if len(route) != len(e.lastRoute[tf.Alias]) { e.routeChanges.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(m)).Inc() } else { // m - 1 because if the routes are the same apart from the destination, it's // just the destination that's changed, and that's recorded separately below for i := 0; i < (m - 1); i++ { if !reflect.DeepEqual(route[i], e.lastRoute[tf.Alias][i]) { e.routeChanges.WithLabelValues(tf.Alias, tf.Target, strconv.Itoa(i)).Inc() } } } } e.lastRoute[tf.Alias] = route if e.lastDest[tf.Alias] != nil && !reflect.DeepEqual(destination, e.lastDest[tf.Alias]) { e.destinationChanges.WithLabelValues(tf.Alias, tf.Target, e.lastDest[tf.Alias].String(), destination.String()).Inc() } e.lastDest[tf.Alias] = destination } } } func (e *Exporter) Collect(ch chan<- prometheus.Metric) { e.sent.Collect(ch) e.received.Collect(ch) e.dropped.Collect(ch) e.lost.Collect(ch) e.latency.Collect(ch) e.routeChanges.Collect(ch) e.destinationChanges.Collect(ch) e.failed.Collect(ch) return } func trace(host Host, results chan<- *TargetFeedback) error { // run MTR and wait for it to complete a := mtr.New(1, host.Name, config.Arguments...) <-a.Done // output result if a.Error == nil { results <- &TargetFeedback{ Target: host.Name, Alias: host.Alias, Hosts: a.Hosts, } } return a.Error } func worker(id int, host Host, results chan<- *TargetFeedback, wg *sync.WaitGroup) error { defer wg.Done() return trace(host, results) } func main() { var ( configFile = flag.String("config.file", "mtr.yaml", "MTR exporter configuration file.") listenAddress = flag.String("web.listen-address", ":9116", "The address to listen on for HTTP requests.") showVersion = flag.Bool("version", false, "Print version information.") ) flag.Parse() if *showVersion { fmt.Fprintln(os.Stdout, version.Print("mtr_exporter")) os.Exit(0) } log.Infoln("Starting mtr_exporter", version.Info()) log.Infoln("Build context", version.BuildContext()) yamlFile, err := ioutil.ReadFile(*configFile) if err != nil { log.Fatalf("Error reading config file: %s", err) } err = yaml.Unmarshal(yamlFile, &config) if err != nil { log.Fatalf("Error parsing config file: %s", err) } prometheus.MustRegister(version.NewCollector("mtr_exporter")) exporter := NewExporter() prometheus.MustRegister(exporter) go exporter.collect() http.Handle("/metrics", prometheus.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head><title>MTR Exporter</title></head> <body> <h1>MTR Exporter</h1> <p><a href="/metrics">Metrics</a></p> </body> </html>`)) }) log.Infoln("Listening on", *listenAddress) if err := http.ListenAndServe(*listenAddress, nil); err != nil { log.Fatalf("Error starting HTTP server: %s", err) } }
package models import ( "fmt" "strings" ) //Traveler 乘客信息..... type Traveler struct { PersonName string Gender string Type string IDCardType string IDCardNo string Birthday string Nationality string IDIssueCountry string IDIssueDate string IDExpireDate string OrderID string PNRID string Text string TravelerID string GivenName string SurName string Mobile string TicketNo string // Price float64 // Fax float64 RPH string Airline string CombinStatus string } func (t *Traveler) GetRPHP() string { if strings.HasPrefix(t.RPH, "P") { return t.RPH } return "P" + t.RPH } func (t *Traveler) GetDocs() string { ary := []string{ t.IDCardType, t.Nationality, t.IDCardNo, t.IDIssueCountry, t.Birthday, t.Gender, t.IDExpireDate, t.PersonName, t.GetRPHP(), } //"DOCS UA HK1 P/CN/EB8660653/CN/25JUL94/M/27MAY28/YANG/HU/P7 ssrT := strings.Join(ary, "/") all := fmt.Sprintf("DOCS %s %s1 %s", t.Airline, t.CombinStatus, ssrT) return all } func (t *Traveler) GetFOID() string { all := fmt.Sprintf("FOID %s %s1 NI%s/%s", t.Airline, t.CombinStatus, t.IDCardNo, t.GetRPHP()) return all } type ITravelerSSR interface { Check(traveler *Traveler, personname, ssr string) bool } type TravlerDocs struct { } func (d *TravlerDocs) Check(traveler *Traveler, personname, ssr string) bool { docs := traveler.GetDocs() return ssr == docs } type TravlerFOID struct { } func (f *TravlerFOID) Check(traveler *Traveler, personname, ssr string) bool { foid := traveler.GetFOID() if foid == ssr { if personname != traveler.PersonName { fmt.Printf("姓名不匹配:%s-%s\n", traveler.PersonName, personname) } } // fmt.Println(ssr) // fmt.Println(foid) // fmt.Println("***************************") return foid == ssr && personname == traveler.PersonName }
package gluster import ( //"io/ioutil" //"reflect" "fmt" //"github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" //"string" //"strings" "testing" "time" //"github.com/gluster/gogfapi/gfapi" //"github.com/docker/distribution/registry/storage/driver/testsuites" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } var glusterDriverConstructor func() (storagedriver.StorageDriver, error) func TestNew(t *testing.T) { params := &Parameters{ host: "localhost", volname: "datapoint", mountDirectory: "/mnt/gluster", } fmt.Printf("Test stotageDriver !\n") glusterDriverConstructor = func() (storagedriver.StorageDriver, error) { return New(*params) } d, err := glusterDriverConstructor() if err != nil { fmt.Printf("%v\n", err) } fmt.Println(d.Name()) //Test writer() fmt.Printf("\nTest Writer !\n") f, err4 := d.Writer(nil, "/tests/hello.txt", false) if err4 != nil { fmt.Printf("%v\n", err4) //os.Exit(0) } var tmp string = "2017-04-21T14:16:45Z" cont := []byte(tmp) n, err := f.Write(cont) if err != nil { fmt.Println(err) } fmt.Printf("%d bytes writen to p from filewriter!\n", n) f.Commit() //f.Cancel() f.Close() time.Sleep(10 * time.Millisecond) //Test reader() // fmt.Printf("\nTest Reader !\n") // file, err1 := d.Reader(nil, "/tests/data", 0) // if err1 != nil { // fmt.Printf("%v\n", err1) // } // var p0 [10000]byte // p := p0[:] // n, err2 := file.Read(p) // if err2 != nil { // fmt.Printf("%v\n", err2) // } // //tmp1 := byteToString(p) // //fmt.Println(strings.EqualFold(tmp1, tmp)) // //times, err := time.Parse(time.RFC3339, tmp1) // if err != nil { // fmt.Println(err) // } // //fmt.Printf("Time is %v\n", times) // fmt.Printf("%d bytes read! !%s!\n", n, string(p)) // file.Close() //io.ReadCloser only has two methods ,that is Read() and Close() //Test GetContent() 该方法里面的ioutil.ReadAll(rc)执行后不返回值,有待解决 fmt.Printf("\nTest GetContent !\n") contents, err := d.GetContent(nil, "/tests/data") if err != nil { fmt.Println(err) } //times, err := time.Parse(time.RFC3339, string(contents)) // if err != nil { // fmt.Println(err) // } fmt.Printf("Get contents: %s\n", string(contents)) //fmt.Printf("Time is %v\n", times) //Test PutContent() // fmt.Printf("\nTest PutContent !\n") // con := "test putcontent" // if err = d.PutContent(nil, "/job.txt", []byte(con)); err != nil { // fmt.Println(err) // } //Test Stat() // fmt.Printf("\nTest Stat !\n") // state, err3 := d.Stat(nil, "/job.txt") // if err3 != nil { // fmt.Printf("%v\n", err3) // } // fmt.Printf("%v\n", state.ModTime()) // //Test List() // fmt.Printf("\nTest List !\n") // lists, err := d.List(nil, "/") // fmt.Println(lists) //Test Move() // fmt.Printf("\nTest Move !\n") // err = d.Move(nil, "/tests/hello.txt", "/htf/hello.txt") // if err != nil { // fmt.Println(err) // } //Test Delete() // fmt.Printf("\nTest Delete !\n") // err = d.Delete(nil, "/test.go") // if err != nil { // fmt.Println(err) // } } func byteToString(p []byte) string { for i := 0; i < len(p); i++ { if p[i] == 0 { return string(p[0:i]) } } return string(p) }
package cntest import ( "bufio" "context" "database/sql" "errors" "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "io" "net" "os" "path/filepath" "regexp" "strings" "time" "github.com/cybernostics/cntest/random" "github.com/cybernostics/cntest/wait" ) var api *client.Client // TCPConnectFn override this to provide a tcp connect function type TCPConnectFn = func(timeoutSeconds int) (net.Conn, error) // DBConnectFn override this to provide a DB connect function type DBConnectFn = func(timeoutSeconds int) (*sql.DB, error) // ContainerReadyFn should return true when the container is ready to be used type ContainerReadyFn func() (bool, error) // HostPort typesafe string subtype type HostPort string // ContainerPort typesafe string subtype type ContainerPort string // HostPath typesafe string subtype type HostPath string // ContainerPath typesafe string subtype type ContainerPath string // NOPORT constant for no port specified const NOPORT = HostPort("") // PortMap defines a host to container port mapping type PortMap struct { Host HostPort Container ContainerPort } // AddTo adds this mapping to a docker Portmap map func (p PortMap) AddTo(portmap nat.PortMap) { portmap[p.Container.Nat()] = []nat.PortBinding{p.Host.Binding()} } // Nat does the string formatting for a nat port func (p ContainerPort) Nat() nat.Port { theNat, err := nat.NewPort("tcp", string(p)) if err != nil { panic(err) } return theNat } // Binding Returns a host binding and optionally creates a random one if none provided func (p HostPort) Binding() nat.PortBinding { port := p if port == NOPORT { listener, err := net.Listen("tcp", ":0") defer listener.Close() if err != nil { panic(err) } port = HostPort(fmt.Sprintf("%d", listener.Addr().(*net.TCPAddr).Port)) } return nat.PortBinding{ HostIP: "0.0.0.0", HostPort: string(port), } } // VolumeMount creates a Volume mount from host to container type VolumeMount struct { Host HostPath Container ContainerPath } // Mount is a converter to a docker api mount struct func (v *VolumeMount) Mount() mount.Mount { absMount, _ := filepath.Abs(string(v.Host)) return mount.Mount{ Source: absMount, Target: string(v.Container), Type: mount.TypeBind, } } // ImageRefFn This function type provides a hook to generate a custom docker repo path if needed // You only need this if you're not using the standard docker registry type ImageRefFn func(image string, version string) string // API returns current API client or creates on first call func API() *client.Client { version := os.Getenv("DOCKER_API_VERSION") if len(version) == 0 { os.Setenv("DOCKER_API_VERSION", "1.42") } if api != nil { return api } api, err := client.NewEnvClient() if err != nil { fmt.Println("Unable to create docker client") panic(err) } return api } // PropertyMap Custom container properties used to configure containers // They are stored here for later reference eg by tests // eg They could include db username/password for a db type container type PropertyMap map[string]string // Container a simplified API over the docker client API type Container struct { // Props are metadata for a container type. eg dbusername for a db container // They are not passed directly to the container environment Props PropertyMap // This is the main app port for the container containerPort ContainerPort // These two are used to create the new container using the Docker API Config *container.Config HostConfig *container.HostConfig // Instance Once the container is started this has all the instance data Instance container.CreateResponse // GetImageRepoSource Overload this if you want to get images from a different repo GetImageRepoSource ImageRefFn `json:"-,"` // will stop and remove the container after testing StopAfterTest bool // RemoveAfterTest remove the container after the test RemoveAfterTest bool // The docker image to use for the container dockerImage string // The Maximum time to wait for the container MaxStartTimeSeconds int // The name of the running container name string // NamePrefix is combined with a random suffix to create the containerName // if the name is blank when the container is started NamePrefix string // The environment environment map[string]string // The IP address of the container iP string // ContainerReady Override this if you want to check more than an ok response to a TCP connect ContainerReady ContainerReadyFn `json:"-,"` // TCPConnect fn to connect to a TCP connection TCPConnect TCPConnectFn `json:"-,"` // DBConnect fn to connect to a DB connection DBConnect DBConnectFn `json:"-,"` } // SetIfMissing sets the value if it isn't already func (p PropertyMap) SetIfMissing(key string, value string) { if val, ok := p[key]; !ok { p[key] = val } } // GetOrDefault returns the specified key value or a default func (p PropertyMap) GetOrDefault(key string, defaultValue string) string { if val, ok := p[key]; ok { return val } return defaultValue } // SetAll sets all the props on the provided map func (p PropertyMap) SetAll(amap PropertyMap) { for key, val := range amap { p[key] = val } } // FromDockerHub is the default formatter for a docker image resource // provide your own for private repos func FromDockerHub(image string, version string) string { if version == "" { version = "latest" } return fmt.Sprintf("%s:%s", image, version) } // ContainerConfigFn custom function that configures a container type ContainerConfigFn func(c *Container) error // NewContainer constructor fn func NewContainer() *Container { cnt := Container{ Props: PropertyMap{}, Config: &container.Config{Tty: true}, HostConfig: &container.HostConfig{}, GetImageRepoSource: FromDockerHub, MaxStartTimeSeconds: 30, StopAfterTest: true, RemoveAfterTest: true, } cnt.ContainerReady = cnt.IsRunning return &cnt } // ContainerWith contstructor which takes a custom configurer func ContainerWith(fn ContainerConfigFn) *Container { cnt := NewContainer() fn(cnt) return cnt } // PullImage like docker pull cmd func PullImage(image string, version string, getRepoFn ImageRefFn) { images, err := API().ImageList(context.Background(), types.ImageListOptions{}) toFind := fmt.Sprintf("%s:%s", image, version) for _, image := range images { for _, tags := range image.RepoTags { if tags == toFind { fmt.Printf("Found %s in local store - skipping pull\n", toFind) return } } } reader, err := API().ImagePull(context.Background(), getRepoFn(image, version), types.ImagePullOptions{}) if err != nil { panic(err) } io.Copy(os.Stdout, reader) } // HostPort get the host port func (c *Container) HostPort() string { var binding = c.HostConfig.PortBindings[c.containerPort.Nat()] return binding[0].HostPort } // SetName container name func (c *Container) SetName(name string) { c.name = name } // SetAppPort sets the main port for the container if it has one func (c *Container) SetAppPort(port string) *Container { return c.SetPort(port, "") } // SetPort sets the main port to be used by the container // Other port mappings can be added but this one is considered the big kahuna // for checking readiness for example func (c *Container) SetPort(port string, mappedHostPort string) *Container { c.containerPort = ContainerPort(port) if len(mappedHostPort) == 0 { c.MapToRandomHostPort(c.containerPort) } else { c.AddPortMap(HostPort(mappedHostPort), c.containerPort) } return c } // MapToRandomHostPort like --ports cmd switch for mapping ports func (c *Container) MapToRandomHostPort(containerPort ContainerPort) { c.addPortBinding(PortMap{Container: containerPort, Host: NOPORT}) c.AddExposedPort(containerPort) } // AddPathMap like -v cmd switch for mapping paths func (c *Container) AddPathMap(Host HostPath, Container ContainerPath) { pathMap := VolumeMount{Host, Container} if c.HostConfig.Mounts == nil { c.HostConfig.Mounts = make([]mount.Mount, 0) } c.HostConfig.Mounts = append(c.HostConfig.Mounts, pathMap.Mount()) } // AddPortMap like -p cmd line switch for adding port mappings func (c *Container) AddPortMap(host HostPort, container ContainerPort) { c.addPortBinding(PortMap{host, container}) } func (c *Container) addPortBinding(portMap PortMap) { if c.HostConfig.PortBindings == nil { c.HostConfig.PortBindings = make(nat.PortMap) } portMap.AddTo(c.HostConfig.PortBindings) } // AddExposedPort expose a container port func (c *Container) AddExposedPort(port ContainerPort) { if c.Config.ExposedPorts == nil { c.Config.ExposedPorts = make(nat.PortSet) } c.Config.ExposedPorts[port.Nat()] = struct{}{} } // AddAllEnv adds the mapped values to the config func (c *Container) AddAllEnv(aMap map[string]string) { for key, val := range aMap { c.AddEnv(key, val) } } // AddEnv adds the value to the config func (c *Container) AddEnv(key, value string) { c.Config.Env = append(c.Config.Env, fmt.Sprintf("%s=%s", key, value)) } // Start starts the container func (c *Container) Start() (string, error) { c.name = c.ContainerName() instance, err := API().ContainerCreate( context.Background(), c.Config, c.HostConfig, nil, nil, c.name) if err != nil { return "", err } c.Instance = instance err = API().ContainerStart(context.Background(), c.Instance.ID, types.ContainerStartOptions{}) if err != nil { return "", err } c.iP, err = c.InspectIPAddress() if err != nil { return "", err } fmt.Printf("Container %s is starting\n", c.Instance.ID) if len(c.Instance.Warnings) > 0 { for _, warning := range c.Instance.Warnings { fmt.Println(warning) } } return c.Instance.ID, nil } // ContainerName returns the generated name for the container func (c *Container) ContainerName() string { if len(c.name) == 0 { c.name = c.NamePrefix + "-" + random.Name() } return c.name } // LogsMatch returns a fn matcher for bool wait fns func (c *Container) LogsMatch(pattern string) func() (bool, error) { var logPattern = regexp.MustCompile(pattern) return func() (bool, error) { logsOptions := types.ContainerLogsOptions{ Details: true, ShowStderr: true, ShowStdout: true, } if logsReader, err := API().ContainerLogs(context.Background(), c.Instance.ID, logsOptions); err == nil { bufferedLogs := bufio.NewReader(logsReader) defer logsReader.Close() for { line, error := bufferedLogs.ReadString('\n') if error == io.EOF { break } else if error != nil { return false, nil } if logPattern.FindString(line) != "" { return true, nil } } } return false, nil } } // Logs returns the container logs as a string or error func (c *Container) Logs() (string, error) { logsOptions := types.ContainerLogsOptions{ Details: true, ShowStderr: true, ShowStdout: true, Tail: "all", } logsReader, err := API().ContainerLogs(context.Background(), c.Instance.ID, logsOptions) if err != nil { return "", err } defer logsReader.Close() buf := new(strings.Builder) _, err = io.Copy(buf, logsReader) // check errors return buf.String(), err } // AwaitLogPattern waits for the container to start based on expected log message patterns func (c *Container) AwaitLogPattern(timeoutSeconds int, patternRegex string) (started bool, err error) { return wait.UntilTrue(timeoutSeconds, c.LogsMatch(patternRegex)) } // AwaitIsRunning waits for the container is in the running state func (c *Container) AwaitIsRunning() (started bool, err error) { return wait.UntilTrue(c.MaxStartTimeSeconds, c.IsRunning) } // AwaitIsReady waits for the container is in the running state func (c *Container) AwaitIsReady() (started bool, err error) { return wait.UntilTrue(c.MaxStartTimeSeconds, c.ContainerReady) } // IPAddress retrieve the IP address of the running container func (c *Container) IPAddress() (string, error) { if len(c.iP) != 0 { return c.iP, nil } ip, err := c.InspectIPAddress() if err != nil { return "", err } c.iP = ip return c.iP, nil } // InspectIPAddress uses docker inspect to find out the ip address func (c *Container) InspectIPAddress() (string, error) { inspect, err := API().ContainerInspect(context.Background(), c.Instance.ID) if err != nil { return "", err } return inspect.NetworkSettings.IPAddress, nil } // Port returns the containers port func (c *Container) Port() ContainerPort { return c.containerPort } // ConnectTCP Connects tot he container port using a TCP connection func (c *Container) ConnectTCP(timeoutSeconds int) (net.Conn, error) { var port string for key := range c.Config.ExposedPorts { port = key.Port() } ip, err := c.IPAddress() if err != nil { return nil, err } host := fmt.Sprintf("%s:%s", ip, port) var timeout time.Duration if timeoutSeconds == 0 { timeout = time.Duration(10) * time.Minute } else { timeout = time.Duration(timeoutSeconds) * time.Minute } for { var conn net.Conn conn, err = net.DialTimeout("tcp", host, timeout) if err != nil { return nil, err } return conn, nil } } // Check if tcp port is open func (c *Container) Check(timeoutSeconds int) (ret bool, err error) { conn, err := c.ConnectTCP(timeoutSeconds) if err != nil { return false, nil } defer func() { conn.Close() }() return true, nil } // Stop stops the container func (c *Container) Stop(timeoutSeconds int) (ok bool, err error) { timeout := 30 err = API().ContainerStop(context.Background(), c.Instance.ID, container.StopOptions{ Signal: "SIGKILL", Timeout: &timeout, }) if err != nil { return } if timeoutSeconds > 0 { return c.AwaitExit(timeoutSeconds) } return true, nil } // AwaitExit waits for the container to stop func (c *Container) AwaitExit(timeoutSeconds int) (ok bool, err error) { return wait.UntilTrue(timeoutSeconds, c.IsExited) } // RunCmd execs the specified command and args on the container func (c *Container) RunCmd(cmd []string) (io.Reader, error) { cmdConfig := types.ExecConfig{AttachStdout: true, AttachStderr: true, Cmd: cmd, } ctx := context.Background() execID, _ := API().ContainerExecCreate(ctx, c.Instance.ID, cmdConfig) fmt.Println(execID) res, err := API().ContainerExecAttach(ctx, execID.ID, types.ExecStartCheck{}) if err != nil { return nil, err } err = API().ContainerExecStart(ctx, execID.ID, types.ExecStartCheck{}) if err != nil { return nil, err } return res.Reader, nil } // Remove deletes the container permanently func (c *Container) Remove() error { return API().ContainerRemove(context.Background(), c.Instance.ID, types.ContainerRemoveOptions{Force: true}) } // IsRemoveAfterTest true if the container should be removed func (c *Container) IsRemoveAfterTest() bool { return c.RemoveAfterTest } // IsRunning returns true if the container is in the started state // Will error if the container has already exited func (c *Container) IsRunning() (started bool, err error) { inspect, err := API().ContainerInspect(context.Background(), c.Instance.ID) status := inspect.State.Status if err != nil { return false, err } if status == "running" { return true, nil } if status == "exited" { return false, errors.New("Container Already exited") } fmt.Printf("Status is %s\n", status) return false, nil } // IsExited returns true if the container has exited func (c *Container) IsExited() (started bool, err error) { inspect, err := API().ContainerInspect(context.Background(), c.Instance.ID) if err != nil { return false, err } if inspect.State.Status == "exited" { return true, nil } return false, nil } // WithImage sets the image name and the default container name prefix func (c *Container) WithImage(image string) *Container { c.Config.Image = image parts := strings.Split(image, ":") c.NamePrefix = parts[0] return c } // IsStopAfterTest if true then stop the container after the test func (c *Container) IsStopAfterTest() bool { return c.StopAfterTest }
package main import ( "fmt" "strings" ) //解析反向json var ss =map[string]interface{}{"1": "bar", "2": "foo.bar", "3": "foo.foo", "4": "baz.cloudmall.com", "5": "baz.cloudmall.ai"} func main(){ var result = []map[string]interface{}{} for key,item:= range ss{ result = append(result,techlist(item.(string),key)) } var res map[string]interface{} for _,item:=range result{ res=allmap(res,item) } fmt.Println(res) } func techlist(str,value string)map[string]interface{}{ kv := reverse(strings.Split(str, ".")) var tmp = map[string]interface{}{} for key,item:=range kv{ var newtmp = map[string]interface{}{} if key==0{ tmp[item] = value }else{ newtmp[item] = tmp tmp = newtmp } } return tmp } func reverse(s []string) []string { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } return s } func allmap(m1,m2 map[string]interface{})map[string]interface{}{ if m1==nil{ return m2 } var flag = false for k,v :=range m1{ if m2[k]!=nil{ v1,flag1:=v.(map[string]interface{}) v2,flag2:=m2[k].(map[string]interface{}) if flag1 &&flag2{ flag =true m1[k] = allmap(v1,v2) } } } if flag==false{ for k,v :=range m2{ m1[k] = v return m1 } } return m1 }
package main import ( "context" "log" "net" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/reflection" pb "github.com/robinjmurphy/go-grpc-example/server/proto" ) const ( port = ":50051" ) type server struct{} func (s *server) Multiply(ctx context.Context, req *pb.Request) (*pb.Response, error) { if len(req.Input) < 2 { err := grpc.Errorf( codes.InvalidArgument, "at least two numbers must be specified", ) return &pb.Response{}, err } var res int32 = 1 for _, i := range req.Input { res = res * i } return &pb.Response{Result: res}, nil } func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterCalculatorServer(s, &server{}) reflection.Register(s) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
/* Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Solution() Initializes the object of the system. String encode(String longUrl) Returns a tiny URL for the given longUrl. String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object. Example 1: Input: url = "https://leetcode.com/problems/design-tinyurl" Output: "https://leetcode.com/problems/design-tinyurl" Explanation: Solution obj = new Solution(); string tiny = obj.encode(url); // returns the encoded tiny url. string ans = obj.decode(tiny); // returns the original url after deconding it. Constraints: 1 <= url.length <= 10^4 url is guranteed to be a valid URL. */ package main import ( "bytes" "fmt" "math/rand" ) func main() { test([]string{ "https://leetcode.com/problems/design-tinyurl", "https://java.com/ide/splx", "https://google.com/tinyurl/ixhe12", "linenoise.bridge.io", }) } func assert(x bool) { if !x { panic("assertion failed") } } func test(longurls []string) { t := NewTiny() for _, longurl := range longurls { shorturl := t.Encode(longurl) xlongurl := t.Decode(shorturl) fmt.Printf("%q | %q\n", shorturl, xlongurl) assert(xlongurl == longurl) } } type Tiny struct { code map[string]string link map[string]string rng *rand.Rand } func NewTiny() *Tiny { return &Tiny{ code: make(map[string]string), link: make(map[string]string), rng: rand.New(rand.NewSource(1)), } } func (t *Tiny) Encode(longurl string) string { if link := t.link[longurl]; link != "" { return link } var code string for tries := 0; tries < 1e9; tries++ { xcode := t.gencode() if _, exist := t.code[xcode]; !exist { code = xcode break } } t.code[code] = longurl t.link[longurl] = code return code } func (t *Tiny) Decode(shorturl string) string { return t.code[shorturl] } func (t *Tiny) gencode() string { const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" w := new(bytes.Buffer) w.WriteString("http://tinyurl.com/") for i := 0; i < 6; i++ { n := t.rng.Intn(len(chars)) w.WriteByte(chars[n]) } return w.String() }
package main import ( "fmt" ) func main() { // ======== Assignments ======== // type goes after the variable // int, float32, float64 var x float64 // x := 1.0 var y float64 // y := 2.0 // x, y := 1.0, 2.0 // assign values x = 1 y = 2 // template print: %v = go obj, %T = type fmt.Printf("x=%v, type of %T\n", x, x) fmt.Printf("y=%v, type of %T\n", y, y) var mean float64 mean = (x + y) / 2.0 fmt.Printf("result: %v, type of %T\n", mean, mean) // ========= Conditionals ======== z := 10 // no parenthesis on statement() if z > 5 { fmt.Println("z is big") } else { fmt.Println("z is small") } // &&, ||, same as c, c++, java, etc a := 11.0 b := 20.0 // single line assignment if frac := a / b; frac > 0.5 { fmt.Println("a is more than half of b") } // Switch case, no use of break after each a 'case' // kind of like an invisible break statement after each case two := 101 switch two { case 1: fmt.Println("one") case 2: fmt.Println("two") default: fmt.Println("many") } // switch without expression switch { case two > 100: fmt.Println("very big") case two > 10: fmt.Println("big") default: fmt.Println("default") } // ========== Loops ========== // break and continue works as always for i := 0; i < 3; i++ { fmt.Println(i) } // while loop: a for with just the condition j := 0 for j < 3 { fmt.Println(j) j++ } // while true for { fmt.Println(j) break } }
package stt import ( "bytes" "fmt" "github.com/open-horizon/examples/cloud/sdr/data-processing/wutil" ) // TranscribeResponse is the top level struct which Watson speech to text gives us. type TranscribeResponse struct { Results []Result `json:"results"` Index int `json:"results_index"` } // Result is just a list of Alternatives with a final bool. For non streaming, we can probaly ignore Final. type Result struct { Alternatives []Alternative `json:"alternatives"` Final bool `json:"final"` } // Alternative holds the actual text along with a Confidence type Alternative struct { Confidence float32 `json:"confidence"` Transcript string `json:"transcript"` } // Transcribe a chunk of audio func Transcribe(audioBytes []byte, contentType string, username, password string) (response TranscribeResponse, err error) { fmt.Println("using Watson STT to convert the audio to text...") // Watson STT API: https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/curl.html?curl#recognize-sessionless apiURL := "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" headers := []wutil.Header{{Key: "Content-Type", Value: contentType}} err = wutil.HTTPPost(apiURL, username, password, headers, bytes.NewReader(audioBytes), &response) return }
package vars import ( "fmt" "net/url" "strconv" "github.com/spf13/cobra" "github.com/makkes/gitlab-cli/api" ) func NewCommand(client api.Client, project *string) *cobra.Command { return &cobra.Command{ Use: "var KEY VALUE [ENVIRONMENT_SCOPE]", Short: "Create a project-level variable", Long: "Create a project-level variable. The KEY may only contain the characters A-Z, a-z, 0-9, and _ and " + "must be no longer than 255 characters.", Args: cobra.RangeArgs(2, 3), RunE: func(cmd *cobra.Command, args []string) error { if project == nil || *project == "" { return fmt.Errorf("please provide a project scope") } project, err := client.FindProject(*project) if err != nil { return fmt.Errorf("cannot create variable: %s", err) } body := map[string]interface{}{ "key": url.QueryEscape(args[0]), "value": url.QueryEscape(args[1]), } if len(args) == 3 { body["environment_scope"] = url.QueryEscape(args[2]) } _, _, err = client.Post("/projects/"+strconv.Itoa(project.ID)+"/variables", body) if err != nil { return fmt.Errorf("cannot create variable: %s", err) } return nil }, } }
package models type Course struct { Name string `json:"name" gorm:"size:255"` Semester uint `json:"semester"` Lect_hour uint `json:"lect_hour"` Lab_hour uint `json:"lab_hour"` Credits uint `json:"credits"` DeptID uint `json:"dept_id"` Dept Department `gorm:"constraint:OnDelete:CASCADE"` }
package handler import ( "context" "errors" "testing" "github.com/stretchr/testify/require" "github.com/dkorittki/loago/internal/pkg/worker/service/loadtest" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "github.com/stretchr/testify/assert" "github.com/dkorittki/loago/pkg/api/v1" "github.com/stretchr/testify/mock" "google.golang.org/grpc/metadata" ) type RunServerMock struct { results []*api.EndpointResult mock.Mock } func (r *RunServerMock) Send(e *api.EndpointResult) error { r.results = append(r.results, e) args := r.Called(e) return args.Error(0) } func (r *RunServerMock) SetHeader(m metadata.MD) error { args := r.Called(m) return args.Error(0) } func (r *RunServerMock) SendHeader(m metadata.MD) error { args := r.Called(m) return args.Error(0) } func (r *RunServerMock) SetTrailer(m metadata.MD) { r.Called(m) } func (r *RunServerMock) Context() context.Context { args := r.Called() return args.Get(0).(context.Context) } func (r *RunServerMock) SendMsg(m interface{}) error { args := r.Called(m) return args.Error(0) } func (r *RunServerMock) RecvMsg(m interface{}) error { args := r.Called(m) return args.Error(0) } func TestNewWorker(t *testing.T) { w1 := &Worker{} w2 := NewWorker() assert.Equal(t, w1, w2) } func TestWorker_Run(t *testing.T) { srv := &RunServerMock{} srv.On("Send", mock.Anything).Return(nil).Once() srv.On("Send", mock.Anything).Return(nil).Once() srv.On("Send", mock.Anything).Return(status.Error(codes.Unavailable, "channel closed")) req := &api.RunRequest{ Endpoints: []*api.RunRequest_Endpoint{ { Url: "http://foo.bar", Weight: 1, }, }, Amount: 1, Type: api.RunRequest_FAKE, MinWaitTime: 1000, MaxWaitTime: 1000, } h := NewWorker() errChan := make(chan error) go func() { errChan <- h.Run(req, srv) }() err := <-errChan srv.AssertExpectations(t) assert.Equal(t, status.Error(codes.Unavailable, "channel closed"), err) assert.Len(t, srv.results, 3) for _, v := range srv.results { assert.Equal(t, int32(50), v.Ttfb) assert.Equal(t, int32(200), v.HttpStatusCode) assert.Equal(t, "OK", v.HttpStatusMessage) assert.False(t, v.Cached) assert.Equal(t, req.Endpoints[0].Url, v.Url) } } func TestServiceErrorHandling(t *testing.T) { srv := &RunServerMock{} req := &api.RunRequest{ Endpoints: []*api.RunRequest_Endpoint{ { Url: "http://foo.bar", Weight: 1, }, }, Amount: 1, Type: api.RunRequest_FAKE, MinWaitTime: 2000, MaxWaitTime: 1000, } h := NewWorker() errChan := make(chan error) go func() { errChan <- h.Run(req, srv) }() err := <-errChan assert.Equal(t, status.Error(codes.Aborted, loadtest.ErrInvalidWaitBoundaries.Error()), err) assert.Len(t, srv.results, 0) } func TestInvalidBrowserType(t *testing.T) { srv := &RunServerMock{} req := &api.RunRequest{ Endpoints: []*api.RunRequest_Endpoint{ { Url: "http://foo.bar", Weight: 1, }, }, Amount: 1, Type: 2, MinWaitTime: 2000, MaxWaitTime: 1000, } h := NewWorker() errChan := make(chan error) go func() { errChan <- h.Run(req, srv) }() err := <-errChan assert.Len(t, srv.results, 0) if assert.Error(t, err) { grpcErr, ok := status.FromError(err) require.True(t, ok) assert.Equal(t, codes.InvalidArgument, grpcErr.Code()) assert.Contains(t, grpcErr.Message(), "unknown browser type") } } func TestUnkownErrorOnSend(t *testing.T) { srv := &RunServerMock{} srv.On("Send", mock.Anything).Return(errors.New("testing error")) req := &api.RunRequest{ Endpoints: []*api.RunRequest_Endpoint{ { Url: "http://foo.bar", Weight: 1, }, }, Amount: 1, Type: api.RunRequest_FAKE, MinWaitTime: 1000, MaxWaitTime: 1000, } h := NewWorker() errChan := make(chan error) go func() { errChan <- h.Run(req, srv) }() err := <-errChan assert.Len(t, srv.results, 1) if assert.Error(t, err) { grpcErr, ok := status.FromError(err) require.True(t, ok) assert.Equal(t, codes.Unknown, grpcErr.Code()) assert.Contains(t, grpcErr.Message(), "no grpc error") } } func TestGRPCErrorOnSend(t *testing.T) { sendErr := status.Error(codes.Internal, "testing error") srv := &RunServerMock{} srv.On("Send", mock.Anything).Return(sendErr) req := &api.RunRequest{ Endpoints: []*api.RunRequest_Endpoint{ { Url: "http://foo.bar", Weight: 1, }, }, Amount: 1, Type: api.RunRequest_FAKE, MinWaitTime: 1000, MaxWaitTime: 1000, } h := NewWorker() errChan := make(chan error) go func() { errChan <- h.Run(req, srv) }() err := <-errChan assert.Len(t, srv.results, 1) assert.Equal(t, sendErr, err) }
package main import ( "bytes" "crypto" "crypto/rand" "crypto/rsa" "fmt" "github.com/go-piv/piv-go/piv" "github.com/tcastelly/try-piv-go/lib" ) // https://github.com/go-piv/piv-go/blob/master/piv/key_test.go#L335 // https://github.com/keybase/go-crypto/blob/master/openpgp/write.go#L204-L209 // https://github.com/keybase/go-crypto/issues/72 func main() { pin, err := lib.AskPin() if err != nil { fmt.Println(err) return } yk, close, err := lib.GetYubikey() if err != nil { fmt.Println(err) return } defer close() cert, err := yk.Certificate(piv.SlotAuthentication) if err != nil { fmt.Println(err) return } rsaPub, ok := cert.PublicKey.(*rsa.PublicKey) if !ok { fmt.Printf("no public rsa") return } data := []byte("hello") ct, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPub, data) if err != nil { fmt.Printf("encryption failed: %v\n", err) return } priv, err := yk.PrivateKey(piv.SlotAuthentication, rsaPub, piv.KeyAuth{ PIN: pin, PINPolicy: piv.PINPolicyOnce, }) if err != nil { fmt.Printf("getting private key: %v", err) return } d, ok := priv.(crypto.Decrypter) if !ok { fmt.Printf("private key didn't implement crypto.Decypter") return } got, err := d.Decrypt(rand.Reader, ct, nil) if err != nil { fmt.Printf("decryption failed: %v", err) return } if !bytes.Equal(data, got) { fmt.Printf("decrypt, got=%q, want=%q\n", got, data) return } fmt.Println("done with success") }