text
stringlengths
11
4.05M
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02800101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.028.001.01 Document"` Message *AgentCADeactivationInstructionV01 `xml:"AgtCADeactvtnInstr"` } func (d *Document02800101) AddMessage() *AgentCADeactivationInstructionV01 { d.Message = new(AgentCADeactivationInstructionV01) return d.Message } // Scope // This message is sent by an issuer (or its agent) to the CSD to instruct the deactivation of a corporate action event or to deactivate one or more specific options of the corporate action. As of the deactivation date, the CSD is allowed to reject any related election instruction received from clients. // Usage // Deactivation refers only to the empowerment of the CSD to reject further elections. To withdraw an event, the Agent Corporate Action Notification Advice message must be used. // This message can be used to deactivate all the options of a corporate action event, in which case, no option should be mentioned in the message. // This message can also be used to deactivate one or more specific corporate action options, in which case, the option type and option number must be present. // This message can only be used when the deactivation date is after the market deadline. Before the market deadline, an updated notification advice message must be sent with option availability status: inactive or cancelled. // An un-effected deactivation (pending deactivation date/time) can be cancelled with an Agent Corporate Action Deactivation Cancellation Request. // The amendment of a deactivation is effected by cancel/replace mechanism. type AgentCADeactivationInstructionV01 struct { // Identification assigned by the Sender to unambiguously identify the instruction. Identification *iso20022.DocumentIdentification8 `xml:"Id"` // General information about the corporate action event. CorporateActionGeneralInformation *iso20022.CorporateActionInformation1 `xml:"CorpActnGnlInf"` // Information related to the deactivation of a CA event. DeactivationDetails *iso20022.CorporateActionDeactivationInstruction1 `xml:"DeactvtnDtls"` } func (a *AgentCADeactivationInstructionV01) AddIdentification() *iso20022.DocumentIdentification8 { a.Identification = new(iso20022.DocumentIdentification8) return a.Identification } func (a *AgentCADeactivationInstructionV01) AddCorporateActionGeneralInformation() *iso20022.CorporateActionInformation1 { a.CorporateActionGeneralInformation = new(iso20022.CorporateActionInformation1) return a.CorporateActionGeneralInformation } func (a *AgentCADeactivationInstructionV01) AddDeactivationDetails() *iso20022.CorporateActionDeactivationInstruction1 { a.DeactivationDetails = new(iso20022.CorporateActionDeactivationInstruction1) return a.DeactivationDetails }
package ztimer import ( "log" "math" "sync" "time" ) //时间轮调度器 //依赖模块 delayfunc.go timer.go timewheel.go const ( //默认缓冲触发的队列大小 MAX_CHAN_BUF = 2048 //默认最大误差时间 MAX_TIME_DELAY = 100 ) type TimerScheduler struct { //当前调度器的最高优先级 tw *TimeWheel //定时器编号累加器 idGen uint32 //已经触发定时器channel triggerChan chan *DelayFunc //互斥锁 sync.RWMutex } //返回一个定时调度器 主要创建分层定时器 并做关联 依次启动 func NewTimerScheduler() *TimerScheduler { //创建秒数时间轮 secondTw := NewTimeWheel(SECOND_NAME, SECOND_INTERVAL, SECOND_SCALES, TIMERS_MAX_CAP) minuteTw := NewTimeWheel(MINUTE_NAME, MINUTE_INTERVAL, MINUTE_SCALES, TIMERS_MAX_CAP) hourTw := NewTimeWheel(HOUR_NAME, HOUR_INTERVAL, HOUR_SCALES, TIMERS_MAX_CAP) //将分层时间做关联 hourTw.AddTimeWheel(minuteTw) minuteTw.AddTimeWheel(secondTw) //时间轮运行 secondTw.Run() minuteTw.Run() hourTw.Run() log.Println("timerscheduler NewTimerScheduler are run") return &TimerScheduler{ tw: hourTw, triggerChan: make(chan *DelayFunc, MAX_CHAN_BUF), } } //创建一个定点timer 并将timer添加到分层时间轮中 返回 timer中的tid func (ts *TimerScheduler) CreateTimerAt(df *DelayFunc, unixNano int64) (uint32, error) { ts.Lock() defer ts.Unlock() ts.idGen++ return ts.idGen, ts.tw.AddTimer(ts.idGen, NewTimerAt(df, unixNano)) } //创建一个定时器,并将timer添加到分层时间轮中,返回timer的tid func (ts *TimerScheduler) CreateTimerAfter(df *DelayFunc, duration time.Duration) (uint32, error) { ts.Lock() defer ts.Unlock() ts.idGen++ return ts.idGen, ts.tw.AddTimer(ts.idGen, NewTimerAfter(df, duration)) } //删除timer func (ts *TimerScheduler) CancelTimer(tid uint32) { ts.Lock() ts.Unlock() ts.tw.RemoveTimer(tid) } //获取时间结束的延迟执行函数 func (ts *TimerScheduler) GetTriggerChan() chan *DelayFunc { return ts.triggerChan } //非阻塞方式启动timerscheduler func (ts *TimerScheduler) Start() { go func() { for { //当前时间 now := UinxMilli() //获取最近的定时器集合 timerList := ts.tw.GetTimerWithIn(MAX_TIME_DELAY * time.Millisecond) for _, timer := range timerList { if math.Abs(float64(now-timer.unixts)) > MAX_TIME_DELAY { //已经超时,报警处理 log.Println("timerscheduler start call at ", timer.unixts, " real call at ", now, " delay ", now-timer.unixts) } ts.triggerChan <- timer.delayFunc } time.Sleep(MAX_TIME_DELAY / 2 * time.Millisecond) } }() } //时间轮定时器 自动调度 func NewAutoExecTimerScheduler() *TimerScheduler { //创建一个调度器 autoExecScheduler := NewTimerScheduler() //启动调度器 autoExecScheduler.Start() //阻塞获取定时器并执行 go func() { delayFunc := autoExecScheduler.GetTriggerChan() for df := range delayFunc { go df.Call() } }() return autoExecScheduler }
// Copyright (c) 2018 Benjamin Borbe All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The kafka-version-collector collects available versions of software and publish it to a topic. package main import ( "context" "fmt" "net/http" "os" "os/signal" "runtime" "strings" "syscall" "time" "github.com/Shopify/sarama" "github.com/bborbe/argument" "github.com/bborbe/cron" flag "github.com/bborbe/flagenv" "github.com/bborbe/kafka-dockerhub-version-collector/version" "github.com/bborbe/run" "github.com/golang/glog" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/seibert-media/go-kafka/schema" ) func main() { defer glog.Flush() glog.CopyStandardLogTo("info") runtime.GOMAXPROCS(runtime.NumCPU()) _ = flag.Set("logtostderr", "true") app := &application{} if err := argument.Parse(app); err != nil { glog.Exitf("parse app failed: %v", err) } glog.V(0).Infof("app started") if err := app.Run(contextWithSig(context.Background())); err != nil { glog.Exitf("app failed: %+v", err) } glog.V(0).Infof("app finished") } func contextWithSig(ctx context.Context) context.Context { ctxWithCancel, cancel := context.WithCancel(ctx) go func() { defer cancel() signalCh := make(chan os.Signal, 1) signal.Notify(signalCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) select { case <-signalCh: case <-ctx.Done(): } }() return ctxWithCancel } type application struct { Wait time.Duration `required:"true" arg:"wait" env:"WAIT" default:"1h" usage:"time to wait before next version collect"` Port int `required:"true" arg:"port" env:"PORT" default:"9003" usage:"port to listen"` KafkaBrokers string `required:"true" arg:"kafka-brokers" env:"KAFKA_BROKERS" usage:"kafka brokers"` KafkaTopic string `required:"true" arg:"kafka-topic" env:"KAFKA_TOPIC" usage:"kafka topic"` SchemaRegistryUrl string `required:"true" arg:"kafka-schema-registry-url" env:"KAFKA_SCHEMA_REGISTRY_URL" usage:"kafka schema registry url"` Repositories string `required:"true" arg:"repositories" env:"REPOSITORIES" usage:"Docker Repositories"` } func (a *application) Run(ctx context.Context) error { return run.CancelOnFirstFinish( ctx, a.runCron, a.runHttpServer, ) } func (a *application) runCron(ctx context.Context) error { config := sarama.NewConfig() config.Version = sarama.V2_0_0_0 config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Retry.Max = 10 config.Producer.Return.Successes = true client, err := sarama.NewClient(strings.Split(a.KafkaBrokers, ","), config) if err != nil { return errors.Wrap(err, "create client failed") } defer client.Close() producer, err := sarama.NewSyncProducerFromClient(client) if err != nil { return errors.Wrap(err, "create sync producer failed") } defer producer.Close() httpClient := http.DefaultClient var fetcherlist []version.Fetcher for _, repo := range strings.Split(a.Repositories, ",") { fetcherlist = append( fetcherlist, version.NewFetcher(httpClient, "https://hub.docker.com", repo), ) } syncer := version.NewSyncer( version.NewFetcherList(fetcherlist), version.NewSender( producer, schema.NewRegistry( httpClient, a.SchemaRegistryUrl, ), a.KafkaTopic, ), ) cronJob := cron.NewWaitCron( a.Wait, syncer.Sync, ) return cronJob.Run(ctx) } func (a *application) runHttpServer(ctx context.Context) error { server := &http.Server{ Addr: fmt.Sprintf(":%d", a.Port), Handler: promhttp.Handler(), } go func() { select { case <-ctx.Done(): if err := server.Shutdown(ctx); err != nil { glog.Warningf("shutdown failed: %v", err) } } }() err := server.ListenAndServe() if err == http.ErrServerClosed { glog.V(0).Info(err) return nil } return errors.Wrap(err, "httpServer failed") }
package main import ( "bufio" "fmt" "os" "github.com/nu7hatch/gouuid" . "../middleware" ) func readNotifications(publisher *TopicPublisher, session *TopicSession,topic string, channel (chan int)){ i := 0 for{ messageFromInput := sendMessage() uuid_, _ := uuid.NewV4() publisher.Send(session.CreateMessage(messageFromInput, topic,i,uuid_.String())) i++ } } func sendMessage() string{ reader := bufio.NewReader(os.Stdin) fmt.Print("Enter the sale description: ") title, _ := reader.ReadString('\n') fmt.Print("Enter the sale link: ") link, _ := reader.ReadString('\n') return title + "\n" + link }
package main import ( "fmt" ) //請將以下程式以物件導向方式重新撰寫,並利用Interface建立相關物件 // type AnimalsType int // const ( // Duck AnimalsType = iota // Dog // Tiger // ) // func New(t AnimalsType) string { // switch t { // case Duck: // return "Pack Pack" // case Dog: // return "Wow Wow" // case Tiger: // return "Halum Halum" // default: // panic("Unknow animals type") // } // } // func main() { // animals := make([]AnimalsType, 0) // animals = append(animals,Duck ,Dog ,Tiger) // for _, a := range animals{ // fmt.Println(New(a)) // } // } type AnimalsType int const ( Duck AnimalsType = iota Dog Tiger ) type DuckClass struct{} func NewDuck() *DuckClass { return new(DuckClass) } func (t *DuckClass) Speak() { fmt.Println("Pack Pack") } type DogClass struct{} func NewDog() *DogClass { return new(DogClass) } func (t *DogClass) Speak() { fmt.Println("Wow Wow") } type TigerClass struct{} func NewTiger() *TigerClass{ return new(TigerClass) } func (t *TigerClass) Speak() { fmt.Println("Halum Halum") } type IAnimals interface{ Speak() } func New(t AnimalsType) IAnimals { switch t { case Duck: return NewDuck() case Dog: return NewDog() case Tiger: return NewTiger() default: panic("Unknow animals type") } } func main() { // animals := make([]IAnimals, 0) duck := New(Duck) dog := New(Dog) tiger := New(Tiger) fmt.Printf("%T,%T,%T\n", duck,dog,tiger) //duck,dog,tiger為初始化後的Class // animals = append(animals,duck ,dog ,tiger) animals := []IAnimals{duck,dog,tiger} fmt.Printf("%T\n", animals) for _, a := range animals{ a.Speak() } }
package service import ( "encoding/json" "errors" "github.com/gin-gonic/gin" "github.com/godcong/role-manager-server/model" "github.com/godcong/role-manager-server/permission" log "github.com/sirupsen/logrus" "strings" ) // MaxMultipartMemory ... const MaxMultipartMemory = 8 << 20 // LoginCheck ... func LoginCheck(ver string) gin.HandlerFunc { return func(ctx *gin.Context) { token := ctx.Request.Header.Get("token") if token == "" { failed(ctx, "token is null") ctx.Abort() return } t, err := FromToken(token) if err != nil { failed(ctx, err.Error()) ctx.Abort() return } user := model.NewUser() log.Println(t.OID) user.ID = model.ID(t.OID) err = user.Find() if err != nil { failed(ctx, err.Error()) ctx.Abort() return } ctx.Set("user", user) ctx.Next() } } func handleFuncName(ctx *gin.Context) string { hn := strings.Split(ctx.HandlerName(), ".") size := len(hn) if size > 0 { size -= 2 } return hn[size] } // PermissionCheck ... func PermissionCheck(ver string) gin.HandlerFunc { return func(ctx *gin.Context) { per := permission.ParseContext(ctx) user := User(ctx) role, err := user.Role() if err == nil { //超级管理员拥有所有权限 if role.Slug == model.SlugGenesis { ctx.Next() return } } if user.Block { nop(ctx, "this account has been blocked") return } p := model.NewPermission() //logger := Logger(ctx) p.Slug = per.Slug() err = p.Find() if err != nil { log.Println(err.Error()) nop(ctx, err.Error()) ctx.Abort() return } err = user.CheckPermission(p) if err != nil { log.Println(err.Error()) nop(ctx, "this account has no permissions to visit this url") ctx.Abort() return } ctx.Next() } } // VisitLog ... func VisitLog(ver string) gin.HandlerFunc { return func(ctx *gin.Context) { l := model.NewLog() l.Permission = handleFuncName(ctx) l.Method = ctx.Request.Method l.URL = ctx.Request.URL.String() detail, err := GetPostFormString(ctx) if err != nil { log.Error(err) l.Err = err.Error() } l.Detail = detail user, err := decodeUser(ctx) if err != nil { log.Error(err) l.Err = err.Error() } l.UserID = user.ID l.VisitIP = ctx.Request.Header.Get("REMOTE-HOST") err = l.Create() if err != nil { log.Error(err) } ctx.Set("logger", l) log.Printf("visit: %+v\n", *l) } } // GetPostFormString ... func GetPostFormString(ctx *gin.Context) (string, error) { req := ctx.Request req.ParseForm() req.ParseMultipartForm(MaxMultipartMemory) if len(req.PostForm) > 0 { bytes, err := json.Marshal(req.PostForm) if err != nil { return "", err } return string(bytes), nil } if req.MultipartForm != nil && req.MultipartForm.File != nil { bytes, err := json.Marshal(req.PostForm) if err != nil { return "", err } return string(bytes), nil } return "", nil } func decodeUser(ctx *gin.Context) (*model.User, error) { user := User(ctx) if user != nil { return user, nil } token := ctx.Request.Header.Get("token") if token == "" { return &model.User{}, errors.New("token is null") } t, err := FromToken(token) if err != nil { return &model.User{}, err } user = model.NewUser() log.Println(t.OID) user.ID = model.ID(t.OID) err = user.Find() if err != nil { return &model.User{}, err } return user, nil }
package PDU import ( "github.com/andrewz1/gosmpp/Data" "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/Utils" ) type AlertNotification struct { Request } func NewAlertNotification() *AlertNotification { a := &AlertNotification{} a.Construct() return a } func (c *AlertNotification) Construct() { defer c.SetRealReference(c) c.Request.Construct() c.SetCommandId(Data.ALERT_NOTIFICATION) } func (c *AlertNotification) GetInstance() (IPDU, error) { return NewAlertNotification(), nil } func (c *AlertNotification) CanResponse() bool { return false } func (c *AlertNotification) CreateResponse() (IResponse, error) { return nil, nil } func (c *AlertNotification) GetBody() (*Utils.ByteBuffer, *Exception.Exception, IPDU) { return nil, nil, nil } func (c *AlertNotification) SetBody(buffer *Utils.ByteBuffer) (*Exception.Exception, IPDU) { return nil, nil }
package render import ( "github.com/eriklupander/rt/internal/pkg/config" "github.com/eriklupander/rt/internal/pkg/mat" "github.com/stretchr/testify/assert" "math" "testing" ) func TestReflectedColorForNonreflectiveMaterial(t *testing.T) { w := mat.NewDefaultWorld() rc := Context{world: w} r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 0, 1)) shape := w.Objects[1] material := shape.GetMaterial() material.Ambient = 1.0 shape.SetMaterial(material) xs := mat.NewIntersection(1, shape) comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs, r, &comps) color := rc.reflectedColor(comps, 1, 1) assert.Equal(t, black, color) } func TestReflectedColorForReflectiveMaterial(t *testing.T) { w := mat.NewDefaultWorld() plane := mat.NewPlane() plane.SetTransform(mat.Translate(0, -1, -0)) material := plane.GetMaterial() material.Reflectivity = 0.5 plane.SetMaterial(material) w.Objects = append(w.Objects, plane) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -3), mat.NewVector(0, -math.Sqrt(2)/2, math.Sqrt(2)/2)) xs := mat.NewIntersection(math.Sqrt(2), plane) comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs, r, &comps) color := rc.reflectedColor(comps, 1, 1) assert.InEpsilon(t, 0.19032, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.2379, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.14274, color.Get(2), mat.Epsilon) } func TestShadeHitWithReflectiveMaterial(t *testing.T) { w := mat.NewDefaultWorld() plane := mat.NewPlane() plane.SetTransform(mat.Translate(0, -1, -0)) material := plane.GetMaterial() material.Reflectivity = 0.5 plane.SetMaterial(material) w.Objects = append(w.Objects, plane) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -3), mat.NewVector(0, -math.Sqrt(2)/2, math.Sqrt(2)/2)) xs := mat.NewIntersection(math.Sqrt(2), plane) comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs, r, &comps) color := rc.shadeHit(comps, 1, 1) assert.InEpsilon(t, 0.87677, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.92436, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.82918, color.Get(2), mat.Epsilon) } func TestColorAtWithMutuallyReflectiveSurfaces(t *testing.T) { w := mat.NewWorld() w.Light = []mat.Light{mat.NewLight(mat.NewPoint(0, 0, 0), mat.NewColor(1, 1, 1))} lowerPlane := mat.NewPlane() lowerPlane.SetMaterial(mat.NewDefaultReflectiveMaterial(1.0)) lowerPlane.SetTransform(mat.Translate(0, -1, 0)) w.Objects = append(w.Objects, lowerPlane) upperPlane := mat.NewPlane() upperPlane.SetMaterial(mat.NewDefaultReflectiveMaterial(1.0)) upperPlane.SetTransform(mat.Translate(0, 1, 0)) w.Objects = append(w.Objects, upperPlane) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 1, 0)) _ = rc.colorAt(r, 1, 5) } func TestTheReflectedColorAtMaxRecursiveDepth(t *testing.T) { w := mat.NewWorld() pl := mat.NewPlane() pl.SetMaterial(mat.NewDefaultReflectiveMaterial(0.5)) pl.SetTransform(mat.Translate(0, -1, 0)) w.Objects = append(w.Objects, pl) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -3), mat.NewVector(0, -math.Sqrt(2)/2, math.Sqrt(2)/2)) xs := mat.NewIntersection(math.Sqrt(2), pl) comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs, r, &comps) color := rc.reflectedColor(comps, 0, 0) assert.Equal(t, black, color) } func TestRayForPixelThroughCenterOfCanvas(t *testing.T) { cam := mat.NewCamera(201, 101, math.Pi/2.0) // copy(cam.Inverse.Elems, mat.IdentityMatrix.Elems) cam.Inverse = mat.IdentityMatrix rc := NewContext(0, mat.NewWorld(), cam, nil, nil, nil) r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 0, 0)) rc.rayForPixel(100, 50, &r) assert.Equal(t, mat.NewPoint(0, 0, 0), r.Origin) assert.Equal(t, mat.NewVector(0, 0, -1), r.Direction) } func TestRayForPixelThroughCornerOfCanvas(t *testing.T) { cam := mat.NewCamera(201, 101, math.Pi/2.0) rc := NewContext(0, mat.NewWorld(), cam, nil, nil, nil) r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 0, 0)) rc.rayForPixel(0, 0, &r) assert.Equal(t, mat.NewPoint(0, 0, 0), r.Origin) assert.InEpsilon(t, 0.66519, r.Direction.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.33259, r.Direction.Get(1), mat.Epsilon) assert.InEpsilon(t, -0.66851, r.Direction.Get(2), mat.Epsilon) } // Page 103, third testx func TestRayForPixelWhenCamIsTransformed(t *testing.T) { cam := mat.NewCamera(201, 101, math.Pi/2.0) cam.Transform = mat.Multiply(mat.RotateY(math.Pi/4), mat.Translate(0, -2, 5)) cam.Inverse = mat.Inverse(cam.Transform) rc := NewContext(0, mat.NewWorld(), cam, nil, nil, nil) r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 0, 0)) rc.rayForPixel(100, 50, &r) assert.Equal(t, mat.NewPoint(0, 2, -5), r.Origin) assert.True(t, mat.TupleEquals(mat.NewVector(math.Sqrt(2.0)/2.0, 0.0, -math.Sqrt(2.0)/2.0), r.Direction)) } // Page 104 func TestRender(t *testing.T) { config.Cfg = &config.Config{ Width: 160, Height: 120, Threads: 1, DoFCamera: false, Samples: 0, SoftShadowSamples: 0, } worlds := make([]mat.World, 0) for i := 0; i < config.Cfg.Threads; i++ { w := mat.NewDefaultWorld() worlds = append(worlds, w) } c := mat.NewCamera(11, 11, math.Pi/2) from := mat.NewPoint(0, 0, -5) to := mat.NewPoint(0, 0, 0) upVec := mat.NewVector(0, 1, 0) c.Transform = mat.ViewTransform(from, to, upVec) c.Inverse = mat.Inverse(c.Transform) canvas := Threaded(c, worlds) // Note use of very high epsilon, is due to random multisampling being used.F assert.InEpsilon(t, 0.38066, canvas.ColorAt(5, 5).Get(0), 0.3) assert.InEpsilon(t, 0.47583, canvas.ColorAt(5, 5).Get(1), 0.3) assert.InEpsilon(t, 0.2855, canvas.ColorAt(5, 5).Get(2), 0.3) } // Page 95 func TestShadeIntersection(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -5), mat.NewVector(0, 0, 1)) i := mat.Intersection{T: 4.0, S: w.Objects[0]} comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(i, r, &comps) color := rc.shadeHit(comps, 1, 1) assert.InEpsilon(t, 0.38066, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.47583, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.2855, color.Get(2), mat.Epsilon) } func TestShadeIntersectionFromInside(t *testing.T) { w := mat.NewDefaultWorld() w.Light = []mat.Light{mat.NewLight(mat.NewPoint(0, 0.25, 0), mat.NewColor(1, 1, 1))} rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, 0), mat.NewVector(0, 0, 1)) i := mat.Intersection{T: 0.5, S: w.Objects[1]} comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(i, r, &comps) color := rc.shadeHit(comps, 1, 1) assert.InEpsilon(t, 0.90498, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.90498, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.90498, color.Get(2), mat.Epsilon) } func TestColorWhenRayMiss(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -5), mat.NewVector(0, 1, 0)) color := rc.colorAt(r, 1, 5) assert.Equal(t, color[0], 0.0) assert.Equal(t, color[1], 0.0) assert.Equal(t, color[2], 0.0) } func TestColorWhenRayHits(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -5), mat.NewVector(0, 0, 1)) color := rc.colorAt(r, 1, 5) assert.InEpsilon(t, 0.38066, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.47583, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.2855, color.Get(2), mat.Epsilon) } // Page 97 func TestColorWhenCastWithinSphereAtInsideSphere(t *testing.T) { w := mat.NewDefaultWorld() w.Objects[0].SetMaterial(mat.NewMaterial(mat.NewColor(0.8, 1.0, 0.6), 1.0, 0.7, 0.2, 200)) w.Objects[1].SetMaterial(mat.NewMaterial(mat.NewColor(0.8, 1.0, 0.6), 1.0, 0.7, 0.2, 200)) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, 0.75), mat.NewVector(0, 0, -1)) color := rc.colorAt(r, 1, 5) assert.InEpsilon(t, w.Objects[1].GetMaterial().Color.Get(0), color.Get(0), mat.Epsilon) assert.InEpsilon(t, w.Objects[1].GetMaterial().Color.Get(1), color.Get(1), mat.Epsilon) assert.InEpsilon(t, w.Objects[1].GetMaterial().Color.Get(2), color.Get(2), mat.Epsilon) } func TestPointNotInShadow(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) p := mat.NewPoint(0, 10, 10) assert.False(t, rc.pointInShadow(w.Light[0], p)) } func TestPointInShadow(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) p := mat.NewPoint(10, -10, 10) assert.True(t, rc.pointInShadow(w.Light[0], p)) } func TestPointNotInShadowWhenBehindLight(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) p := mat.NewPoint(-20, 20, -20) assert.False(t, rc.pointInShadow(w.Light[0], p)) } func TestPointNotInShadowWhenBehindPoint(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) p := mat.NewPoint(-2, 2, -2) assert.False(t, rc.pointInShadow(w.Light[0], p)) } // Big one on page 114 func TestWorldWithShadowTest(t *testing.T) { w := mat.NewDefaultWorld() w.Light = []mat.Light{mat.NewLight(mat.NewPoint(0, 0, -10), mat.NewColor(1, 1, 1))} s := mat.NewSphere() w.Objects = append(w.Objects, s) s2 := mat.NewSphere() s2.Transform = mat.Multiply(s2.Transform, mat.Translate(0, 0, 10)) w.Objects = append(w.Objects, s2) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, 5), mat.NewVector(0, 0, 1)) i := mat.NewIntersection(4, s2) comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(i, r, &comps) color := rc.shadeHit(comps, 1, 1) color[3] = 1 // just a fix for me using Tuple4 to represent colors... assert.Equal(t, mat.NewColor(0.1, 0.1, 0.1), color) } func TestOpaqueRefraction(t *testing.T) { w := mat.NewDefaultWorld() rc := New(w) s1 := w.Objects[0] r := mat.NewRay(mat.NewPoint(0, 0, -5), mat.NewVector(0, 0, 1)) xs := []mat.Intersection{ mat.NewIntersection(4, s1), mat.NewIntersection(6, s1), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[0], r, &comps, xs...) color := rc.refractedColor(comps, 5, 5) assert.Equal(t, black, color) } func TestRefractiveColorAndMaxRecursionDepth(t *testing.T) { w := mat.NewDefaultWorld() s1 := w.Objects[0] material := mat.NewDefaultMaterial() material.Transparency = 1.0 material.RefractiveIndex = 1.5 s1.SetMaterial(material) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, -5), mat.NewVector(0, 0, 1)) xs := []mat.Intersection{ mat.NewIntersection(4, s1), mat.NewIntersection(6, s1), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[0], r, &comps, xs...) color := rc.refractedColor(comps, 0, 0) assert.Equal(t, black, color) } func TestTotalInternalRefraction(t *testing.T) { w := mat.NewDefaultWorld() s1 := w.Objects[0] material := mat.NewDefaultMaterial() material.Transparency = 1.0 material.RefractiveIndex = 1.5 s1.SetMaterial(material) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, math.Sqrt(2)/2), mat.NewVector(0, 1, 0)) xs := []mat.Intersection{ mat.NewIntersection(-math.Sqrt(2)/2, s1), mat.NewIntersection(math.Sqrt(2)/2, s1), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[1], r, &comps, xs...) color := rc.refractedColor(comps, 5, 5) assert.Equal(t, black, color) } func TestRefractedColorWithRefractedRay(t *testing.T) { w := mat.NewDefaultWorld() s1 := w.Objects[0] material := mat.NewDefaultMaterial() material.Ambient = 1.0 material.Pattern = mat.NewTestPattern() s1.SetMaterial(material) s2 := w.Objects[1] material2 := mat.NewDefaultMaterial() material2.Transparency = 1.0 material2.RefractiveIndex = 1.5 s2.SetMaterial(material2) rc := New(w) r := mat.NewRay(mat.NewPoint(0, 0, 0.1), mat.NewVector(0, 1, 0)) xs := []mat.Intersection{ mat.NewIntersection(-0.9899, s1), mat.NewIntersection(-0.4899, s2), mat.NewIntersection(0.4899, s2), mat.NewIntersection(0.4899, s1), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[2], r, &comps, xs...) color := rc.refractedColor(comps, 5, 5) assert.Equal(t, 0.0, color.Get(0)) assert.InEpsilon(t, 0.99888, color.Get(1), mat.Epsilon*2) assert.InEpsilon(t, 0.04725, color.Get(2), mat.Epsilon*5) } func TestShadeHitWithRefractedMaterial(t *testing.T) { w := mat.NewDefaultWorld() floor := mat.NewPlane() floor.SetTransform(mat.Translate(0, -1, 0)) mat1 := mat.NewDefaultMaterial() mat1.Transparency = 0.5 mat1.RefractiveIndex = 1.5 floor.SetMaterial(mat1) w.Objects = append(w.Objects, floor) ball := mat.NewSphere() mat2 := mat.NewDefaultMaterial() mat2.Color = mat.NewColor(1, 0, 0) mat2.Ambient = 0.5 ball.SetMaterial(mat2) ball.SetTransform(mat.Translate(0, -3.5, -0.5)) w.Objects = append(w.Objects, ball) rc := New(w) ray := mat.NewRay(mat.NewPoint(0, 0, -3), mat.NewVector(0, -math.Sqrt(2)/2, math.Sqrt(2)/2)) xs := []mat.Intersection{ mat.NewIntersection(math.Sqrt(2), floor), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[0], ray, &comps, xs...) color := rc.shadeHit(comps, 5, 5) assert.InEpsilon(t, 0.93642, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.68642, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.68642, color.Get(2), mat.Epsilon) } func TestShadeHitWhenBothTransparentAndRefractive(t *testing.T) { w := mat.NewDefaultWorld() r := mat.NewRay(mat.NewPoint(0, 0, -3), mat.NewVector(0, -math.Sqrt(2)/2, math.Sqrt(2)/2)) floor := mat.NewPlane() floor.SetTransform(mat.Translate(0, -1, 0)) mat1 := mat.NewDefaultMaterial() mat1.Reflectivity = 0.5 mat1.Transparency = 0.5 mat1.RefractiveIndex = 1.5 floor.SetMaterial(mat1) w.Objects = append(w.Objects, floor) ball := mat.NewSphere() ball.SetTransform(mat.Translate(0, -3.5, -0.5)) mat2 := mat.NewDefaultMaterial() mat2.Color = mat.NewColor(1, 0, 0) mat2.Ambient = 0.5 ball.SetMaterial(mat2) w.Objects = append(w.Objects, ball) rc := New(w) xs := []mat.Intersection{ mat.NewIntersection(math.Sqrt(2), floor), } comps := mat.NewComputation() mat.PrepareComputationForIntersectionPtr(xs[0], r, &comps, xs...) color := rc.shadeHit(comps, 5, 5) assert.InEpsilon(t, 0.93391, color.Get(0), mat.Epsilon) assert.InEpsilon(t, 0.69643, color.Get(1), mat.Epsilon) assert.InEpsilon(t, 0.69243, color.Get(2), mat.Epsilon) }
package db import "os" type DB interface { InitDB(conn map[string]string) AddToDB(key string, val string) ReadFromDB(id string) (string, error) } func CreateDB() DB { params := make(map[string]string) tmp := os.Getenv("MYSQL_SERVICE_HOST") if tmp == "" { tmp = "mysql" } params["Username"] = "root" params["Password"] = "root" params["Host"] = tmp params["Db"] = "test" z := &mySQLDB{} z.InitDB(params) return z }
package utils import ( "net/http" "io/ioutil" "log" "strings" "bytes" "fmt" ) func GetContent(url string) string{ resp, err := http.Get(url) if err != nil || resp == nil{ log.Printf("%s url connection issue",url) return "" } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } pageContent := string(body) status := resp.StatusCode //返回的状态码 if status == 200 { log.Println(pageContent) }else { log.Printf("%s url connection issue, status code:%d",url,status) } return pageContent } func PostHttp(url,para string) string { //json序列化 post := para //fmt.Println(url, "post", post) var jsonStr = []byte(post) //fmt.Println("jsonStr", jsonStr) fmt.Println("new_str", bytes.NewBuffer(jsonStr)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) // req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { //panic(err) return "" } defer resp.Body.Close() //fmt.Println("response Status:", resp.Status) //fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) return string(body) } func PostContent(url,para string) string{ resp, err := http.Post(url,"application/json",strings.NewReader(para)) if err != nil || resp == nil{ log.Printf("%s url connection issue",url) return "" } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } pageContent := string(body) status := resp.StatusCode //返回的状态码 if status == 200 { log.Println(pageContent) }else { log.Printf("%s url connection issue, status code:%d",url,status) } return pageContent }
package cmd import ( "bytes" "copyto/logic" "fmt" "github.com/gookit/color" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "io" "testing" ) type mockprn struct { w *bytes.Buffer } func (m *mockprn) String() string { return m.w.String() } func newMockPrn() logic.Printer { return &mockprn{w: bytes.NewBufferString("")} } func (m *mockprn) Print(format string, a ...interface{}) { str := fmt.Sprintf(format, a...) _, _ = fmt.Fprint(m.w, str) } func (m *mockprn) W() io.Writer { return m.w } func (*mockprn) SetColor(c color.Color) {} func (*mockprn) ResetColor() {} func Test_ConfNormalCase(t *testing.T) { var tests = []struct { cmd string pathKey string }{ {"conf", "-p"}, {"conf", "--path"}, {"config", "--path"}, {"c", "--path"}, } for _, test := range tests { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() const config = `# test config title = "test" [sources] [sources.source1] source = 's' [definitions] [definitions.def1] sourcelink = "source1" target = 't' [definitions.def2] source = 's1' target = 't1'` appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) appFS.MkdirAll("c", 0755) const sourceContent = "src" const sourceFilePath = "s/p1/f1.txt" const targetContent = "tgt" const targetFilePath = "t/p1/f1.txt" const configPath = "c/config.toml" afero.WriteFile(appFS, sourceFilePath, []byte(sourceContent), 0644) afero.WriteFile(appFS, targetFilePath, []byte(targetContent), 0644) afero.WriteFile(appFS, configPath, []byte(config), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute(test.cmd, test.pathKey, configPath) // Assert newTargetContent, _ := afero.ReadFile(appFS, targetFilePath) ass.Equal(sourceContent, string(newTargetContent)) } } func Test_SourceKeyMismatch_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() const config = `# test config title = "test" [sources] [sources.source1] source = 's' [definitions] [definitions.def1] sourcelink = "source2" target = 't'` appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) appFS.MkdirAll("c", 0755) afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) afero.WriteFile(appFS, "c/config.toml", []byte(config), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute("conf", "-p", "c/config.toml") // Assert b, _ := afero.ReadFile(appFS, "t/p1/f1.txt") ass.Equal("/t/p1/f1.txt", string(b)) } func Test_InvalidConfig_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() const config = `# test config title = "test" [sources] [sources.source1` appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) appFS.MkdirAll("c", 0755) afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) afero.WriteFile(appFS, "c/config.toml", []byte(config), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute("conf", "-p", "c/config.toml") // Assert b, _ := afero.ReadFile(appFS, "t/p1/f1.txt") ass.Equal("/t/p1/f1.txt", string(b)) } func Test_UnexistConfig_NothingCopied(t *testing.T) { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) afero.WriteFile(appFS, "s/p1/f1.txt", []byte("/s/p1/f1.txt"), 0644) afero.WriteFile(appFS, "t/p1/f1.txt", []byte("/t/p1/f1.txt"), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute("conf", "-p", "c/config.toml") // Assert b, _ := afero.ReadFile(appFS, "t/p1/f1.txt") ass.Equal("/t/p1/f1.txt", string(b)) } func Test_ConfIncludeFileNotMatched_FileNotCopied(t *testing.T) { var tests = []struct { cmd string pathKey string }{ {"conf", "-p"}, {"conf", "--path"}, {"config", "--path"}, {"c", "--path"}, } for _, test := range tests { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() const config = `# test config title = "test" [definitions] [definitions.def2] source = 's' target = 't' include = 'f2.*'` appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) appFS.MkdirAll("c", 0755) const sourceContent = "src" const sourceFilePath = "s/p1/f1.txt" const targetContent = "tgt" const targetFilePath = "t/p1/f1.txt" const configPath = "c/config.toml" afero.WriteFile(appFS, sourceFilePath, []byte(sourceContent), 0644) afero.WriteFile(appFS, targetFilePath, []byte(targetContent), 0644) afero.WriteFile(appFS, configPath, []byte(config), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute(test.cmd, test.pathKey, configPath) // Assert newTargetContent, _ := afero.ReadFile(appFS, targetFilePath) ass.Equal(targetContent, string(newTargetContent)) } } func Test_ConfExcludeFileMatched_FileNotCopied(t *testing.T) { var tests = []struct { cmd string pathKey string }{ {"conf", "-p"}, {"conf", "--path"}, {"config", "--path"}, {"c", "--path"}, } for _, test := range tests { // Arrange ass := assert.New(t) appFS := afero.NewMemMapFs() const config = `# test config title = "test" [definitions] [definitions.def2] source = 's' target = 't' exclude = 'f1.*'` appFS.MkdirAll("s/p1", 0755) appFS.MkdirAll("t/p1", 0755) appFS.MkdirAll("c", 0755) const sourceContent = "src" const sourceFilePath = "s/p1/f1.txt" const targetContent = "tgt" const targetFilePath = "t/p1/f1.txt" const configPath = "c/config.toml" afero.WriteFile(appFS, sourceFilePath, []byte(sourceContent), 0644) afero.WriteFile(appFS, targetFilePath, []byte(targetContent), 0644) afero.WriteFile(appFS, configPath, []byte(config), 0644) appPrinter = newMockPrn() appFileSystem = appFS // Act _ = Execute(test.cmd, test.pathKey, configPath) // Assert newTargetContent, _ := afero.ReadFile(appFS, targetFilePath) ass.Equal(targetContent, string(newTargetContent)) } }
package main import ( "github.com/fleegrid/core" "github.com/fleegrid/nat" "github.com/fleegrid/pkt" "github.com/fleegrid/sh" "github.com/fleegrid/tun" "net" "syscall" ) // DefaultServerSubnet default subnet for server const DefaultServerSubnet = "10.152.219.2/24" // Server Server context type Server struct { // init config *core.Config cipher core.Cipher net *nat.Net localIP net.IP // boot tun *tun.Device listener net.Listener // running // [NAT IP] -> [Client Virtual LocalIP] clientIPs *nat.IPMap // [NAT IP] -> [net.Conn] clients *ConnMgr // done done chan bool stop bool } // NewServer create a new server instance func NewServer(config *core.Config) (s *Server, err error) { // alloc s = &Server{ config: config, clientIPs: nat.NewIPMap(), clients: NewConnMgr(), done: make(chan bool, 2), } // create cipher if s.cipher, err = core.NewCipher(config.Cipher, config.Passwd); err != nil { logln("core: failed to initializae cipher:", config.Cipher, err) return } // create managed net if s.net, err = nat.NewNetFromCIDR(DefaultServerSubnet); err != nil { logln("nat: failed to create managed subnet:", err) return } // take a localIP if s.localIP, err = s.net.Take(); err != nil { logln("nat: failed to take a localIP:", err) return } return } // Run run the server, method not returns until Stop() called func (s *Server) Run() (err error) { if err = s.boot(); err != nil { return } go s.acceptLoop() go s.tunReadLoop() <-s.done <-s.done return } func (s *Server) boot() (err error) { s.stop = false // print informations logf("core: using cipher %v\n", s.config.Cipher) logf("nat: using subnet %v, %v -> %v\n", s.net.String(), s.localIP.String(), s.net.GatewayIP.String()) // TUN if s.tun, err = tun.NewDevice(); err != nil { logln("tun: failed to create device:", err) return } logln("tun: device created:", s.tun.Name()) // listen if s.listener, err = net.Listen("tcp", s.config.Address); err != nil { logln("conn: failed to listen:", s.config.Address, err) return } logln("conn: listening on:", s.config.Address) // setup TUN if err = s.setupTUN(); err != nil { logln("tun: failed to setup TUN:", err) return } logln("tun: setup success") return } func (s *Server) acceptLoop() { // defer to notify done defer func() { dlogln("server: acceptLoop done") s.done <- true }() // accept for { conn, err := s.listener.Accept() if err != nil { if !s.stop { logln("conn: failed to accept:", err) } break } logln("conn: new connection:", conn.RemoteAddr().String()) // cipher wrapped connection conn = core.NewStreamConn(conn, s.cipher) // handle connection go s.handleConnection(conn) } } func (s *Server) tunReadLoop() { // defer to notify done defer func() { dlogln("server: tunReadLoop done") s.done <- true }() buf := make([]byte, 64*1024) for { // read buf var l int var err error if l, err = s.tun.Read(buf); err != nil { if !s.stop { logln("tun: failed to read packet:", err) } break } // extract Payload var pl []byte if pl, err = pkt.TUNPacket(buf[:l]).Payload(); err != nil { logln("tun: failed to extract payload:", err) continue } // extract IPPacket ipp := pkt.IPPacket(pl) // check IP version if ipp.Version() != 4 { logln("tun: only IPv4 is supported") continue } // check IPPacket length if il, err := ipp.Length(); il != len(ipp) || err != nil { logln("tun: IPPacket length mismatch", il, "!=", len(ipp), err) continue } // extract destination IP dstIP, err := ipp.IP(pkt.DestinationIP) if err != nil { logln("tun: cannot extract destination IP") continue } // log srcIP, _ := ipp.IP(pkt.SourceIP) dstIP, _ = ipp.IP(pkt.DestinationIP) dlogf("tun: >> [v%v|%v], [%v -> %v]", ipp.Version(), len(ipp), srcIP.String(), dstIP.String()) // get client localIP clientLocalIP := s.clientIPs.Get(dstIP) if clientLocalIP == nil { logln("tun: IPPacket destination IP not found") continue } // rewrite DestinationIP to client's virtual localIP if err := ipp.SetIP(pkt.DestinationIP, clientLocalIP); err != nil { logln("tun: IPPacket destination IP failed to set") continue } // find client connection conn := s.clients.Get(dstIP) if conn == nil { logln("conn: cannot find corresponding connection for", dstIP.String()) continue } srcIP, _ = ipp.IP(pkt.SourceIP) dstIP, _ = ipp.IP(pkt.DestinationIP) dlogf("conn: %v << [v%v|%v], [%v -> %v]", conn.RemoteAddr().String(), ipp.Version(), len(ipp), srcIP.String(), dstIP.String()) // make a local copy and write p := make([]byte, len(ipp), len(ipp)) copy(p, ipp) go conn.Write(p) } } func (s *Server) setupTUN() (err error) { p := &sh.Params{ "DeviceName": s.tun.Name(), "LocalIP": s.localIP.String(), "RemoteIP": s.net.GatewayIP.String(), "Netmask": "255.255.255.0", "MTU": "1500", "CIDR": s.net.IP.String() + "/24", } if _, err = sh.Run(serverSetupScript, p); err != nil { logln("tun: failed to setup device:", err) } return } func (s *Server) shutdownTUN() (err error) { p := &sh.Params{ "DeviceName": s.tun.Name(), "CIDR": DefaultServerSubnet + "/24", } if _, err = sh.Run(serverShutdownScript, p); err != nil { logln("tun: failed to shutdown device:", err) } return } // handleConnection handles a connection between FleeGrid client and server // it reads IPPacket sent from client, assigns and rewrite virtual IP and send to TUN device func (s *Server) handleConnection(conn net.Conn) { // defer to close connection defer conn.Close() // extract RemoteAddr for name name := conn.RemoteAddr().String() // virtual ip var vip net.IP // original ip var oip net.IP // defer to remove virtual IP defer func() { if vip != nil { // remote conn ref s.clients.Delete(vip) // delete ip connection s.clientIPs.Delete(vip) // release allocated virtual IP s.net.Remove(vip) } }() for { // read packet ipp, err := pkt.ReadIPPacket(conn) if err != nil { if !s.stop { logln("conn:", name, "failed to read a IPPacket:", err) } break } // check version if ipp.Version() != 4 { logln("conn:", name, "IPPacket v6 is not supported") break } // log src, _ := ipp.IP(pkt.SourceIP) dst, _ := ipp.IP(pkt.DestinationIP) dlogf("conn: %v >> [v%v|%v], [%v -> %v]\n", name, ipp.Version(), len(ipp), src.String(), dst.String()) // virtual ip not assigned if vip == nil { // take a virtual IP vip, err = s.net.Take() if err != nil { logln("conn:", name, "cannot assign IP:", err) break } // get orignal IP oip, err = ipp.IP(pkt.SourceIP) if err != nil { logln("conn:", name, "cannot retrieve original IP:", name, err) break } // record [virtual IP] -> [client localIP] s.clientIPs.Set(vip, oip) // record [virtual IP] -> [net.Conn] s.clients.Set(vip, conn) logln("conn:", name, "virtual IP assigned", oip.String(), "->", vip.String()) // rewrite IP err = ipp.SetIP(pkt.SourceIP, vip) if err != nil { logln("conn:", name, "cannot rewrite source IP:", err) break } } else { // check source IP noip, err := ipp.IP(pkt.SourceIP) if err != nil { logln("conn:", name, "cannot retrieve original IP:", err) break } if !noip.Equal(oip) { logln("conn:", name, "original IP changed:", oip.String(), "->", noip.String()) break } // rewrite IP err = ipp.SetIP(pkt.SourceIP, vip) if err != nil { logln("conn:", name, "cannot rewrite source IP:", err) break } } // log src, _ = ipp.IP(pkt.SourceIP) dst, _ = ipp.IP(pkt.DestinationIP) dlogf("tun: << [v%v|%v], [%v -> %v]\n", ipp.Version(), len(ipp), src.String(), dst.String()) // create TUNPacket tp := make(pkt.TUNPacket, len(ipp)+4, len(ipp)+4) tp.SetProto(syscall.AF_INET) tp.CopyPayload(ipp) // write TUNPacket to tun if s.tun != nil { if _, err = s.tun.Write(tp); err != nil && !s.stop { logln("tun: failed to write:", err) } } } } // Stop stop the server, makes Run() exit func (s *Server) Stop() { s.stop = true logln("tun: closing device") s.shutdownTUN() if s.tun != nil { s.tun.Close() } logln("conn: closing server") if s.listener != nil { s.listener.Close() } }
package compute import ( "encoding/json" "fmt" "net/http" "net/url" ) const ( // ServiceDownActionNone indicates no action will be taken when a pool service is down. ServiceDownActionNone = "NONE" // ServiceDownActionDrop indicates that a pool service will be dropped when it is down. ServiceDownActionDrop = "DROP" // ServiceDownActionReselect indicates that a pool service will be reselected when it is down. ServiceDownActionReselect = "RESELECT" // LoadBalanceMethodRoundRobin indicates that requests will be directed to pool nodes in round-robin fashion. LoadBalanceMethodRoundRobin = "ROUND_ROBIN" // LoadBalanceMethodLeastConnectionsNode indicates that requests will be directed to the pool node that has the smallest number of active connections at the moment of connection. // All connections to the node are considered. LoadBalanceMethodLeastConnectionsNode = "LEAST_CONNECTIONS_NODE" // LoadBalanceMethodLeastConnectionsMember indicates that requests will be directed to the pool node that has the smallest number of active connections at the moment of connection. // Only connections to the node as a member of the current pool are considered. LoadBalanceMethodLeastConnectionsMember = "LEAST_CONNECTIONS_MEMBER" // LoadBalanceMethodObservedNode indicates that requests will be directed to the pool node that has the smallest number of active connections over time. // All connections to the node are considered. LoadBalanceMethodObservedNode = "OBSERVED_NODE" // LoadBalanceMethodObservedMember indicates that requests will be directed to the pool node that has the smallest number of active connections over time. // Only connections to the node as a member of the current pool are considered. LoadBalanceMethodObservedMember = "OBSERVED_MEMBER" // LoadBalanceMethodPredictiveNode indicates that requests will be directed to the pool node that is predicted to have the smallest number of active connections. // All connections to the pool are considered. LoadBalanceMethodPredictiveNode = "PREDICTIVE_NODE" // LoadBalanceMethodPredictiveMember indicates that requests will be directed to the pool node that is predicted to have the smallest number of active connections over time. // Only connections to the pool as a member of the current pool are considered. LoadBalanceMethodPredictiveMember = "PREDICTIVE_MEMBER" ) // VIPPool represents a VIP pool. type VIPPool struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` LoadBalanceMethod string `json:"loadBalanceMethod"` HealthMonitors []EntityReference `json:"healthMonitor"` ServiceDownAction string `json:"serviceDownAction"` SlowRampTime int `json:"slowRampTime"` State string `json:"state"` NetworkDomainID string `json:"networkDomainID"` DataCenterID string `json:"datacenterId"` CreateTime string `json:"createTime"` } // GetID returns the pool's Id. func (pool *VIPPool) GetID() string { return pool.ID } // GetResourceType returns the pool's resource type. func (pool *VIPPool) GetResourceType() ResourceType { return ResourceTypeVIPPool } // GetName returns the pool's name. func (pool *VIPPool) GetName() string { return pool.Name } // GetState returns the pool's current state. func (pool *VIPPool) GetState() string { return pool.State } // IsDeleted determines whether the pool has been deleted (is nil). func (pool *VIPPool) IsDeleted() bool { return pool == nil } var _ Resource = &VIPPool{} // ToEntityReference creates an EntityReference representing the VIPNode. func (pool *VIPPool) ToEntityReference() EntityReference { return EntityReference{ ID: pool.ID, Name: pool.Name, } } var _ NamedEntity = &VIPNode{} // VIPPools represents a page of VIPPool results. type VIPPools struct { Items []VIPPool PagedResult } // NewVIPPoolConfiguration represents the configuration for a new VIP pool. type NewVIPPoolConfiguration struct { // The VIP pool name. Name string `json:"name"` // The VIP pool description. Description string `json:"description"` // The load-balancing method used for pools in the pool. LoadBalanceMethod string `json:"loadBalanceMethod"` // The Id of the pool's associated health monitors (if any). // Up to 2 health monitors can be specified per pool. HealthMonitorIDs []string `json:"healthMonitorId,omitempty"` // The action performed when a pool in the pool is down. ServiceDownAction string `json:"serviceDownAction"` // The time, in seconds, over which the the pool will ramp new pools up to their full request rate. SlowRampTime int `json:"slowRampTime"` // The Id of the network domain where the pool is located. NetworkDomainID string `json:"networkDomainId"` // The Id of the data centre where the pool is located. DatacenterID string `json:"datacenterId,omitempty"` } // EditVIPPoolConfiguration represents the request body when editing a VIP pool. type EditVIPPoolConfiguration struct { // The VIP pool Id. ID string `json:"id"` // The VIP pool description. Description *string `json:"description,omitempty"` // The load-balancing method used for pools in the pool. LoadBalanceMethod *string `json:"loadBalanceMethod"` // The Id of the pool's associated health monitors (if any). // Up to 2 health monitors can be specified per pool. HealthMonitorIDs *[]string `json:"healthMonitorId,omitempty"` // The action performed when a pool in the pool is down. ServiceDownAction *string `json:"serviceDownAction"` // The time, in seconds, over which the the pool will ramp new pools up to their full request rate. SlowRampTime *int `json:"slowRampTime"` } // Request body for deleting a VIP pool. type deleteVIPPool struct { // The VIP pool ID. ID string `json:"id"` } // ListVIPPoolsInNetworkDomain retrieves a list of all VIP pools in the specified network domain. func (client *Client) ListVIPPoolsInNetworkDomain(networkDomainID string, paging *Paging) (pools *VIPPools, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/networkDomainVip/pool?networkDomainId=%s&%s", url.QueryEscape(organizationID), url.QueryEscape(networkDomainID), paging.EnsurePaging().toQueryParameters(), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } return nil, apiResponse.ToError("Request to list VIP pools in network domain '%s' failed with status code %d (%s): %s", networkDomainID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } pools = &VIPPools{} err = json.Unmarshal(responseBody, pools) if err != nil { return nil, err } return pools, nil } // GetVIPPool retrieves the VIP pool with the specified Id. // Returns nil if no VIP pool is found with the specified Id. func (client *Client) GetVIPPool(id string) (pool *VIPPool, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/networkDomainVip/pool/%s", url.QueryEscape(organizationID), url.QueryEscape(id), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } if apiResponse.ResponseCode == ResponseCodeResourceNotFound { return nil, nil // Not an error, but was not found. } return nil, apiResponse.ToError("Request to retrieve VIP pool with Id '%s' failed with status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } pool = &VIPPool{} err = json.Unmarshal(responseBody, pool) if err != nil { return nil, err } return pool, nil } // CreateVIPPool creates a new VIP pool. // Returns the Id of the new pool. func (client *Client) CreateVIPPool(poolConfiguration NewVIPPoolConfiguration) (poolID string, err error) { organizationID, err := client.getOrganizationID() if err != nil { return "", err } requestURI := fmt.Sprintf("%s/networkDomainVip/createPool", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &poolConfiguration) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return "", err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return "", err } if apiResponse.ResponseCode != ResponseCodeOK { return "", apiResponse.ToError("Request to create VIP pool '%s' failed with status code %d (%s): %s", poolConfiguration.Name, statusCode, apiResponse.ResponseCode, apiResponse.Message) } // Expected: "info" { "name": "poolId", "value": "the-Id-of-the-new-pool" } poolIDMessage := apiResponse.GetFieldMessage("poolId") if poolIDMessage == nil { return "", apiResponse.ToError("Received an unexpected response (missing 'poolId') with status code %d (%s): %s", statusCode, apiResponse.ResponseCode, apiResponse.Message) } return *poolIDMessage, nil } // EditVIPPool updates an existing VIP pool. func (client *Client) EditVIPPool(id string, poolConfiguration EditVIPPoolConfiguration) error { organizationID, err := client.getOrganizationID() if err != nil { return err } editPoolConfiguration := &poolConfiguration editPoolConfiguration.ID = id requestURI := fmt.Sprintf("%s/networkDomainVip/editPool", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, editPoolConfiguration) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return err } if statusCode != http.StatusOK { return apiResponse.ToError("Request to edit VIP pool '%s' failed with status code %d (%s): %s", poolConfiguration.ID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } return nil } // DeleteVIPPool deletes an existing VIP pool. // Returns an error if the operation was not successful. func (client *Client) DeleteVIPPool(id string) (err error) { organizationID, err := client.getOrganizationID() if err != nil { return err } requestURI := fmt.Sprintf("%s/networkDomainVip/deletePool", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &deleteVIPPool{id}) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return err } if apiResponse.ResponseCode != ResponseCodeOK { return apiResponse.ToError("Request to delete VIP pool '%s' failed with unexpected status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } return nil }
package main import ( "github.com/alecthomas/pathways" "net/http" ) type KeyValueService struct { service *pathways.Service kv map[string]string } func KeyValueServiceMap(root string) *pathways.Service { s := pathways.NewService(root) str := "" s.Path("/").Name("List").Get().APIResponseType(map[string]string{}) s.Path("/{key}").Name("Get").Get().APIResponseType(&str) s.Path("/{key}").Name("Create").Post().APIRequestType(&str) s.Path("/{key}").Name("Delete").Delete() return s } func NewClient(url string) *pathways.Client { s := KeyValueServiceMap(url) return pathways.NewClient(s, "application/json") } func NewKeyValueService(root string) *KeyValueService { k := &KeyValueService{ service: KeyValueServiceMap(root), kv: make(map[string]string), } k.service.Find("List").APIFunction(k.List) k.service.Find("Get").APIFunction(k.Get) k.service.Find("Create").APIFunction(k.Create) k.service.Find("Delete").APIFunction(k.Delete) return k } func (k *KeyValueService) ServeHTTP(w http.ResponseWriter, r *http.Request) { k.service.ServeHTTP(w, r) } func (k *KeyValueService) List(cx *pathways.Context) pathways.Response { return cx.APIResponse(http.StatusOK, k.kv) } func (k *KeyValueService) Get(cx *pathways.Context) pathways.Response { return cx.APIResponse(http.StatusOK, k.kv[cx.PathVars["key"]]) } func (k *KeyValueService) Create(cx *pathways.Context, value *string) pathways.Response { k.kv[cx.PathVars["key"]] = *value return cx.APIResponse(http.StatusCreated, "ok") } func (k *KeyValueService) Delete(cx *pathways.Context) pathways.Response { delete(k.kv, cx.PathVars["key"]) return cx.APIResponse(http.StatusOK, &struct{}{}) } func main() { s := NewKeyValueService("/api/") http.ListenAndServe(":8080", s) }
package main import "fmt" var z int var a = 3 var b = 4 var c = 5 func tinggiSegitiga() int { z = a + b return z } func main() { // assignmen operator var x, o int x += 1 x -= 1 // unary operator x++ x-- var p = 100 fmt.Println(tinggiSegitiga()) fmt.Println(x, o, p) }
package ingress import ( "context" "kourier/pkg/envoy" "kourier/pkg/generator" "knative.dev/pkg/tracker" "knative.dev/serving/pkg/apis/networking/v1alpha1" "knative.dev/pkg/network" apierrors "k8s.io/apimachinery/pkg/api/errors" kubeclient "k8s.io/client-go/kubernetes" corev1listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" nv1alpha1lister "knative.dev/serving/pkg/client/listers/networking/v1alpha1" ) type Reconciler struct { IngressLister nv1alpha1lister.IngressLister EndpointsLister corev1listers.EndpointsLister EnvoyXDSServer *envoy.XdsServer kubeClient kubeclient.Interface CurrentCaches *generator.Caches tracker tracker.Interface statusManager *StatusProber } func (reconciler *Reconciler) Reconcile(ctx context.Context, key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { return err } ingress, err := reconciler.IngressLister.Ingresses(namespace).Get(name) if apierrors.IsNotFound(err) { return reconciler.deleteIngress(namespace, name) } else if err != nil { return err } return reconciler.updateIngress(ingress) } func (reconciler *Reconciler) deleteIngress(namespace, name string) error { ingress := reconciler.CurrentCaches.GetIngress(name, namespace) // We need to check for ingress not being nil, because we can receive an event from an already // removed ingress, like for example, when the endpoints object for that ingress is updated/removed. if ingress != nil { reconciler.statusManager.CancelIngress(ingress) } err := reconciler.CurrentCaches.DeleteIngressInfo(name, namespace, reconciler.kubeClient) if err != nil { return err } snapshot, err := reconciler.CurrentCaches.ToEnvoySnapshot() if err != nil { return err } return reconciler.EnvoyXDSServer.SetSnapshot(&snapshot, nodeID) } func (reconciler *Reconciler) updateIngress(ingress *v1alpha1.Ingress) error { err := generator.UpdateInfoForIngress( reconciler.CurrentCaches, ingress, reconciler.kubeClient, reconciler.EndpointsLister, network.GetClusterDomainName(), reconciler.tracker, ) if err != nil { return err } snapshot, err := reconciler.CurrentCaches.ToEnvoySnapshot() if err != nil { return err } err = reconciler.EnvoyXDSServer.SetSnapshot(&snapshot, nodeID) if err != nil { return err } _, err = reconciler.statusManager.IsReady(ingress) return err }
package server import ( "io" "log" "net/http" "os" "service-import-data/repository" "service-import-data/service" ) type httpServer struct { http.Handler } func NewServer() Storage { return new(httpServer) } //Init new routes func (h *httpServer) NewRoutes() { log.Println("Init Routes") router := http.NewServeMux() //Create the endpoins router.Handle("/", http.HandlerFunc(jsonOperator)) h.Handler = router } //Run server func (h *httpServer) StartAPI() { port := os.Getenv("PORT") if port == "" { port = "5050" } log.Println("Start API") log.Println("** Service Started on Port " + port + " **") if err := http.ListenAndServe(":"+port, h); err != nil { log.Fatal("init server error in StartApi(), ", err) } } func jsonOperator(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodPost: file, handler, err := r.FormFile("file") if err != nil { log.Println("FormFile error in csvOperator(), ", err) } defer file.Close() f, err := os.OpenFile("archives/"+handler.Filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { log.Println("open file error in csvOperator(), ", err) } defer f.Close() _, err = io.Copy(f, file) if err != nil { log.Println("open file error in csvOperator(), ", err) } data := &service.Negativacoes{} ng := service.NewNegativacoes(data.Data) json, err := ng.ConvertFileToStruct("archives/" + handler.Filename) if err != nil { log.Println("open file error in csvOperator(), ", err) } db, err := repository.OpenConnection() if err != nil { log.Println("open file error in csvOperator(), ", err) } repo := repository.NewRepository(db) err = repo.SaveJson(json) if err != nil { log.Println("open file error in csvOperator(), ", err) } _, err = io.WriteString(w, "File Uploaded successfully\n") if err != nil { log.Println(" write http.ResponseWriter error in csvOperator(), ", err) } db.Close() default: w.WriteHeader(http.StatusNotFound) } }
// From https://github.com/aaronhackney/gowhois package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "sync" log "github.com/sirupsen/logrus" ) type ReturnJSON struct { WhoisRecord *Whois `json:"whoIsRecord"` ContactRecord *ContactRecord `json:"ContactRecord,omitempty"` } type WhoisList struct { WhoisRecords []*Whois `json:"records"` } type Whois struct { StartAddress string `json:"startAddress"` EndAddress string `json:"endAddress"` Handle string `json:"handle"` Name string `json:"name"` RegistrationDate string `json:"registrationDate,omitempty"` UpdateDate string `json:"updateDate,omitempty"` Version string `json:"version"` OriginASes []string `json:"originASes,omitempty"` ParentRefUrl map[string]string `json:"parentRefUrl,omitempty"` ContactRef map[string]string `json:"ContactRef,omitempty"` Comments []string `json:"comments,omitempty"` NetBlocks []map[string]string `json:"netBlocks"` } type ContactRecord struct { Handle string `json:"handle"` Name string `json:"name"` StreetAddress []string `json:"address"` City string `json:"city"` State string `json:"state"` PostalCode string `json:"postalCode"` Country string `json:"country"` ContactType string `json:"type"` Reference string `json:"reference"` } func whois(ip string, wg *sync.WaitGroup) (*Whois, error) { defer wg.Done() url := fmt.Sprintf("https://whois.arin.net/rest/ip/%s", ip) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Add("Accept", "application/json") client := &http.Client{} var resp *http.Response resp, err = client.Do(req) if err != nil { return nil, err } if resp.StatusCode != 200 { log.Warnf("ip: %s whois: %v", ip, resp) return nil, errors.New(fmt.Sprintf("response code: %d", resp.StatusCode)) } data, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } return unmarshalResponse(data) //contactRecord, _ := getContactRecord(whois.ContactRef["url"], data) //jsonOutput, _ := whois.generateJson(whois, contactRecord) //log.Info(string(jsonOutput)) } func getContactRecord(url string, data []byte) (*ContactRecord, error) { var contactRecord ContactRecord var jsonMap map[string]interface{} if err := json.Unmarshal(data, &jsonMap); err != nil { // unmarshall into a map of interfaces return nil, err } var prefix interface{} if org, exists := jsonMap["org"]; exists { contactRecord.ContactType = "org" prefix = org } else if cust, exists := jsonMap["customer"]; exists { contactRecord.ContactType = "customer" prefix = cust } for key, value := range prefix.(map[string]interface{}) { switch key { case "handle": contactRecord.Handle = value.(map[string]interface{})["$"].(string) case "name": contactRecord.Name = value.(map[string]interface{})["$"].(string) case "city": contactRecord.City = value.(map[string]interface{})["$"].(string) case "iso3166-2": contactRecord.State = value.(map[string]interface{})["$"].(string) case "postalCode": contactRecord.PostalCode = value.(map[string]interface{})["$"].(string) case "iso3166-1": contactRecord.Country = value.(map[string]interface{})["code2"].(map[string]interface{})["$"].(string) case "ref": contactRecord.Reference = value.(map[string]interface{})["$"].(string) } } contactRecord.StreetAddress, _ = getAddressLines(prefix) return &contactRecord, nil } func unmarshalResponse(b []byte) (*Whois, error) { var whois Whois var jsonMap map[string]interface{} var returnNetBlocks []map[string]string if err := json.Unmarshal(b, &jsonMap); err != nil { // unmarshall into a map of interfaces return nil, err } for key, value := range jsonMap["net"].(map[string]interface{}) { // Extract the top level json nest []net switch key { case "startAddress": whois.StartAddress = value.(map[string]interface{})["$"].(string) case "endAddress": whois.EndAddress = value.(map[string]interface{})["$"].(string) case "handle": whois.Handle = value.(map[string]interface{})["$"].(string) case "name": whois.Name = value.(map[string]interface{})["$"].(string) case "version": whois.Version = value.(map[string]interface{})["$"].(string) case "orgRef", "customerRef": whois.ContactRef = map[string]string{ "url": value.(map[string]interface{})["$"].(string), "handle": value.(map[string]interface{})["@handle"].(string), "name": value.(map[string]interface{})["@name"].(string), } case "comment": comments, _ := convertToSlice(value.(map[string]interface{})["line"]) var returnComments []string for i := range comments { returnComments = append(returnComments, comments[i].(map[string]interface{})["$"].(string)) } whois.Comments = returnComments case "originASes": originAS, _ := convertToSlice(value.(map[string]interface{})["originAS"]) var originASes []string for i := range originAS { originASes = append(originASes, originAS[i].(map[string]interface{})["$"].(string)) } whois.OriginASes = originASes case "parentNetRef": whois.ParentRefUrl = map[string]string{ "url": value.(map[string]interface{})["$"].(string), "handle": value.(map[string]interface{})["@handle"].(string), "name": value.(map[string]interface{})["@name"].(string), } case "registrationDate": whois.RegistrationDate = value.(map[string]interface{})["$"].(string) case "updateDate": whois.UpdateDate = value.(map[string]interface{})["$"].(string) case "netBlocks": netBlockList, err := convertToSlice(value.(map[string]interface{})["netBlock"]) if err != nil { fmt.Println("ERROR: ", err) } for i := range netBlockList { description := netBlockList[i].(map[string]interface{})["description"].(map[string]interface{})["$"].(string) endAddress := netBlockList[i].(map[string]interface{})["endAddress"].(map[string]interface{})["$"].(string) startAddress := netBlockList[i].(map[string]interface{})["startAddress"].(map[string]interface{})["$"].(string) blockType := netBlockList[i].(map[string]interface{})["type"].(map[string]interface{})["$"].(string) cidrLength := netBlockList[i].(map[string]interface{})["cidrLength"].(map[string]interface{})["$"].(string) netBlockObject := map[string]string{ "description": description, "startAddress": startAddress, "endAddress": endAddress, "cidrLength": cidrLength, "type": blockType, } returnNetBlocks = append(returnNetBlocks, netBlockObject) } whois.NetBlocks = returnNetBlocks } } return &whois, nil } func (*Whois) generateJson(whoisRecord *Whois, contactRecord *ContactRecord) ([]byte, error) { var returnJson ReturnJSON returnJson.WhoisRecord = whoisRecord returnJson.ContactRecord = contactRecord jsonOutput, err := json.MarshalIndent(&returnJson, "", "\t") if err != nil { fmt.Println("err:", err.Error()) return nil, err } return jsonOutput, nil } func convertToSlice(object interface{}) ([]interface{}, error) { switch v := object.(type) { case []interface{}: return object.([]interface{}), nil case interface{}: var returnInterfaceArray []interface{} = make([]interface{}, 1) returnInterfaceArray[0] = object return returnInterfaceArray, nil default: fmt.Println(v) return nil, nil } } func getAddressLines(rawJson interface{}) ([]string, error) { var streetAddress []string address, err := convertToSlice(rawJson.(map[string]interface{})["streetAddress"].(map[string]interface{})["line"]) if err != nil { return nil, err } for line := range address { //fmt.Printf("\nADDRESS LINE: %+v\n", address[line]) streetAddress = append(streetAddress, address[line].(map[string]interface{})["$"].(string)) } return streetAddress, nil }
package openapi import "encoding/json" // OpenAPI represents the root document object of // an OpenAPI document. type OpenAPI struct { OpenAPI string `json:"openapi" yaml:"openapi"` Info *Info `json:"info" yaml:"info"` Servers []*Server `json:"servers,omitempty" yaml:"servers,omitempty"` Paths Paths `json:"paths" yaml:"paths"` Components *Components `json:"components,omitempty" yaml:"components,omitempty"` Tags []*Tag `json:"tags,omitempty" yaml:"tags,omitempty"` Security []*SecurityRequirement `json:"security,omitempty" yaml:"security,omitempty"` XTagGroups []*XTagGroup `json:"x-tagGroups,omitempty" yaml:"x-tagGroups,omitempty"` } // Components holds a set of reusable objects for different // aspects of the specification. type Components struct { Schemas map[string]*SchemaOrRef `json:"schemas,omitempty" yaml:"schemas,omitempty"` Responses map[string]*ResponseOrRef `json:"responses,omitempty" yaml:"responses,omitempty"` Parameters map[string]*ParameterOrRef `json:"parameters,omitempty" yaml:"parameters,omitempty"` Examples map[string]*ExampleOrRef `json:"examples,omitempty" yaml:"examples,omitempty"` Headers map[string]*HeaderOrRef `json:"headers,omitempty" yaml:"headers,omitempty"` SecuritySchemes map[string]*SecuritySchemeOrRef `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"` } // Info represents the metadata of an API. type Info struct { Title string `json:"title" yaml:"title"` Description string `json:"description,omitempty" yaml:"description,omitempty"` TermsOfService string `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty"` Contact *Contact `json:"contact,omitempty" yaml:"contact,omitempty"` License *License `json:"license,omitempty" yaml:"license,omitempty"` Version string `json:"version" yaml:"version"` XLogo *XLogo `json:"x-logo,omitempty" yaml:"x-logo,omitempty"` } // Contact represents the the contact informations // exposed for an API. type Contact struct { Name string `json:"name,omitempty" yaml:"name,omitempty"` URL string `json:"url,omitempty" yaml:"url,omitempty"` Email string `json:"email,omitempty" yaml:"email,omitempty"` } // License represents the license informations // exposed for an API. type License struct { Name string `json:"name" yaml:"name"` URL string `json:"url,omitempty" yaml:"url,omitempty"` } // Server represents a server. type Server struct { URL string `json:"url" yaml:"url"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Variables map[string]*ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"` } // ServerVariable represents a server variable for server // URL template substitution. type ServerVariable struct { Enum []string `json:"enum,omitempty" yaml:"enum,omitempty"` Default string `json:"default" yaml:"default"` Description string `json:"description,omitempty" yaml:"description,omitempty"` } // Paths represents the relative paths to the individual // endpoints and their operations. type Paths map[string]*PathItem // PathItem describes the operations available on a single // API path. type PathItem struct { Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"` Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` GET *Operation `json:"get,omitempty" yaml:"get,omitempty"` PUT *Operation `json:"put,omitempty" yaml:"put,omitempty"` POST *Operation `json:"post,omitempty" yaml:"post,omitempty"` DELETE *Operation `json:"delete,omitempty" yaml:"delete,omitempty"` OPTIONS *Operation `json:"options,omitempty" yaml:"options,omitempty"` HEAD *Operation `json:"head,omitempty" yaml:"head,omitempty"` PATCH *Operation `json:"patch,omitempty" yaml:"patch,omitempty"` TRACE *Operation `json:"trace,omitempty" yaml:"trace,omitempty"` Servers []*Server `json:"servers,omitempty" yaml:"servers,omitempty"` Parameters []*ParameterOrRef `json:"parameters,omitempty" yaml:"parameters,omitempty"` } // Reference is a simple object to allow referencing // other components in the specification, internally and // externally. type Reference struct { Ref string `json:"$ref" yaml:"$ref"` } // Parameter describes a single operation parameter. type Parameter struct { Name string `json:"name" yaml:"name"` In string `json:"in" yaml:"in"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Required bool `json:"required,omitempty" yaml:"required,omitempty"` Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` Schema *SchemaOrRef `json:"schema,omitempty" yaml:"schema,omitempty"` Style string `json:"style,omitempty" yaml:"style,omitempty"` Explode bool `json:"explode,omitempty" yaml:"explode,omitempty"` } // ParameterOrRef represents a Parameter that can be inlined // or referenced in the API description. type ParameterOrRef struct { *Parameter *Reference } // MarshalYAML implements yaml.Marshaler for ParameterOrRef. func (por *ParameterOrRef) MarshalYAML() (interface{}, error) { if por.Parameter != nil { return por.Parameter, nil } return por.Reference, nil } // RequestBody represents a request body. type RequestBody struct { Description string `json:"description,omitempty" yaml:"description,omitempty"` Content map[string]*MediaType `json:"content" yaml:"content"` Required bool `json:"required,omitempty" yaml:"required,omitempty"` } // SchemaOrRef represents a Schema that can be inlined // or referenced in the API description. type SchemaOrRef struct { *Schema *Reference } // MarshalYAML implements yaml.Marshaler for SchemaOrRef. func (sor *SchemaOrRef) MarshalYAML() (interface{}, error) { if sor.Schema != nil { return sor.Schema, nil } return sor.Reference, nil } // Schema represents the definition of input and output data // types of the API. type Schema struct { // The following properties are taken from the JSON Schema // definition but their definitions were adjusted to the // OpenAPI Specification. Type string `json:"type,omitempty" yaml:"type,omitempty"` AllOf *SchemaOrRef `json:"allOf,omitempty" yaml:"allOf,omitempty"` OneOf *SchemaOrRef `json:"oneOf,omitempty" yaml:"oneOf,omitempty"` AnyOf *SchemaOrRef `json:"anyOf,omitempty" yaml:"anyOf,omitempty"` Items *SchemaOrRef `json:"items,omitempty" yaml:"items,omitempty"` Properties map[string]*SchemaOrRef `json:"properties,omitempty" yaml:"properties,omitempty"` AdditionalProperties *SchemaOrRef `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Format string `json:"format,omitempty" yaml:"format,omitempty"` Default interface{} `json:"default,omitempty" yaml:"default,omitempty"` Example interface{} `json:"example,omitempty" yaml:"example,omitempty"` // The following properties are taken directly from the // JSON Schema definition and follow the same specifications Title string `json:"title,omitempty" yaml:"title,omitempty"` MultipleOf int `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"` Maximum int `json:"maximum,omitempty" yaml:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"` Minimum int `json:"minimum,omitempty" yaml:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"` MaxLength int `json:"maxLength,omitempty" yaml:"maxLength,omitempty"` MinLength int `json:"minLength,omitempty" yaml:"minLength,omitempty"` Pattern string `json:"pattern,omitempty" yaml:"pattern,omitempty"` MaxItems int `json:"maxItems,omitempty" yaml:"maxItems,omitempty"` MinItems int `json:"minItems,omitempty" yaml:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"` MaxProperties int `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"` MinProperties int `json:"minProperties,omitempty" yaml:"minProperties,omitempty"` Required []string `json:"required,omitempty" yaml:"required,omitempty"` Enum []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"` Nullable bool `json:"nullable,omitempty" yaml:"nullable,omitempty"` Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` } // Operation describes an API operation on a path. type Operation struct { Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` ID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` Parameters []*ParameterOrRef `json:"parameters,omitempty" yaml:"parameters,omitempty"` RequestBody *RequestBody `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` Responses Responses `json:"responses,omitempty" yaml:"responses,omitempty"` Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` Servers []*Server `json:"servers,omitempty" yaml:"servers,omitempty"` Security []*SecurityRequirement `json:"security" yaml:"security"` XCodeSamples []*XCodeSample `json:"x-codeSamples,omitempty" yaml:"x-codeSamples,omitempty"` XInternal bool `json:"x-internal,omitempty" yaml:"x-internal,omitempty"` } // A workaround for missing omitnil functionality. // Explicitely omit the Security field from marshaling when it is nil, but not when empty. type operationNilOmitted struct { Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` ID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` Parameters []*ParameterOrRef `json:"parameters,omitempty" yaml:"parameters,omitempty"` RequestBody *RequestBody `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` Responses Responses `json:"responses,omitempty" yaml:"responses,omitempty"` Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` Servers []*Server `json:"servers,omitempty" yaml:"servers,omitempty"` XCodeSamples []*XCodeSample `json:"x-codeSamples,omitempty" yaml:"x-codeSamples,omitempty"` XInternal bool `json:"x-internal,omitempty" yaml:"x-internal,omitempty"` } // MarshalYAML implements yaml.Marshaler for Operation. // Needed to marshall empty but non-null SecurityRequirements. func (o *Operation) MarshalYAML() (interface{}, error) { if o.Security == nil { return omitOperationNilFields(o), nil } return o, nil } // MarshalJSON excludes empty but non-null SecurityRequirements. func (o *Operation) MarshalJSON() ([]byte, error) { if o.Security == nil { return json.Marshal(omitOperationNilFields(o)) } return json.Marshal(*o) } func omitOperationNilFields(o *Operation) *operationNilOmitted { return &operationNilOmitted{ Tags: o.Tags, Summary: o.Summary, Description: o.Description, ID: o.ID, Parameters: o.Parameters, RequestBody: o.RequestBody, Responses: o.Responses, Deprecated: o.Deprecated, Servers: o.Servers, XCodeSamples: o.XCodeSamples, XInternal: o.XInternal, } } // Responses represents a container for the expected responses // of an opration. It maps a HTTP response code to the expected // response. type Responses map[string]*ResponseOrRef // ResponseOrRef represents a Response that can be inlined // or referenced in the API description. type ResponseOrRef struct { *Response *Reference } // MarshalYAML implements yaml.Marshaler for ResponseOrRef. func (ror *ResponseOrRef) MarshalYAML() (interface{}, error) { if ror.Response != nil { return ror.Response, nil } return ror.Reference, nil } // Response describes a single response from an API. type Response struct { Description string `json:"description,omitempty" yaml:"description,omitempty"` Headers map[string]*HeaderOrRef `json:"headers,omitempty" yaml:"headers,omitempty"` Content map[string]*MediaTypeOrRef `json:"content,omitempty" yaml:"content,omitempty"` } // HeaderOrRef represents a Header that can be inlined // or referenced in the API description. type HeaderOrRef struct { *Header *Reference } // MarshalYAML implements yaml.Marshaler for HeaderOrRef. func (hor *HeaderOrRef) MarshalYAML() (interface{}, error) { if hor.Header != nil { return hor.Header, nil } return hor.Reference, nil } // Header represents an HTTP header. type Header struct { Description string `json:"description,omitempty" yaml:"description,omitempty"` Required bool `json:"required,omitempty" yaml:"required,omitempty"` Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` Schema *SchemaOrRef `json:"schema,omitempty" yaml:"schema,omitempty"` } // MediaTypeOrRef represents a MediaType that can be inlined // or referenced in the API description. type MediaTypeOrRef struct { *MediaType *Reference } // MarshalYAML implements yaml.Marshaler for MediaTypeOrRef. func (mtor *MediaTypeOrRef) MarshalYAML() (interface{}, error) { if mtor.MediaType != nil { return mtor.MediaType, nil } return mtor.Reference, nil } // MediaType represents the type of a media. type MediaType struct { Schema *SchemaOrRef `json:"schema" yaml:"schema"` Example interface{} `json:"example,omitempty" yaml:"example,omitempty"` Examples map[string]*ExampleOrRef `json:"examples,omitempty" yaml:"examples,omitempty"` Encoding map[string]*Encoding `json:"encoding,omitempty" yaml:"encoding,omitempty"` } // ExampleOrRef represents an Example that can be inlined // or referenced in the API description. type ExampleOrRef struct { *Example *Reference } // MarshalYAML implements yaml.Marshaler for ExampleOrRef. func (eor *ExampleOrRef) MarshalYAML() (interface{}, error) { if eor.Example != nil { return eor.Example, nil } return eor.Reference, nil } // Example represents the example of a media type. type Example struct { Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` Value interface{} `json:"value,omitempty" yaml:"value,omitempty"` ExternalValue string `json:"externalValue,omitempty" yaml:"externalValue,omitempty"` } // Encoding represents a single encoding definition // applied to a single schema property. type Encoding struct { ContentType string `json:"contentType,omitempty" yaml:"contentType,omitempty"` Headers map[string]*HeaderOrRef `json:"headers,omitempty" yaml:"headers,omitempty"` Style string `json:"style,omitempty" yaml:"style,omitempty"` Explode bool `json:"explode,omitempty" yaml:"explode,omitempty"` AllowReserved bool `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"` } // Tag represents the metadata of a single tag. type Tag struct { Name string `json:"name" yaml:"name"` Description string `json:"description,omitempty" yaml:"description,omitempty"` } // SecuritySchemeOrRef represents a SecurityScheme that can be inlined // or referenced in the API description. type SecuritySchemeOrRef struct { *SecurityScheme *Reference } // MarshalYAML implements yaml.Marshaler for SecuritySchemeOrRef. func (sor *SecuritySchemeOrRef) MarshalYAML() (interface{}, error) { if sor.SecurityScheme != nil { return sor.SecurityScheme, nil } return sor.Reference, nil } // SecurityScheme represents a security scheme that can be used by an operation. type SecurityScheme struct { Type string `json:"type,omitempty" yaml:"type,omitempty"` Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"` BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"` Description string `json:"description,omitempty" yaml:"description,omitempty"` In string `json:"in,omitempty" yaml:"in,omitempty"` Name string `json:"name,omitempty" yaml:"name,omitempty"` OpenIDConnectURL string `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"` Flows *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"` } // OAuthFlows represents all the supported OAuth flows. type OAuthFlows struct { Implicit *OAuthFlow `json:"implicit,omitempty" yaml:"implicit,omitempty"` Password *OAuthFlow `json:"password,omitempty" yaml:"password,omitempty"` ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty"` AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty"` } // OAuthFlow represents an OAuth security scheme. type OAuthFlow struct { AuthorizationURL string `json:"authorizationUrl,omitempty" yaml:"authorizationUrl,omitempty"` TokenURL string `json:"tokenUrl,omitempty" yaml:"tokenUrl,omitempty"` RefreshURL string `json:"refreshUrl,omitempty" yaml:"refreshUrl,omitempty"` Scopes map[string]string `json:"scopes,omitempty" yaml:"scopes,omitempty"` } // MarshalYAML implements yaml.Marshaler for OAuthFlow. func (f OAuthFlow) MarshalYAML() ([]byte, error) { type flow OAuthFlow if f.Scopes == nil { // The field is REQUIRED and MAY be empty according to the spec. f.Scopes = map[string]string{} } return json.Marshal(flow(f)) } // SecurityRequirement represents the security object in the API specification. type SecurityRequirement map[string][]string // XLogo represents the information about the x-logo extension. // See: https://github.com/Redocly/redoc/blob/master/docs/redoc-vendor-extensions.md#x-logo type XLogo struct { URL string `json:"url,omitempty" yaml:"url,omitempty"` BackgroundColor string `json:"backgroundColor,omitempty" yaml:"backgroundColor,omitempty"` AltText string `json:"altText,omitempty" yaml:"altText,omitempty"` Href string `json:"href,omitempty" yaml:"href,omitempty"` } // XTagGroup represents the information about the x-tagGroups extension. // See: https://github.com/Redocly/redoc/blob/master/docs/redoc-vendor-extensions.md#x-taggroups type XTagGroup struct { Name string `json:"name,omitempty" yaml:"name,omitempty"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` } // XCodeSample represents the information about the x-codeSample extension. // See: https://github.com/Redocly/redoc/blob/master/docs/redoc-vendor-extensions.md#x-codesamples type XCodeSample struct { Lang string `json:"lang,omitempty" yaml:"lang,omitempty"` Label string `json:"label,omitempty" yaml:"label,omitempty"` Source string `json:"source,omitempty" yaml:"source,omitempty"` }
package curd import ( "testing" "github.com/stretchr/testify/assert" ) var ( db = NewDB( "test", "test", "", "3306", "test", ) ) type Order struct { ID int64 `db:"id"` Status int `db:"status"` } func TestSelect(t *testing.T) { ins := make([]*Order, 0) err := db.R( "order", []string{"id", "status"}, map[string]interface{}{"id": 1}, &ins, ) assert.Nil(t, err) assert.Equal(t, []*Order{ &Order{ID: 1, Status: 3}, }, ins) } func TestSelectPage(t *testing.T) { ins := make([]*Order, 0) err := db.RPage( "order", 1, 5, []string{"id", "status"}, map[string]interface{}{"status": 2}, &ins, ) assert.Nil(t, err) assert.Equal(t, 5, len(ins)) ins = make([]*Order, 0) err = db.RPage( "order", 1, 10, []string{"id", "status"}, map[string]interface{}{"status": 2}, &ins, ) assert.Nil(t, err) assert.Equal(t, 10, len(ins)) } func TestInsert(t *testing.T) { oldCount := 0 err := db.Get(&oldCount, "select COUNT(*) FROM `user`") assert.Nil(t, err) _, err = db.C( "user", map[string]interface{}{ "name": "314156", }, ) assert.Nil(t, err) newCount := 0 _ = db.Get(&newCount, "select COUNT(*) FROM `user`") assert.Equal(t, newCount, oldCount+1) _, err = db.D( "user", map[string]interface{}{ "name": "314156", }, ) assert.Nil(t, err) _ = db.Get(&newCount, "select COUNT(*) FROM `user`") assert.Equal(t, newCount, oldCount) }
package logger type multiBackend struct { bes []Backend } func NewMultiBackend(bes ...Backend) (*multiBackend, error) { var b multiBackend b.bes = bes return &b, nil } func (self *multiBackend) Log(s Severity, msg []byte) { for _, be := range self.bes { be.Log(s, msg) } } func (self *multiBackend) Close() { for _, be := range self.bes { be.Close() } }
package main import ( "fmt" "net/http" "os" "time" "github.com/getsentry/sentry-go" "github.com/go-chi/chi" "github.com/joho/godotenv" "github.com/kelseyhightower/envconfig" "go.uber.org/zap" "rayyildiz.dev/app/internal/infra" // FIXME if your change your module name in `go.mod` file, don't forget to change import ) func init() { godotenv.Load() } func main() { var spec infra.Specification err := envconfig.Process("app", &spec) if err != nil { fmt.Printf("could not load config, %v", err) os.Exit(1) } log := infra.NewLogger(spec.Debug) defer sentry.Flush(time.Second * 5) db, err := infra.NewDatabase(spec.PostgresConnection) if err != nil { log.Fatal("could not initialize database", zap.Error(err)) } defer db.Close() r := infra.NewRouter() port := fmt.Sprintf("%d", spec.Port) if port == "" { port = "4000" } // Handlers r.Route("/api", func(r chi.Router) { }) log.Info("server is starting", zap.String("port", port)) if err := http.ListenAndServe(":"+port, r); err != nil { log.Error("could not start server", zap.String("port", port), zap.Error(err)) } }
package main import "github.com/torbensky/go-logfilter/example" func main() { example.Run() /* Output: debug:File1 info:File1 warning:File1 error:File1 warning:File2 error:File2 */ }
package gex import ( "io" "io/ioutil" "log" "os" "github.com/izumin5210/execx" "github.com/pkg/errors" "github.com/spf13/afero" "github.com/izumin5210/gex/pkg/manager" "github.com/izumin5210/gex/pkg/manager/dep" "github.com/izumin5210/gex/pkg/manager/mod" "github.com/izumin5210/gex/pkg/tool" ) // Config specifies the configration for managing development tools. type Config struct { OutWriter io.Writer ErrWriter io.Writer InReader io.Reader FS afero.Fs Exec *execx.Executor WorkingDir string RootDir string ManifestName string BinDirName string ManagerType manager.Type Verbose bool Logger *log.Logger } // Default contains default configuration. var Default = createDefaultConfig() func createDefaultConfig() *Config { wd, _ := os.Getwd() if wd == "" { wd = "." } cfg := &Config{ OutWriter: os.Stdout, ErrWriter: os.Stderr, InReader: os.Stdin, FS: afero.NewOsFs(), Exec: execx.New(), WorkingDir: wd, ManifestName: "tools.go", BinDirName: "bin", Logger: log.New(ioutil.Discard, "", 0), } cfg.ManagerType, cfg.RootDir = manager.DetectType(cfg.WorkingDir, cfg.FS, cfg.Exec) return cfg } // Create creates a new instance of tool.Repository to manage developemnt tools. func (c *Config) Create() (tool.Repository, error) { c.setDefaultsIfNeeded() manager, executor, err := c.createManager() if err != nil { return nil, errors.WithStack(err) } return tool.NewRepository(executor, manager, c.ManagerType, &tool.Config{ FS: c.FS, WorkingDir: c.WorkingDir, RootDir: c.RootDir, ManifestName: c.ManifestName, BinDirName: c.BinDirName, Verbose: c.Verbose, Log: c.Logger, }), nil } func (c *Config) setDefaultsIfNeeded() { d := createDefaultConfig() if c.OutWriter == nil { c.OutWriter = d.OutWriter } if c.ErrWriter == nil { c.ErrWriter = d.ErrWriter } if c.InReader == nil { c.InReader = d.InReader } if c.FS == nil { c.FS = d.FS } if c.Exec == nil { c.Exec = d.Exec } if c.WorkingDir == "" { c.WorkingDir = d.WorkingDir } if c.ManifestName == "" { c.ManifestName = d.ManifestName } if c.BinDirName == "" { c.BinDirName = d.BinDirName } if c.Logger == nil { c.Logger = d.Logger } if c.ManagerType == manager.TypeUnknown { c.ManagerType, c.RootDir = manager.DetectType(c.WorkingDir, c.FS, c.Exec) } if rootDir, err := manager.FindRoot(c.WorkingDir, c.FS, c.ManifestName); err == nil { if len(rootDir) > len(c.RootDir) { c.RootDir = rootDir } } } func (c *Config) createManager() ( manager.Interface, manager.Executor, error, ) { executor := manager.NewExecutor(c.Exec, c.OutWriter, c.ErrWriter, c.InReader, c.WorkingDir, c.Logger) var ( m manager.Interface ) switch c.ManagerType { case manager.TypeModules: m = mod.NewManager(executor) case manager.TypeDep: m = dep.NewManager(executor, c.RootDir, c.WorkingDir) default: return nil, nil, errors.New("failed to detect a dependencies management tool") } return m, executor, nil }
package config import ( "encoding/json" "io/ioutil" ) type Target struct { Host string JQuery string } type Config struct { IP string Port string Routes map[string]Target AllowedQueryParameters []string TimePerRequest int64 BurstRequests int64 } func LoadConfig(path string) (*Config, error) { raw, err := ioutil.ReadFile(path) if err != nil { return nil, err } var conf Config err = json.Unmarshal(raw, &conf) if err != nil { return nil, err } return &conf, nil }
package container import ( "os" "syscall" "time" "github.com/criyle/go-sandbox/pkg/mount" "github.com/criyle/go-sandbox/pkg/rlimit" "github.com/criyle/go-sandbox/pkg/seccomp" "github.com/criyle/go-sandbox/runner" ) // cmd is the control message send into container type cmd struct { DeleteCmd *deleteCmd // delete argument ExecCmd *execCmd // execve argument ConfCmd *confCmd // to set configuration OpenCmd []OpenCmd // open argument Cmd cmdType // type of the cmd } // OpenCmd correspond to a single open syscall type OpenCmd struct { Path string Flag int Perm os.FileMode } // deleteCmd stores delete command type deleteCmd struct { Path string } // execCmd stores execve parameter type execCmd struct { Argv []string // execve argv Env []string // execve env RLimits []rlimit.RLimit // execve posix rlimit Seccomp seccomp.Filter // seccomp filter FdExec bool // if use fexecve (fd[0] as exec) CTTY bool // if set CTTY } // confCmd stores conf parameter type confCmd struct { Conf containerConfig } // ContainerConfig set the container config type containerConfig struct { WorkDir string HostName string DomainName string ContainerRoot string Mounts []mount.Mount SymbolicLinks []SymbolicLink MaskPaths []string ContainerUID int ContainerGID int Cred bool UnshareCgroup bool } // reply is the reply message send back to controller type reply struct { Error *errorReply // nil if no error ExecReply *execReply } // errorReply stores error returned back from container type errorReply struct { Errno *syscall.Errno Msg string } // execReply stores execve result type execReply struct { ExitStatus int // waitpid exit status Status runner.Status // return status Time time.Duration // waitpid user CPU (ns) Memory runner.Size // waitpid user memory (byte) } func (e *errorReply) Error() string { return e.Msg }
package model import ( "time" ) // AuthenticationAttempt represents an authentication attempt row in the database. type AuthenticationAttempt struct { ID int `db:"id"` Time time.Time `db:"time"` Successful bool `db:"successful"` Banned bool `db:"banned"` Username string `db:"username"` Type string `db:"auth_type"` RemoteIP NullIP `db:"remote_ip"` RequestURI string `db:"request_uri"` RequestMethod string `db:"request_method"` }
package pipeline import ( "sync" "github.com/sherifabdlnaby/prism/app/pipeline/node" "github.com/sherifabdlnaby/prism/pkg/job" ) //recoverAsyncJobs checks pipeline's persisted unfinished jobs and re-apply them func (p *pipeline) recoverAsyncJobs() error { JobsList, err := p.bucket.GetAllAsyncJobs() if err != nil { p.logger.Infow("error occurred while reading in-disk jobs", "error", err.Error()) return err } if len(JobsList) <= 0 { return nil } wg := sync.WaitGroup{} p.logger.Infof("re-applying %d async requests found", len(JobsList)) for _, Job := range JobsList { wg.Add(1) go func(Job job.Async) { defer wg.Done() // Do the Job p.recoverAsyncJob(&Job) }(Job) } //cleanup after all jobs are done go func() { wg.Wait() p.bucket.Cleanup() p.logger.Info("finished processing jobs in persistent queue") }() return nil } func (p *pipeline) recoverAsyncJob(asyncJob *job.Async) { p.startAsyncJob(asyncJob) p.handleJob(asyncJob.Job, node.ID(asyncJob.NodeID)) }
package recipient type RecipientType string const ( Server RecipientType = "server" Namespace RecipientType = "namespace" Workflow RecipientType = "workflow" Instance RecipientType = "instance" Mirror RecipientType = "mirror" ) func (rt RecipientType) String() string { return string(rt) }
package vo type PesertaID string type PesertaIDRequest struct { GenerateID func() string } func NewPesertaID(req PesertaIDRequest) (PesertaID, error) { obj := PesertaID(req.GenerateID()) return obj, nil } func (r PesertaID) String() string { return string(r) }
package catm import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00300104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catm.003.001.04 Document"` Message *AcceptorConfigurationUpdateV04 `xml:"AccptrCfgtnUpd"` } func (d *Document00300104) AddMessage() *AcceptorConfigurationUpdateV04 { d.Message = new(AcceptorConfigurationUpdateV04) return d.Message } // Update of the acceptor configuration to be downloaded by the terminal management system. type AcceptorConfigurationUpdateV04 struct { // Set of characteristics related to the transfer of the acceptor parameters. Header *iso20022.Header14 `xml:"Hdr"` // Acceptor configuration to be downloaded from the terminal management system. AcceptorConfiguration *iso20022.AcceptorConfiguration4 `xml:"AccptrCfgtn"` // Trailer of the message containing a MAC or a digital signature. SecurityTrailer *iso20022.ContentInformationType12 `xml:"SctyTrlr"` } func (a *AcceptorConfigurationUpdateV04) AddHeader() *iso20022.Header14 { a.Header = new(iso20022.Header14) return a.Header } func (a *AcceptorConfigurationUpdateV04) AddAcceptorConfiguration() *iso20022.AcceptorConfiguration4 { a.AcceptorConfiguration = new(iso20022.AcceptorConfiguration4) return a.AcceptorConfiguration } func (a *AcceptorConfigurationUpdateV04) AddSecurityTrailer() *iso20022.ContentInformationType12 { a.SecurityTrailer = new(iso20022.ContentInformationType12) return a.SecurityTrailer }
package Responsibility_Chain import "strconv" type Handler interface { Handler(handerID int) string } type handler struct { name string next Handler handlerID int } func NewHandler(name string,next Handler,handlerID int) *handler { return &handler{ name:name, next:next, handlerID:handlerID, } } func (h *handler) Handler(handlerID int) string { if h.handlerID == handlerID { return h.name+" handled " + strconv.Itoa(handlerID) } if h.next == nil { return "" } return h.next.Handler(handlerID) }
package compute import ( "encoding/json" "fmt" "net/http" "net/url" ) // VIPPoolMember represents a combination of node and port as a member of a VIP pool. type VIPPoolMember struct { ID string `json:"id"` Pool EntityReference `json:"pool"` Node VIPNodeReference `json:"node"` Port *int `json:"port,omitempty"` Status string `json:"status"` State string `json:"state"` NetworkDomainID string `json:"networkDomainId"` DatacenterID string `json:"datacenterId"` CreateTime string `json:"createTime"` } // VIPPoolMembers represents a page of VIPPoolMember results. type VIPPoolMembers struct { Items []VIPPoolMember `json:"poolMember"` PagedResult } // Request body for adding a VIP pool member. type addPoolMember struct { PoolID string `json:"poolId"` NodeID string `json:"nodeId"` Status string `json:"status"` Port *int `json:"port,omitempty"` } // Request body for updating a VIP pool member. type editPoolMember struct { ID string `json:"id"` Status string `json:"status"` } // Request body for removing a VIP pool member. type removePoolMember struct { ID string `json:"id"` } // ListVIPPoolMembers retrieves a list of all members of the specified VIP pool. func (client *Client) ListVIPPoolMembers(poolID string, paging *Paging) (members *VIPPoolMembers, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/networkDomainVip/poolMember?poolId=%s&%s", url.QueryEscape(organizationID), url.QueryEscape(poolID), paging.EnsurePaging().toQueryParameters(), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } return nil, apiResponse.ToError("Request to list members of VIP pool '%s' failed with status code %d (%s): %s", poolID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } members = &VIPPoolMembers{} err = json.Unmarshal(responseBody, members) if err != nil { return nil, err } return members, nil } // ListVIPPoolMembershipsInNetworkDomain retrieves a list of all VIP pool memberships of the specified network domain. func (client *Client) ListVIPPoolMembershipsInNetworkDomain(networkDomainID string, paging *Paging) (members *VIPPoolMembers, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/networkDomainVip/poolMember?networkDomainId=%s&%s", url.QueryEscape(organizationID), url.QueryEscape(networkDomainID), paging.EnsurePaging().toQueryParameters(), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } return nil, apiResponse.ToError("Request to list all VIP pool memberships in network domain '%s' failed with status code %d (%s): %s", networkDomainID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } members = &VIPPoolMembers{} err = json.Unmarshal(responseBody, members) if err != nil { return nil, err } return members, nil } // GetVIPPoolMember retrieves the VIP pool member with the specified Id. // Returns nil if no VIP pool member is found with the specified Id. func (client *Client) GetVIPPoolMember(id string) (member *VIPPoolMember, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/networkDomainVip/poolMember/%s", url.QueryEscape(organizationID), url.QueryEscape(id), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } if apiResponse.ResponseCode == ResponseCodeResourceNotFound { return nil, nil // Not an error, but was not found. } return nil, apiResponse.ToError("Request to retrieve VIP pool with Id '%s' failed with status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } member = &VIPPoolMember{} err = json.Unmarshal(responseBody, member) if err != nil { return nil, err } return member, nil } // AddVIPPoolMember adds a VIP node as a member of a VIP pool. // State must be one of VIPNodeStatusEnabled, VIPNodeStatusDisabled, or VIPNodeStatusDisabled // Returns the member ID (uniquely identifies this combination of node, pool, and port). func (client *Client) AddVIPPoolMember(poolID string, nodeID string, status string, port *int) (poolMemberID string, err error) { organizationID, err := client.getOrganizationID() if err != nil { return "", err } requestURI := fmt.Sprintf("%s/networkDomainVip/addPoolMember", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &addPoolMember{ PoolID: poolID, NodeID: nodeID, Status: status, Port: port, }) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return "", err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return "", err } if statusCode != http.StatusOK { return "", apiResponse.ToError("Request to add VIP node '%s' as a member of pool '%s' failed with status code %d (%s): %s", nodeID, poolID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } // Expected: "info" { "name": "poolMemberId", "value": "the-Id-of-the-new-pool-member" } poolMemberIDMessage := apiResponse.GetFieldMessage("poolMemberId") if poolMemberIDMessage == nil { return "", apiResponse.ToError("Received an unexpected response (missing 'poolMemberId') with status code %d (%s): %s", statusCode, apiResponse.ResponseCode, apiResponse.Message) } return *poolMemberIDMessage, nil } // EditVIPPoolMember updates the status of an existing VIP pool member. // status can be VIPNodeStatusEnabled, VIPNodeStatusDisabled, or VIPNodeStatusForcedOffline func (client *Client) EditVIPPoolMember(id string, status string) error { organizationID, err := client.getOrganizationID() if err != nil { return err } requestURI := fmt.Sprintf("%s/networkDomainVip/editPoolMember", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &editPoolMember{ ID: id, Status: status, }) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return err } if statusCode != http.StatusOK { return apiResponse.ToError("Request to edit VIP pool member '%s' failed with status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } return nil } // RemoveVIPPoolMember removes a VIP pool member. func (client *Client) RemoveVIPPoolMember(id string) error { organizationID, err := client.getOrganizationID() if err != nil { return err } requestURI := fmt.Sprintf("%s/networkDomainVip/removePoolMember", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &removePoolMember{id}) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return err } if statusCode != http.StatusOK { return apiResponse.ToError("Request to remove member '%s' from its pool failed with status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } return nil }
package restserver import "github.com/prometheus/client_golang/prometheus" var metricLabelList = []string{"user", "repo", "type"} var metricBlobWriteTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_write_total", Help: "Total number of blobs written", }, metricLabelList, ) var metricBlobWriteBytesTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_write_bytes_total", Help: "Total number of bytes written to blobs", }, metricLabelList, ) var metricBlobReadTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_read_total", Help: "Total number of blobs read", }, metricLabelList, ) var metricBlobReadBytesTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_read_bytes_total", Help: "Total number of bytes read from blobs", }, metricLabelList, ) var metricBlobDeleteTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_delete_total", Help: "Total number of blobs deleted", }, metricLabelList, ) var metricBlobDeleteBytesTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "rest_server_blob_delete_bytes_total", Help: "Total number of bytes of blobs deleted", }, metricLabelList, ) func init() { // These are always initialized, but only updated if Config.Prometheus is set prometheus.MustRegister(metricBlobWriteTotal) prometheus.MustRegister(metricBlobWriteBytesTotal) prometheus.MustRegister(metricBlobReadTotal) prometheus.MustRegister(metricBlobReadBytesTotal) prometheus.MustRegister(metricBlobDeleteTotal) prometheus.MustRegister(metricBlobDeleteBytesTotal) }
package main func main() { } var keys = map[byte]bool{ 'a': true, 'e': true, 'i': true, 'o': true, 'u': true, } func maxVowels(s string, k int) int { left, right := 0, 0 mx := 0 win := 0 for right < len(s) { if keys[s[right]] { win++ } right++ for right-left > k { if keys[s[left]] { win-- } left++ } if win > mx { mx = win } } return mx }
package ctx type ReqId struct { RequestId string CurrentRpcId string NextSubRpcNo int } type Context struct { ReqId ReqId Data map[string]string TimeLimit TimeLimit TTL TTL } func NewContext(reqId, currentRpcId string, timelimit TimeLimit, ttl TTL) *Context { return &Context{ ReqId: ReqId{ RequestId: reqId, CurrentRpcId: currentRpcId, NextSubRpcNo: 1, }, Data: make(map[string]string), TimeLimit: timelimit, TTL: ttl, } } type RpcContext struct { RequestId string `ctxfield:"requestId"` RpcId string `ctxfield:"rpcId"` Data map[string]string `ctxfield:"data"` AppName string `ctxfield:"appName"` CallerNodeId string `ctxfield:"callerNodeId"` // automatic filled by Client not by caller TTL byte `ctxfield:"ttl"` MaxTTL byte `ctxfield:"maxTtl"` RouteRule []byte `ctxfield:"routeRule"` }
package triviabot import ( "encoding/json" "errors" "fmt" "html" "math/rand" "net/http" "strings" "time" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/keybase1" "github.com/malware-unicorn/managed-bots/base" ) var eligibleCategories = []int{9, 10, 11, 12, 14, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27} type apiQuestion struct { Category string Difficulty string Question string CorrectAnswer string `json:"correct_answer"` IncorrectAnswers []string `json:"incorrect_answers"` } type apiResponse struct { ResponseCode int `json:"response_code"` Results []apiQuestion } type apiTokenResponse struct { ResponseCode int Token string } type question struct { category string difficulty string question string answers []string correctAnswer int } func newQuestion(aq apiQuestion) question { a := append([]string{aq.CorrectAnswer}, aq.IncorrectAnswers...) rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) correctAnswer := 0 for index, answer := range a { if answer == aq.CorrectAnswer { correctAnswer = index break } } for index := range a { a[index] = html.UnescapeString(a[index]) } return question{ category: aq.Category, difficulty: aq.Difficulty, question: html.UnescapeString(aq.Question), answers: a, correctAnswer: correctAnswer, } } func (q question) Answer() string { return q.answers[q.correctAnswer] } func (q question) String() (res string) { res = fmt.Sprintf(`*Question:* %s Difficulty: %s Category: %s `, q.question, q.difficulty, q.category) var strAnswers []string for index, answer := range q.answers { strAnswers = append(strAnswers, fmt.Sprintf("%s %s", base.NumberToEmoji(index+1), answer)) } return res + strings.Join(strAnswers, "\n") } const defaultTotal = 10 type answer struct { selection int msgID chat1.MessageID username string } type session struct { *base.DebugOutput kbc *kbchat.API db *DB convID chat1.ConvIDStr numUsersInConv int curQuestion *question curMsgID chat1.MessageID answerCh chan answer stopCh chan struct{} dupCheck map[string]bool } func newSession(kbc *kbchat.API, debugConfig *base.ChatDebugOutputConfig, db *DB, convID chat1.ConvIDStr) *session { return &session{ DebugOutput: base.NewDebugOutput("session", debugConfig), db: db, convID: convID, answerCh: make(chan answer, 10), kbc: kbc, stopCh: make(chan struct{}), dupCheck: make(map[string]bool), } } func (s *session) getCategory() int { return eligibleCategories[rand.Intn(len(eligibleCategories))] } func (s *session) getAPIToken() (string, error) { resp, err := http.Get("https://opentdb.com/api_token.php?command=request") if err != nil { return "", err } defer resp.Body.Close() var apiResp apiTokenResponse decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&apiResp); err != nil { return "", err } if apiResp.ResponseCode != 0 { return "", fmt.Errorf("error from token API: %d", apiResp.ResponseCode) } return apiResp.Token, nil } var errForceAPI = errors.New("API token fetch requested") func (s *session) getToken(forceAPI bool) (token string, err error) { if !forceAPI { token, err = s.db.GetAPIToken(s.convID) } else { err = errForceAPI } if err != nil { s.Debug("getToken: failed to get token from DB: %s", err) if token, err = s.getAPIToken(); err != nil { s.ChatErrorf(s.convID, "getToken: failed to get token from API: %s", err) return "", err } if err := s.db.SetAPIToken(s.convID, token); err != nil { s.Errorf("getToken: failed to set token in DB: %s", err) } } else { s.Debug("getToken: DB hit") } return token, nil } var errTokenExpired = errors.New("token expired") func (s *session) getNextQuestion() error { token, err := s.getToken(false) if err != nil { s.Errorf("getNextQuestion: failed to get token: %s", err) return err } var apiResp apiResponse getQuestion := func(token string) error { url := fmt.Sprintf("https://opentdb.com/api.php?amount=1&category=%d&token=%s&type=multiple", s.getCategory(), token) s.Debug("getNextQuestion: url: %s", url) resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&apiResp); err != nil { return err } if apiResp.ResponseCode == 3 { // need new token return errTokenExpired } return nil } if err := getQuestion(token); err != nil { if err == errTokenExpired { s.Debug("getNextQuestion: token expired, trying again") if token, err = s.getToken(true); err != nil { s.Errorf("getNextQuestion: failed to get token: %s", err) return err } if err := getQuestion(token); err != nil { s.Errorf("getNextQuestion: failed to get next question after token error: %s", err) return err } } } if len(apiResp.Results) > 0 { q := newQuestion(apiResp.Results[0]) s.curQuestion = &q res, err := s.kbc.ListMembersByConvID(s.convID) if err != nil { return err } // ignore bot users here s.numUsersInConv = len(res.Owners) + len(res.Admins) + len(res.Writers) + len(res.Readers) // If we're not a bot member exclude us from the member count. if !s.isBotRole(res) { s.numUsersInConv-- } } return nil } func (s *session) isBotRole(members keybase1.TeamMembersDetails) bool { for _, member := range append(members.Bots, members.RestrictedBots...) { if member.Username == s.kbc.GetUsername() { return true } } return false } func (s *session) askQuestion() error { if s.curQuestion == nil { s.Debug("askQuestion: current question nil, bailing") return errors.New("no question to ask") } q := *s.curQuestion s.Debug("askQuestion: question: %s answer: %d", q.question, q.correctAnswer+1) sendRes, err := s.kbc.SendMessageByConvID(s.convID, q.String()) if err != nil { s.ChatErrorf(s.convID, "askQuestion: failed to ask question: %s", err) return err } if sendRes.Result.MessageID == nil { s.ChatErrorf(s.convID, "askQuestion: failed to get message ID of question ask") } for index := range q.answers { if _, err := s.kbc.ReactByConvID(s.convID, *sendRes.Result.MessageID, base.NumberToEmoji(index+1)); err != nil { s.ChatErrorf(s.convID, "askQuestion: failed to set reaction option: %s", err) } } s.curMsgID = *sendRes.Result.MessageID return nil } func (s *session) getAnswerPoints(a answer, q question) (isCorrect bool, pointAdjust int) { if a.selection != q.correctAnswer { return false, -5 } switch q.difficulty { case "easy": return true, 5 case "medium": return true, 10 case "hard": return true, 15 default: s.Debug("getAnswerPoints: unknown difficulty: %s", q.difficulty) return true, 5 } } func (s *session) dupKey(username string) string { return fmt.Sprintf("%s:%d", username, s.curMsgID) } func (s *session) checkDupe(username string) bool { return s.dupCheck[s.dupKey(username)] } func (s *session) regDupe(username string) { s.dupCheck[s.dupKey(username)] = true } func (s *session) numAnswers() int { return len(s.dupCheck) } func (s *session) waitForCorrectAnswer() { timeoutCh := make(chan struct{}) doneCh := make(chan struct{}) base.GoWithRecover(s.DebugOutput, func() { for { select { case <-s.stopCh: return case <-timeoutCh: return case answer := <-s.answerCh: if s.checkDupe(answer.username) { s.Debug("ignoring duplicate answer from: %s", answer.username) continue } if answer.msgID != s.curMsgID { s.Debug("ignoring answer for non-current question: cur: %d ans: %d", s.curMsgID, answer.msgID) continue } if s.curQuestion == nil { s.Debug("ignoring answer since curQuestion is nil") continue } isCorrect, pointAdjust := s.getAnswerPoints(answer, *s.curQuestion) if err := s.db.RecordAnswer(s.convID, answer.username, pointAdjust, isCorrect); err != nil { s.Errorf("waitForCorrectAnswer: failed to record answer: %s", err) } s.regDupe(answer.username) if !isCorrect { s.ChatEcho(s.convID, "Incorrect answer of %s by %s (%d points)", base.NumberToEmoji(answer.selection+1), answer.username, pointAdjust) // If no one else can answer short circuit instead of forcing the timeout if s.numAnswers() >= s.numUsersInConv { s.ChatEcho(s.convID, "Next question!\nCorrect answer was %s *%q*", base.NumberToEmoji(s.curQuestion.correctAnswer+1), s.curQuestion.Answer()) s.curQuestion = nil close(doneCh) return } } else { s.ChatEcho(s.convID, "*Correct answer of %s by %s (%d points)*", base.NumberToEmoji(answer.selection+1), answer.username, pointAdjust) s.curQuestion = nil close(doneCh) return } } } }) select { case <-time.After(20 * time.Second): s.ChatEcho(s.convID, "Times up, next question!\nCorrect answer was %s *%q*", base.NumberToEmoji(s.curQuestion.correctAnswer+1), s.curQuestion.Answer()) close(timeoutCh) return case <-doneCh: case <-s.stopCh: } } func (s *session) start(intotal int) (doneCb chan struct{}, err error) { doneCb = make(chan struct{}) total := defaultTotal if intotal > 0 { total = intotal } base.GoWithRecover(s.DebugOutput, func() { defer close(doneCb) for i := 0; i < total; i++ { select { case <-s.stopCh: return default: } if err := s.getNextQuestion(); err != nil { s.ChatErrorf(s.convID, "start: failed to get next question: %s", err) continue } if err := s.askQuestion(); err != nil { s.ChatErrorf(s.convID, "start: failed to ask question: %s", err) continue } s.waitForCorrectAnswer() } }) return doneCb, nil } func (s *session) stop() { close(s.stopCh) }
package service import ( "fmt" "time" "github.com/TRON-US/soter-order-service/common/constants" "github.com/TRON-US/soter-order-service/common/errorm" "github.com/TRON-US/soter-order-service/logger" "github.com/TRON-US/soter-order-service/model" "github.com/TRON-US/soter-order-service/utils" "github.com/TRON-US/chaos/network/slack" ) // Close order controller. func (s *Server) CloseOrderController(orderId int64) error { // Get order info by order id. order, err := s.DbConn.QueryOrderInfoById(orderId) if err != nil { if err.Error() != errorm.QueryResultEmpty { go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] query order info error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.QueryOrderInfoModel) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.QueryOrderInfoModel, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) } return err } // Check order status. if order.Status != constants.OrderPending { return errorm.OrderStatusIllegal } // Open transaction. session := s.DbConn.DB.NewSession() err = session.Begin() if err != nil { go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] open transaction error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.SessionBegin) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.SessionBegin, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } defer session.Close() // Lock row by address. ledger, err := s.DbConn.LockLedgerInfoByAddress(session, order.Address) if err != nil { _ = session.Rollback() go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] get lock error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.GetLedgerRowLockModel) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.GetLedgerRowLockModel, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } // Check freeze balance illegal. if ledger.FreezeBalance < order.Amount { _ = session.Rollback() return errorm.InsufficientBalance } if order.OrderType == constants.Charge { // Delete file. err = model.DeleteFile(session, order.FileId, order.FileVersion) if err != nil { _ = session.Rollback() go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] delete file error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.DeleteFileModel) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.DeleteFileModel, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } } // Unfreeze user balance. err = model.UpdateUserBalance(session, ledger.Balance+order.Amount, ledger.FreezeBalance-order.Amount, ledger.Version, ledger.Id, order.Address, int(time.Now().Local().Unix())) if err != nil { _ = session.Rollback() go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] update user balance error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.UpdateUserBalanceModel) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.UpdateUserBalanceModel, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } // Update order status by order id. err = model.UpdateOrderStatus(session, orderId, constants.OrderFailed) if err != nil { _ = session.Rollback() go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] update order status error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.UpdateOrderStatusModel) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.UpdateOrderStatusModel, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } // Submit transaction. err = session.Commit() if err != nil { go func(orderId int64, err error) { errMessage := fmt.Sprintf("orderId: [%v] commit transaction error, reasons: [%v]", orderId, err) logger.Logger.Errorw(errMessage, "function", constants.SessionCommit) _ = slack.SendSlackNotification(s.Config.Slack.SlackWebhookUrl, utils.ErrorRequestBody(errMessage, constants.SessionCommit, constants.SlackNotifyLevel0), s.Config.Slack.SlackNotificationTimeout, slack.Priority0, slack.Priority(s.Config.Slack.SlackPriorityThreshold)) }(orderId, err) return err } return nil }
/* Nil channel blocks forever for sender and reciever function */ package main import "fmt" func main() { var ch chan int ch <- 2 fmt.Println("VBlocked") }
package stravaclient import ( "context" "strconv" "time" "github.com/antihax/optional" "github.com/gobuffalo/envy" "github.com/tcarreira/roaw2020/strava_client/swagger" ) // StravaAPI contains a Strava API Client with the necessary context type StravaAPI struct { client *swagger.APIClient ctx context.Context opts *swagger.ActivitiesApiGetLoggedInAthleteActivitiesOpts } func getThisYear() int { osEnv := envy.Get("ROAW_YEAR", "") thisYear, err := strconv.Atoi(osEnv) if err != nil { // Fail silently return time.Now().Year() } return thisYear } // NewStravaAPI returns a StravaAPI ready to make API calls (on behalf of stravaAccessToken) // with default opts (like after/before dates) func NewStravaAPI(stravaAccessToken string) *StravaAPI { thisYear := getThisYear() s := &StravaAPI{ client: swagger.NewAPIClient(swagger.NewConfiguration()), ctx: context.WithValue(context.Background(), swagger.ContextAccessToken, stravaAccessToken), opts: &swagger.ActivitiesApiGetLoggedInAthleteActivitiesOpts{ After: optional.NewInt32(int32(time.Date(thisYear, 1, 1, 0, 0, 0, 0, time.UTC).Unix())), Before: optional.NewInt32(int32(time.Date(thisYear+1, 1, 1, 0, 0, 0, 0, time.UTC).Unix())), Page: optional.NewInt32(1), PerPage: optional.NewInt32(int32(5)), }, } return s } // fetchActivitiesSinglePage will fetch a single page func (s *StravaAPI) fetchActivitiesSinglePage(page int) ([]swagger.SummaryActivity, error) { s.opts.Page = optional.NewInt32(int32(page)) activities, _, err := s.client.ActivitiesApi.GetLoggedInAthleteActivities(s.ctx, s.opts) return activities, err } // FetchAllActivities will fetch and return all activities (within the after/before defined in StravaAPI.opts) func FetchAllActivities(stravaAccessToken string) ([]swagger.SummaryActivity, error) { stravaAPI := NewStravaAPI(stravaAccessToken) stravaAPI.opts.PerPage = optional.NewInt32(200) // set to max limit if we are going to fetch all anyway (https://developers.strava.com/docs/#Pagination) var allActivities []swagger.SummaryActivity for i := 1; ; i++ { activities, err := stravaAPI.fetchActivitiesSinglePage(i) if err != nil { return []swagger.SummaryActivity{}, err } allActivities = append(allActivities, activities...) if int32(len(activities)) != stravaAPI.opts.PerPage.Value() { // repeat the cicle until returns less than PerPage break } } return allActivities, nil } // FetchLatestActivities will fetch and return the latest N activities (N defined in StravaAPI.opts) func FetchLatestActivities(stravaAccessToken string) ([]swagger.SummaryActivity, error) { stravaAPI := NewStravaAPI(stravaAccessToken) activities, err := stravaAPI.fetchActivitiesSinglePage(1) return activities, err }
package jwt import ( "github.com/dgrijalva/jwt-go" "google.golang.org/grpc/status" "time" ) const ( Jwtkey = "com.hive-and-cell.com" //TODO !!! Change that TokenExpired = 34 InvalidToken = 35 ) func CheckJwt(tokenString string) error { claims := jwt.MapClaims{} _, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) { return []byte(Jwtkey), nil }) if err != nil && "Token is expired" == err.Error() { return status.Error(TokenExpired, err.Error()) } else if err != nil { return status.Error(InvalidToken, err.Error()) } return nil } func GenerateToken(username, email string) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "user": username, "email": email, "exp": time.Now().Add(time.Hour * time.Duration(48)).Unix(), "iat": time.Now().Unix(), }) return token.SignedString([]byte(Jwtkey)) }
package main import ( "basic-app-server/config" "basic-app-server/core" apperr "basic-app-server/errors" "basic-app-server/logger" "fmt" "os" "path" "time" "github.com/coreos/go-systemd/daemon" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) const SOFTWARE_NAME = "UNKNOWN_SOFTWARE_NAME" var ( BUILD_TAGS = "UNKNOWN_BUILD_TAGS" VERSION_MAJOR = "UNKNOWN_VERSION_MAJOR" VERSION_MINOR = "UNKNOWN_VERSION_MINOR" VERSION_DERIVATIVE = "UNKNOWN_VERSION_DERIVATIVE" GIT_BRANCH = "UNKNOWN_GIT_BRANCH" BUILD_DATE = time.Now().Local().Format(time.RFC3339) ) var cfgFile string var mainLogger *logrus.Entry = logger.GetLogger("main") func init() { cobra.OnInitialize() RootCmd.AddCommand(versionCmd) RootCmd.AddCommand(configCmd) RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is ./config.yaml") } var RootCmd = &cobra.Command{ Use: SOFTWARE_NAME, Short: SOFTWARE_NAME + " is a basic application server.", Long: "A basic application server built by Leo Hung. Complete documentation is available at https://github.com/srleohung/basic-app-server", Run: func(cmd *cobra.Command, args []string) { appServer() }, } var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of " + SOFTWARE_NAME, Long: "All software has versions. This is " + SOFTWARE_NAME + `'s`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Software name :", SOFTWARE_NAME) fmt.Println("Build tags :", BUILD_TAGS) fmt.Println("Version major :", VERSION_MAJOR) fmt.Println("Version minor :", VERSION_MINOR) fmt.Println("Version Derivative :", VERSION_DERIVATIVE) fmt.Println("Git branch :", GIT_BRANCH) fmt.Println("Build date :", BUILD_DATE) }, } var configCmd = &cobra.Command{ Use: "config", Short: "Print the configuration of " + SOFTWARE_NAME, Run: func(cmd *cobra.Command, args []string) { configuration := loadConfig() if bytes, err := yaml.Marshal(*configuration); err != nil { fmt.Println(err) } else { fmt.Println(string(bytes)) } }, } func main() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(apperr.EXITCODE_PROGRAM_COMMAND_ERROR) } } func appServer() { version := VERSION_MAJOR + "." + VERSION_MINOR + "_" + VERSION_DERIVATIVE mainLogger.Infoln("--------------------------------------------------") mainLogger.Infoln("Starting application server version:", version) appServer := appServerSetup(version) daemon.SdNotify(false, "READY=1") mainLogger.Infoln("--------------------------------------------------") mainLogger.Infoln("Finished application server configuration and setup.") appServer.Start() mainLogger.Infoln("--------------------------------------------------") mainLogger.Infoln("Start serving application server.") go watchdog() <-quit } var quit = make(chan bool) func watchdog() { interval, err := daemon.SdWatchdogEnabled(false) if err != nil || interval == 0 { mainLogger.Warn("Watchdog is not enabled.") return } for { daemon.SdNotify(false, "WATCHDOG=1") time.Sleep(interval / 3) } } func loadConfig() *config.Config { var configuration config.Config useDefaultConfig := true if len(cfgFile) > 0 { if _, err := os.Stat(cfgFile); os.IsNotExist(err) { useDefaultConfig = true } else { mainLogger.Infoln("Load the application server configuration from", cfgFile) if tmpConfig := config.LoadConfigFromYaml(cfgFile); tmpConfig == nil { useDefaultConfig = true } else { configuration = *tmpConfig useDefaultConfig = false } } } else { workingDir, _ := os.Getwd() defaultConfigFile := path.Join(workingDir, config.DAFAULT_CONFIG_FILENAME) if _, err := os.Stat(defaultConfigFile); os.IsNotExist(err) { useDefaultConfig = true } else { if tmpConfig := config.LoadConfigFromYaml(defaultConfigFile); tmpConfig == nil { useDefaultConfig = true } else { configuration = *tmpConfig useDefaultConfig = false } } } if useDefaultConfig { mainLogger.Infoln("Load the default application server configuration.") configuration = config.DEFAULT_CONFIG if workingDir, err := os.Getwd(); err != nil { mainLogger.Errorln("The current working directory cannot be recognized.", err) os.Exit(apperr.EXITCODE_UNEXPECTED_ERROR) } else { if err := configuration.SaveConfigToYamlFile(path.Join(workingDir, config.DAFAULT_CONFIG_FILENAME)); err != nil { mainLogger.Warnln("Unable to save application server configuration file to " + path.Join(workingDir, config.DAFAULT_CONFIG_FILENAME)) } } } return &configuration } func appServerSetup(version string) *core.AppServer { if configuration := loadConfig(); configuration != nil { return core.GetAppServer(configuration, version) } else { mainLogger.Errorln("The application server configuration is not recognized.") os.Exit(apperr.EXITCODE_UNEXPECTED_ERROR) } return nil }
package main import ( "fmt" "log" "os" "strconv" ) const usage = ` usage: crawl <starting-url> [num-workers=1] If not specified, the number of workers will default to 1. To specify more workers, pass an integer as the second command-line argument. ` const defaultNumWorkers = 1 type crawlResults struct { pageInfo *PageInfo err error } //TODO: define a worker function func main() { if len(os.Args) < 2 { fmt.Println(usage) os.Exit(1) } numWorkers := defaultNumWorkers if len(os.Args) > 2 { var err error numWorkers, err = strconv.Atoi(os.Args[2]) if err != nil { log.Fatalf("number of workers must be a number: %v", err) } } log.Printf("starting %d workers...", numWorkers) //TODO: create channels for the URLs to crawl (jobs) //and the crawlResults of each crawl (results) //TODO: start workers on their own goroutines, //passing those channels as arguments //TODO: create a map to track all the URLs //we've already crawled so that we don't //crawl them multiple times //TODO: write the first command-line arg //to the URLs-to-crawl channel, and add it //to the map of already-crawled URLs //TODO: range over the results channel, //processing each link in the crawled page info }
package actors import "github.com/dpordomingo/learning-exercises/ant/geo" //Rover modelates an actor that can walk over a map and look for a target type Rover interface { //Init initializes the Ant searching for certain destiny from certain origin Init(geo.Point, geo.Point) //Position returns the position of the Rover Position() geo.Point }
package config import ( "flag" "os" "strconv" "github.com/joho/godotenv" _ "github.com/joho/godotenv/autoload" ) var ( goAddrPort = flag.String("goAddrPort", ":8080", "RESTful api port") ) var appConfig *AppConfig func init() { godotenv.Load() } // AppConfig mean app config struct type AppConfig struct { AppLogPath string DBConnection string DBHost string DBPort int DBDatabase string DBUsername string DBPassword string LineChannelSecret string LineChannelAccessToken string GoAddrPort string } // SetAppConfig mean set app config func SetAppConfig() { dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT")) appConfig = &AppConfig{ AppLogPath: os.Getenv("APP_LOG_PATH"), DBConnection: os.Getenv("DB_CONNECTION"), DBHost: os.Getenv("DB_HOST"), DBPort: dbPort, DBDatabase: os.Getenv("DB_DATABASE"), DBUsername: os.Getenv("DB_USERNAME"), DBPassword: os.Getenv("DB_PASSWORD"), LineChannelSecret: os.Getenv("LINE_CHANNEL_SECRET"), LineChannelAccessToken: os.Getenv("LINE_CHANNEL_ACCESS_TOKEN"), GoAddrPort: *goAddrPort, } } // GetAppConfig mean get app config func GetAppConfig() *AppConfig { return appConfig }
package schema import ( "github.com/facebook/ent" "github.com/facebook/ent/schema/field" ) // QccEnterpriseData holds the schema definition for the QccEnterpriseData entity. type QccEnterpriseData struct { ent.Schema } // Fields of the QccEnterpriseData. func (QccEnterpriseData) Fields() []ent.Field { return []ent.Field{ field.String("name"), // 企业名称 field.String("register_status"), // 登记状态 field.String("legal_person"), // 法人 field.String("registered_capital"), // 注册资本 field.String("set_up_date"), // 成立日期 field.String("verify_date"), // 核准日期 field.String("province"), // 省 field.String("city"), // 市 field.String("county"), // 县 field.String("phone"), // 电话 field.String("other_phones"), // 更多电话 field.String("email"), // 邮箱 field.String("other_emails"), // 更多邮箱 field.String("unified_social_credit_code"), // 统一社会信用代码 field.String("taxpayer_identification_number"), // 纳税人识别号 field.String("registration_number"), // 注册号 field.String("organization_code"), // 组织机构代码 field.String("insurance_person_nums"), // 参保人数 field.String("enterprise_type"), // 企业类型 field.String("industry_involved"), // 所属行业 field.String("former_name"), // 曾用名 field.String("website"), // 官网 field.String("address"), // 企业地址 field.String("business_scope"), // 经营范围 } } // Edges of the QccEnterpriseData. func (QccEnterpriseData) Edges() []ent.Edge { return nil }
package main import ( "flag" "fmt" "net/url" "os" "github.com/dah8ra/ch4/omdbapi" ) const baseurl = "http://omdbapi.com/?" const basefilename = "../ex4.13/" var word = flag.String("w", "frozen", "Search word") func main() { flag.Parse() values := url.Values{} values.Add("t", *word) values.Add("r", "json") url := baseurl + values.Encode() fmt.Printf("-------> %s\n", url) r, _ := omdbapi.Get(url) if r != nil { fmt.Printf("#%s %s %s\n", r.Title, r.Year, r.Poster) } else { fmt.Println("Failed to download...") } if r != nil { body, _ := omdbapi.Download(r.Poster) filename := basefilename + *word + ".jpeg" fmt.Printf("Saved ==> %s\n", filename) file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0666) if err != nil { fmt.Println(err) } defer file.Close() file.Write(body) } else { fmt.Println("Failed to download...") } }
package test_sandbox_sc import ( "fmt" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/coretypes/cbalances" "github.com/iotaledger/wasp/packages/kv/dict" "github.com/iotaledger/wasp/packages/kv/kvdecoder" "github.com/iotaledger/wasp/packages/vm/core/accounts" ) // calls withdrawToChain to the chain ID func withdrawToChain(ctx coretypes.Sandbox) (dict.Dict, error) { ctx.Log().Infof(FuncWithdrawToChain) params := kvdecoder.New(ctx.Params(), ctx.Log()) targetChain := params.MustGetChainID(ParamChainID) succ := ctx.PostRequest(coretypes.PostRequestParams{ TargetContractID: accounts.Interface.ContractID(targetChain), EntryPoint: coretypes.Hn(accounts.FuncWithdrawToChain), Transfer: cbalances.NewFromMap(map[balance.Color]int64{ balance.ColorIOTA: 2, }), }) if !succ { return nil, fmt.Errorf("failed to post request") } ctx.Log().Infof("%s: success", FuncWithdrawToChain) return nil, nil }
package main import ( "fmt" "github.com/cloudfoundry/packit" "laraboot-buildpacks/poc/laraboot" ) // To be replaced using go generate var TaskName = "unset" func main() { fmt.Printf("Detecting %s", TaskName) packit.Detect(laraboot.Detect(TaskName)) }
package packages import ( "fmt" ) // TestPackageManager is a noop manager. type TestPackageManager struct{} func (t *TestPackageManager) Install(pkg, version string) (error, bool) { return nil, false } func (t *TestPackageManager) Unitfile(pkg string) (string, error) { return "", fmt.Errorf("not found: %s", pkg) } func (t *TestPackageManager) Clean(pkg string) string { return pkg }
package wordCount import ( "fmt" "strings" ) func WordCount(text string) map[string]int { words := strings.Fields(text) wordsCount := map[string]int{} for _, word := range words { wordsCount[strings.ToLower(word)]++ } fmt.Println(wordsCount) return wordsCount }
package main import ( "testing" "github.com/stretchr/testify/assert" ) func TestStart(t *testing.T) { monitor := tempMonitor{} assert.NotNil(t, monitor) }
package v1beta2 import ( "errors" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util" next "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta3" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/devspace-cloud/devspace/pkg/util/ptr" ) // getSelector returns the service referenced by serviceName func getSelector(config *Config, selectorName string) (*SelectorConfig, error) { if config.Dev.Selectors != nil { for _, selector := range *config.Dev.Selectors { if *selector.Name == selectorName { return selector, nil } } } return nil, errors.New("Unable to find selector: " + selectorName) } func ptrArrToStrArr(ptrArr *[]*string) []string { if ptrArr == nil { return nil } retArr := []string{} for _, v := range *ptrArr { retArr = append(retArr, *v) } return retArr } func ptrMapToStrMap(ptrMap *map[string]*string) map[string]string { if ptrMap == nil { return nil } retMap := make(map[string]string) for k, v := range *ptrMap { retMap[k] = *v } return retMap } // Upgrade upgrades the config func (c *Config) Upgrade(log log.Logger) (config.Config, error) { nextConfig := &next.Config{} err := util.Convert(c, nextConfig) if err != nil { return nil, err } // Check if old cluster exists if c.Cluster != nil && (c.Cluster.KubeContext != nil || c.Cluster.Namespace != nil) { log.Warnf("cluster config option is not supported anymore in v1beta2 and devspace v4") } if nextConfig.Dev == nil { nextConfig.Dev = &next.DevConfig{} } if nextConfig.Dev.Interactive == nil { nextConfig.Dev.Interactive = &next.InteractiveConfig{} } if c.Dev != nil && c.Dev.Terminal != nil && c.Dev.Terminal.Disabled != nil { nextConfig.Dev.Interactive.DefaultEnabled = ptr.Bool(!*c.Dev.Terminal.Disabled) } else { nextConfig.Dev.Interactive.DefaultEnabled = ptr.Bool(true) } // Convert override images if c.Dev != nil { if c.Dev.OverrideImages != nil && len(*c.Dev.OverrideImages) > 0 { nextConfig.Dev.Interactive.Images = []*next.InteractiveImageConfig{} for _, overrideImage := range *c.Dev.OverrideImages { if overrideImage.Name == nil { continue } if overrideImage.Dockerfile != nil { log.Warnf("dev.overrideImages[*].dockerfile is not supported anymore, please use profiles instead") } if overrideImage.Context != nil { log.Warnf("dev.overrideImages[*].context is not supported anymore, please use profiles instead") } entrypoint := []string{} cmd := []string{} if overrideImage.Entrypoint != nil && len(*overrideImage.Entrypoint) > 0 { entrypoint = []string{*(*overrideImage.Entrypoint)[0]} for i, s := range *overrideImage.Entrypoint { if i == 0 { continue } cmd = append(cmd, *s) } } nextConfig.Dev.Interactive.Images = append(nextConfig.Dev.Interactive.Images, &next.InteractiveImageConfig{ Name: *overrideImage.Name, Entrypoint: entrypoint, Cmd: cmd, }) } } // Convert terminal if c.Dev.Terminal != nil { if c.Dev.Terminal.Command != nil || c.Dev.Terminal.Selector != nil || c.Dev.Terminal.LabelSelector != nil || c.Dev.Terminal.Namespace != nil || c.Dev.Terminal.ContainerName != nil { if c.Dev.Terminal.Selector != nil { selector, err := getSelector(c, *c.Dev.Terminal.Selector) if err != nil { return nil, err } nextConfig.Dev.Interactive.Terminal = &next.TerminalConfig{ LabelSelector: ptrMapToStrMap(selector.LabelSelector), Namespace: ptr.ReverseString(selector.Namespace), ContainerName: ptr.ReverseString(selector.ContainerName), } } else { nextConfig.Dev.Interactive.Terminal = &next.TerminalConfig{ LabelSelector: ptrMapToStrMap(c.Dev.Terminal.LabelSelector), Namespace: ptr.ReverseString(c.Dev.Terminal.Namespace), ContainerName: ptr.ReverseString(c.Dev.Terminal.ContainerName), } } nextConfig.Dev.Interactive.Terminal.Command = ptrArrToStrArr(c.Dev.Terminal.Command) } } // Convert sync if c.Dev.Sync != nil { for idx, syncConfig := range *c.Dev.Sync { if syncConfig.Selector != nil { selector, err := getSelector(c, *syncConfig.Selector) if err != nil { return nil, err } if selector.LabelSelector != nil { nextConfig.Dev.Sync[idx].LabelSelector = ptrMapToStrMap(selector.LabelSelector) } if selector.Namespace != nil { nextConfig.Dev.Sync[idx].Namespace = *selector.Namespace } if selector.ContainerName != nil { nextConfig.Dev.Sync[idx].ContainerName = *selector.ContainerName } } } } // Convert port forward if c.Dev.Ports != nil { for idx, portConfig := range *c.Dev.Ports { if portConfig.Selector != nil { selector, err := getSelector(c, *portConfig.Selector) if err != nil { return nil, err } if selector.LabelSelector != nil { nextConfig.Dev.Ports[idx].LabelSelector = ptrMapToStrMap(selector.LabelSelector) } if selector.Namespace != nil { nextConfig.Dev.Ports[idx].Namespace = *selector.Namespace } } } } } // Upgrade dependencies if c.Dependencies != nil { for idx, dependency := range *c.Dependencies { if dependency.Config != nil { nextConfig.Dependencies[idx].Profile = *dependency.Config } } } // Upgrade images if c.Images != nil { for imageName, image := range *c.Images { if image.CreatePullSecret == nil { nextConfig.Images[imageName].CreatePullSecret = ptr.Bool(false) } } } // Update deployments if c.Deployments != nil { for idx, deployment := range *c.Deployments { if deployment.Helm != nil { nextConfig.Deployments[idx].Helm.ReplaceImageTags = deployment.Helm.DevSpaceValues } } } return nextConfig, nil } // UpgradeVarPaths upgrades the config func (c *Config) UpgradeVarPaths(varPaths map[string]string, log log.Logger) error { return nil }
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc> // See LICENSE for licensing information package interp import ( "bytes" "context" "fmt" "io" "math" "os" "os/user" "path/filepath" "sort" "strings" "sync" "time" "mvdan.cc/sh/syntax" ) // A Runner interprets shell programs. It cannot be reused once a // program has been interpreted. // // Note that writes to Stdout and Stderr may not be sequential. If // you plan on using an io.Writer implementation that isn't safe for // concurrent use, consider a workaround like hiding writes behind a // mutex. type Runner struct { // Env specifies the environment of the interpreter. // If Env is nil, Run uses the current process's environment. Env []string // envMap is just Env as a map, to simplify and speed up its use envMap map[string]string // Dir specifies the working directory of the command. If Dir is // the empty string, Run runs the command in the calling // process's current directory. Dir string // Params are the current parameters, e.g. from running a shell // file or calling a function. Accessible via the $@/$* family // of vars. Params []string Exec ModuleExec Open ModuleOpen filename string // only if Node was a File // Separate maps, note that bash allows a name to be both a var // and a func simultaneously Vars map[string]Variable Funcs map[string]*syntax.Stmt // like Vars, but local to a func i.e. "local foo=bar" funcVars map[string]Variable // like Vars, but local to a cmd i.e. "foo=bar prog args..." cmdVars map[string]string // >0 to break or continue out of N enclosing loops breakEnclosing, contnEnclosing int inLoop bool inFunc bool inSource bool err error // current fatal error exit int // current (last) exit code Stdin io.Reader Stdout io.Writer Stderr io.Writer bgShells sync.WaitGroup // Context can be used to cancel the interpreter before it finishes Context context.Context shellOpts [len(shellOptsTable)]bool dirStack []string optState getopts ifsJoin string ifsRune func(rune) bool // keepRedirs is used so that "exec" can make any redirections // apply to the current shell, and not just the command. keepRedirs bool // KillTimeout holds how much time the interpreter will wait for a // program to stop after being sent an interrupt signal, after // which a kill signal will be sent. This process will happen when the // interpreter's context is cancelled. // // The zero value will default to 2 seconds. // // A negative value means that a kill signal will be sent immediately. // // On Windows, the kill signal is always sent immediately, // because Go doesn't currently support sending Interrupt on Windows. KillTimeout time.Duration fieldAlloc [4]fieldPart fieldsAlloc [4][]fieldPart bufferAlloc bytes.Buffer oneWord [1]*syntax.Word braceAlloc braceWord bracePartsAlloc [4]braceWordPart } func (r *Runner) strBuilder() *bytes.Buffer { b := &r.bufferAlloc b.Reset() return b } func (r *Runner) optByFlag(flag string) *bool { for i, opt := range shellOptsTable { if opt.flag == flag { return &r.shellOpts[i] } } return nil } func (r *Runner) optByName(name string) *bool { for i, opt := range shellOptsTable { if opt.name == name { return &r.shellOpts[i] } } return nil } var shellOptsTable = [...]struct { flag, name string }{ // sorted alphabetically by name; use a space for the options // that have no flag form {"a", "allexport"}, {"e", "errexit"}, {"n", "noexec"}, {"f", "noglob"}, {"u", "nounset"}, {" ", "pipefail"}, } // To access the shell options arrays without a linear search when we // know which option we're after at compile time. const ( optAllExport = iota optErrExit optNoExec optNoGlob optNoUnset optPipeFail ) // Reset will set the unexported fields back to zero, fill any exported // fields with their default values if not set, and prepare the runner // to interpret a program. // // This function should be called once before running any node. It can // be skipped before any following runs to keep internal state, such as // declared variables. func (r *Runner) Reset() error { // reset the internal state *r = Runner{ Env: r.Env, Dir: r.Dir, Params: r.Params, Context: r.Context, Stdin: r.Stdin, Stdout: r.Stdout, Stderr: r.Stderr, Exec: r.Exec, Open: r.Open, KillTimeout: r.KillTimeout, // emptied below, to reuse the space envMap: r.envMap, Vars: r.Vars, cmdVars: r.cmdVars, dirStack: r.dirStack[:0], } if r.envMap == nil { r.envMap = make(map[string]string) } else { for k := range r.envMap { delete(r.envMap, k) } } if r.Vars == nil { r.Vars = make(map[string]Variable) } else { for k := range r.Vars { delete(r.Vars, k) } } if r.cmdVars == nil { r.cmdVars = make(map[string]string) } else { for k := range r.cmdVars { delete(r.cmdVars, k) } } if r.Context == nil { r.Context = context.Background() } if r.Env == nil { r.Env = os.Environ() } for _, kv := range r.Env { i := strings.IndexByte(kv, '=') if i < 0 { return fmt.Errorf("env not in the form key=value: %q", kv) } name, val := kv[:i], kv[i+1:] r.envMap[name] = val } if _, ok := r.envMap["HOME"]; !ok { u, _ := user.Current() r.Vars["HOME"] = Variable{Value: StringVal(u.HomeDir)} } if r.Dir == "" { dir, err := os.Getwd() if err != nil { return fmt.Errorf("could not get current dir: %v", err) } r.Dir = dir } r.Vars["PWD"] = Variable{Value: StringVal(r.Dir)} r.Vars["IFS"] = Variable{Value: StringVal(" \t\n")} r.ifsUpdated() r.Vars["OPTIND"] = Variable{Value: StringVal("1")} // convert $PATH to a unix path list path := r.envMap["PATH"] path = strings.Join(filepath.SplitList(path), ":") r.Vars["PATH"] = Variable{Value: StringVal(path)} r.dirStack = append(r.dirStack, r.Dir) if r.Exec == nil { r.Exec = DefaultExec } if r.Open == nil { r.Open = DefaultOpen } if r.KillTimeout == 0 { r.KillTimeout = 2 * time.Second } return nil } func (r *Runner) ctx() Ctxt { c := Ctxt{ Context: r.Context, Env: r.Env, Dir: r.Dir, Stdin: r.Stdin, Stdout: r.Stdout, Stderr: r.Stderr, KillTimeout: r.KillTimeout, } for name, vr := range r.Vars { if !vr.Exported { continue } c.Env = append(c.Env, name+"="+r.varStr(vr, 0)) } for name, val := range r.cmdVars { c.Env = append(c.Env, name+"="+val) } return c } type Variable struct { Local bool Exported bool ReadOnly bool NameRef bool Value VarValue } // VarValue is one of: // // StringVal // IndexArray // AssocArray type VarValue interface{} type StringVal string type IndexArray []string type AssocArray map[string]string // maxNameRefDepth defines the maximum number of times to follow // references when expanding a variable. Otherwise, simple name // reference loops could crash the interpreter quite easily. const maxNameRefDepth = 100 func (r *Runner) varStr(vr Variable, depth int) string { if depth > maxNameRefDepth { return "" } switch x := vr.Value.(type) { case StringVal: if vr.NameRef { vr, _ = r.lookupVar(string(x)) return r.varStr(vr, depth+1) } return string(x) case IndexArray: if len(x) > 0 { return x[0] } case AssocArray: // nothing to do } return "" } func (r *Runner) varInd(vr Variable, e syntax.ArithmExpr, depth int) string { if depth > maxNameRefDepth { return "" } switch x := vr.Value.(type) { case StringVal: if vr.NameRef { vr, _ = r.lookupVar(string(x)) return r.varInd(vr, e, depth+1) } if r.arithm(e) == 0 { return string(x) } case IndexArray: switch anyOfLit(e, "@", "*") { case "@": return strings.Join(x, " ") case "*": return strings.Join(x, r.ifsJoin) } i := r.arithm(e) if len(x) > 0 { return x[i] } case AssocArray: if lit := anyOfLit(e, "@", "*"); lit != "" { var strs IndexArray keys := make([]string, 0, len(x)) for k := range x { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { strs = append(strs, x[k]) } if lit == "*" { return strings.Join(strs, r.ifsJoin) } return strings.Join(strs, " ") } return x[r.loneWord(e.(*syntax.Word))] } return "" } type ExitCode uint8 func (e ExitCode) Error() string { return fmt.Sprintf("exit status %d", e) } func (r *Runner) setErr(err error) { if r.err == nil { r.err = err } } func (r *Runner) lastExit() { if r.err == nil { r.err = ExitCode(r.exit) } } func (r *Runner) setVarString(name, val string) { r.setVar(name, nil, Variable{Value: StringVal(val)}) } func (r *Runner) setVarInternal(name string, vr Variable) { if _, ok := vr.Value.(StringVal); ok { if r.shellOpts[optAllExport] { vr.Exported = true } } else { vr.Exported = false } if vr.Local { if r.funcVars == nil { r.funcVars = make(map[string]Variable) } r.funcVars[name] = vr } else { r.Vars[name] = vr } if name == "IFS" { r.ifsUpdated() } } func (r *Runner) setVar(name string, index syntax.ArithmExpr, vr Variable) { cur, _ := r.lookupVar(name) if cur.ReadOnly { r.errf("%s: readonly variable\n", name) r.exit = 1 r.lastExit() return } _, isIndexArray := cur.Value.(IndexArray) _, isAssocArray := cur.Value.(AssocArray) if _, ok := vr.Value.(StringVal); ok && index == nil { // When assigning a string to an array, fall back to the // zero value for the index. if isIndexArray { index = &syntax.Word{Parts: []syntax.WordPart{ &syntax.Lit{Value: "0"}, }} } else if isAssocArray { index = &syntax.Word{Parts: []syntax.WordPart{ &syntax.DblQuoted{}, }} } } if index == nil { r.setVarInternal(name, vr) return } // from the syntax package, we know that val must be a string if // index is non-nil; nested arrays are forbidden. valStr := string(vr.Value.(StringVal)) // if the existing variable is already an AssocArray, try our best // to convert the key to a string if stringIndex(index) || isAssocArray { var amap AssocArray switch x := cur.Value.(type) { case StringVal, IndexArray: return // TODO case AssocArray: amap = x } w, ok := index.(*syntax.Word) if !ok { return } k := r.loneWord(w) amap[k] = valStr cur.Value = amap r.setVarInternal(name, cur) return } var list IndexArray switch x := cur.Value.(type) { case StringVal: list = append(list, string(x)) case IndexArray: list = x case AssocArray: // done above } k := r.arithm(index) for len(list) < k+1 { list = append(list, "") } list[k] = valStr cur.Value = list r.setVarInternal(name, cur) } func (r *Runner) lookupVar(name string) (Variable, bool) { if val, e := r.cmdVars[name]; e { return Variable{Value: StringVal(val)}, true } if vr, e := r.funcVars[name]; e { return vr, true } if vr, e := r.Vars[name]; e { return vr, true } if str, e := r.envMap[name]; e { return Variable{Value: StringVal(str)}, true } if r.shellOpts[optNoUnset] { r.errf("%s: unbound variable\n", name) r.exit = 1 r.lastExit() } return Variable{}, false } func (r *Runner) getVar(name string) string { val, _ := r.lookupVar(name) return r.varStr(val, 0) } func (r *Runner) delVar(name string) { val, _ := r.lookupVar(name) if val.ReadOnly { r.errf("%s: readonly variable\n", name) r.exit = 1 return } delete(r.Vars, name) delete(r.funcVars, name) delete(r.cmdVars, name) delete(r.envMap, name) } func (r *Runner) setFunc(name string, body *syntax.Stmt) { if r.Funcs == nil { r.Funcs = make(map[string]*syntax.Stmt, 4) } r.Funcs[name] = body } // FromArgs populates the shell options and returns the remaining // arguments. For example, running FromArgs("-e", "--", "foo") will set // the "-e" option and return []string{"foo"}. // // This is similar to what the interpreter's "set" builtin does. func (r *Runner) FromArgs(args ...string) ([]string, error) { for len(args) > 0 { arg := args[0] if arg == "" || (arg[0] != '-' && arg[0] != '+') { break } if arg == "--" { args = args[1:] break } enable := arg[0] == '-' var opt *bool if flag := arg[1:]; flag == "o" { args = args[1:] if len(args) == 0 && enable { for i, opt := range shellOptsTable { status := "off" if r.shellOpts[i] { status = "on" } r.outf("%s:\t%s\n", opt.name, status) } break } if len(args) == 0 && !enable { for i, opt := range shellOptsTable { setFlag := "+o" if r.shellOpts[i] { setFlag = "-o" } r.outf("set %s %s\n", setFlag, opt.name) } break } opt = r.optByName(args[0]) } else { opt = r.optByFlag(flag) } if opt == nil { return nil, fmt.Errorf("invalid option: %q", arg) } *opt = enable args = args[1:] } return args, nil } // Run starts the interpreter and returns any error. func (r *Runner) Run(node syntax.Node) error { r.filename = "" switch x := node.(type) { case *syntax.File: r.filename = x.Name r.stmts(x.StmtList) case *syntax.Stmt: r.stmt(x) case syntax.Command: r.cmd(x) default: return fmt.Errorf("Node can only be File, Stmt, or Command: %T", x) } r.lastExit() if r.err == ExitCode(0) { r.err = nil } return r.err } func (r *Runner) Stmt(stmt *syntax.Stmt) error { r.stmt(stmt) return r.err } func (r *Runner) out(s string) { io.WriteString(r.Stdout, s) } func (r *Runner) outf(format string, a ...interface{}) { fmt.Fprintf(r.Stdout, format, a...) } func (r *Runner) errf(format string, a ...interface{}) { fmt.Fprintf(r.Stderr, format, a...) } func (r *Runner) stop() bool { if r.err != nil { return true } if err := r.Context.Err(); err != nil { r.err = err return true } if r.shellOpts[optNoExec] { return true } return false } func (r *Runner) stmt(st *syntax.Stmt) { if r.stop() { return } if st.Background { r.bgShells.Add(1) r2 := r.sub() go func() { r2.stmtSync(st) r.bgShells.Done() }() } else { r.stmtSync(st) } } func stringIndex(index syntax.ArithmExpr) bool { w, ok := index.(*syntax.Word) if !ok || len(w.Parts) != 1 { return false } _, ok = w.Parts[0].(*syntax.DblQuoted) return ok } func (r *Runner) assignVal(as *syntax.Assign, valType string) VarValue { prev, prevOk := r.lookupVar(as.Name.Value) if as.Naked { return prev.Value } if as.Value != nil { s := r.loneWord(as.Value) if !as.Append || !prevOk { return StringVal(s) } switch x := prev.Value.(type) { case StringVal: return x + StringVal(s) case IndexArray: if len(x) == 0 { x = append(x, "") } x[0] += s return x case AssocArray: // TODO } return StringVal(s) } if as.Array == nil { return nil } elems := as.Array.Elems if valType == "" { if len(elems) == 0 || !stringIndex(elems[0].Index) { valType = "-a" // indexed } else { valType = "-A" // associative } } if valType == "-A" { // associative array amap := AssocArray(make(map[string]string, len(elems))) for _, elem := range elems { k := r.loneWord(elem.Index.(*syntax.Word)) amap[k] = r.loneWord(elem.Value) } if !as.Append || !prevOk { return amap } // TODO return amap } // indexed array maxIndex := len(elems) - 1 indexes := make([]int, len(elems)) for i, elem := range elems { if elem.Index == nil { indexes[i] = i continue } k := r.arithm(elem.Index) indexes[i] = k if k > maxIndex { maxIndex = k } } strs := make([]string, maxIndex+1) for i, elem := range elems { strs[indexes[i]] = r.loneWord(elem.Value) } if !as.Append || !prevOk { return IndexArray(strs) } switch x := prev.Value.(type) { case StringVal: prevList := IndexArray([]string{string(x)}) return append(prevList, strs...) case IndexArray: return append(x, strs...) case AssocArray: // TODO } return IndexArray(strs) } func (r *Runner) stmtSync(st *syntax.Stmt) { oldIn, oldOut, oldErr := r.Stdin, r.Stdout, r.Stderr for _, rd := range st.Redirs { cls, err := r.redir(rd) if err != nil { r.exit = 1 return } if cls != nil { defer cls.Close() } } if st.Cmd == nil { r.exit = 0 } else { r.cmd(st.Cmd) } if st.Negated { r.exit = oneIf(r.exit == 0) } if r.exit != 0 && r.shellOpts[optErrExit] { r.lastExit() } if !r.keepRedirs { r.Stdin, r.Stdout, r.Stderr = oldIn, oldOut, oldErr } } func (r *Runner) sub() *Runner { r2 := *r r2.bgShells = sync.WaitGroup{} r2.bufferAlloc = bytes.Buffer{} // TODO: perhaps we could do a lazy copy here, or some sort of // overlay to avoid copying all the time r2.envMap = make(map[string]string, len(r.envMap)) for k, v := range r.envMap { r2.envMap[k] = v } r2.Vars = make(map[string]Variable, len(r.Vars)) for k, v := range r.Vars { r2.Vars[k] = v } r2.cmdVars = make(map[string]string, len(r.cmdVars)) for k, v := range r.cmdVars { r2.cmdVars[k] = v } return &r2 } func (r *Runner) cmd(cm syntax.Command) { if r.stop() { return } switch x := cm.(type) { case *syntax.Block: r.stmts(x.StmtList) case *syntax.Subshell: r2 := r.sub() r2.stmts(x.StmtList) r.exit = r2.exit r.setErr(r2.err) case *syntax.CallExpr: fields := r.Fields(x.Args...) if len(fields) == 0 { for _, as := range x.Assigns { vr, _ := r.lookupVar(as.Name.Value) vr.Value = r.assignVal(as, "") r.setVar(as.Name.Value, as.Index, vr) } break } for _, as := range x.Assigns { val := r.assignVal(as, "") // we know that inline vars must be strings r.cmdVars[as.Name.Value] = string(val.(StringVal)) if as.Name.Value == "IFS" { r.ifsUpdated() defer r.ifsUpdated() } } r.call(x.Args[0].Pos(), fields) // cmdVars can be nuked here, as they are never useful // again once we nest into further levels of inline // vars. for k := range r.cmdVars { delete(r.cmdVars, k) } case *syntax.BinaryCmd: switch x.Op { case syntax.AndStmt: r.stmt(x.X) if r.exit == 0 { r.stmt(x.Y) } case syntax.OrStmt: r.stmt(x.X) if r.exit != 0 { r.stmt(x.Y) } case syntax.Pipe, syntax.PipeAll: pr, pw := io.Pipe() r2 := r.sub() r2.Stdout = pw if x.Op == syntax.PipeAll { r2.Stderr = pw } else { r2.Stderr = r.Stderr } r.Stdin = pr var wg sync.WaitGroup wg.Add(1) go func() { r2.stmt(x.X) pw.Close() wg.Done() }() r.stmt(x.Y) pr.Close() wg.Wait() if r.shellOpts[optPipeFail] && r2.exit > 0 && r.exit == 0 { r.exit = r2.exit } r.setErr(r2.err) } case *syntax.IfClause: r.stmts(x.Cond) if r.exit == 0 { r.stmts(x.Then) break } r.exit = 0 r.stmts(x.Else) case *syntax.WhileClause: for !r.stop() { r.stmts(x.Cond) stop := (r.exit == 0) == x.Until r.exit = 0 if stop || r.loopStmtsBroken(x.Do) { break } } case *syntax.ForClause: switch y := x.Loop.(type) { case *syntax.WordIter: name := y.Name.Value for _, field := range r.Fields(y.Items...) { r.setVarString(name, field) if r.loopStmtsBroken(x.Do) { break } } case *syntax.CStyleLoop: r.arithm(y.Init) for r.arithm(y.Cond) != 0 { if r.loopStmtsBroken(x.Do) { break } r.arithm(y.Post) } } case *syntax.FuncDecl: r.setFunc(x.Name.Value, x.Body) case *syntax.ArithmCmd: r.exit = oneIf(r.arithm(x.X) == 0) case *syntax.LetClause: var val int for _, expr := range x.Exprs { val = r.arithm(expr) } r.exit = oneIf(val == 0) case *syntax.CaseClause: str := r.loneWord(x.Word) for _, ci := range x.Items { for _, word := range ci.Patterns { pat := r.lonePattern(word) if match(pat, str) { r.stmts(ci.StmtList) return } } } case *syntax.TestClause: r.exit = 0 if r.bashTest(x.X) == "" && r.exit == 0 { // to preserve exit code 2 for regex // errors, etc r.exit = 1 } case *syntax.DeclClause: var modes []string valType := "" switch x.Variant.Value { case "local": if !r.inFunc { r.errf("local: can only be used in a function\n") r.exit = 1 return } modes = append(modes, "l") case "export": modes = append(modes, "-x") case "readonly": modes = append(modes, "-r") case "nameref": modes = append(modes, "-n") } for _, opt := range x.Opts { switch s := r.loneWord(opt); s { case "-x", "-r", "-n": modes = append(modes, s) case "-a", "-A": valType = s default: r.errf("declare: invalid option %q\n", s) r.exit = 2 return } } for _, as := range x.Assigns { for _, as := range r.expandAssigns(as) { name := as.Name.Value vr, _ := r.lookupVar(as.Name.Value) vr.Value = r.assignVal(as, valType) for _, mode := range modes { switch mode { case "l": vr.Local = true case "-x": vr.Exported = true case "-r": vr.ReadOnly = true case "-n": vr.NameRef = true } } r.setVar(name, as.Index, vr) } } case *syntax.TimeClause: start := time.Now() if x.Stmt != nil { r.stmt(x.Stmt) } real := time.Since(start) r.outf("\n") r.outf("real\t%s\n", elapsedString(real)) // TODO: can we do these? r.outf("user\t0m0.000s\n") r.outf("sys\t0m0.000s\n") default: panic(fmt.Sprintf("unhandled command node: %T", x)) } } func elapsedString(d time.Duration) string { min := int(d.Minutes()) sec := math.Remainder(d.Seconds(), 60.0) return fmt.Sprintf("%dm%.3fs", min, sec) } func (r *Runner) stmts(sl syntax.StmtList) { for _, stmt := range sl.Stmts { r.stmt(stmt) } } func (r *Runner) redir(rd *syntax.Redirect) (io.Closer, error) { if rd.Hdoc != nil { hdoc := r.loneWord(rd.Hdoc) r.Stdin = strings.NewReader(hdoc) return nil, nil } orig := &r.Stdout if rd.N != nil { switch rd.N.Value { case "1": case "2": orig = &r.Stderr } } arg := r.loneWord(rd.Word) switch rd.Op { case syntax.WordHdoc: r.Stdin = strings.NewReader(arg + "\n") return nil, nil case syntax.DplOut: switch arg { case "1": *orig = r.Stdout case "2": *orig = r.Stderr } return nil, nil case syntax.RdrIn, syntax.RdrOut, syntax.AppOut, syntax.RdrAll, syntax.AppAll: // done further below // case syntax.DplIn: default: panic(fmt.Sprintf("unhandled redirect op: %v", rd.Op)) } mode := os.O_RDONLY switch rd.Op { case syntax.AppOut, syntax.AppAll: mode = os.O_RDWR | os.O_CREATE | os.O_APPEND case syntax.RdrOut, syntax.RdrAll: mode = os.O_RDWR | os.O_CREATE | os.O_TRUNC } f, err := r.open(r.relPath(arg), mode, 0644, true) if err != nil { return nil, err } switch rd.Op { case syntax.RdrIn: r.Stdin = f case syntax.RdrOut, syntax.AppOut: *orig = f case syntax.RdrAll, syntax.AppAll: r.Stdout = f r.Stderr = f default: panic(fmt.Sprintf("unhandled redirect op: %v", rd.Op)) } return f, nil } func (r *Runner) loopStmtsBroken(sl syntax.StmtList) bool { oldInLoop := r.inLoop r.inLoop = true defer func() { r.inLoop = oldInLoop }() for _, stmt := range sl.Stmts { r.stmt(stmt) if r.contnEnclosing > 0 { r.contnEnclosing-- return r.contnEnclosing > 0 } if r.breakEnclosing > 0 { r.breakEnclosing-- return true } } return false } func (r *Runner) ifsUpdated() { runes := r.getVar("IFS") r.ifsJoin = "" if len(runes) > 0 { r.ifsJoin = runes[:1] } r.ifsRune = func(r rune) bool { for _, r2 := range runes { if r == r2 { return true } } return false } } type returnCode uint8 func (returnCode) Error() string { return "returned" } func (r *Runner) call(pos syntax.Pos, args []string) { if r.stop() { return } name := args[0] if body := r.Funcs[name]; body != nil { // stack them to support nested func calls oldParams := r.Params r.Params = args[1:] oldInFunc := r.inFunc oldFuncVars := r.funcVars r.funcVars = nil r.inFunc = true r.stmt(body) r.Params = oldParams r.funcVars = oldFuncVars r.inFunc = oldInFunc if code, ok := r.err.(returnCode); ok { r.err = nil r.exit = int(code) } return } if isBuiltin(name) { r.exit = r.builtinCode(pos, name, args[1:]) return } r.exec(args) } func (r *Runner) exec(args []string) { path := r.lookPath(args[0]) err := r.Exec(r.ctx(), path, args) switch x := err.(type) { case nil: r.exit = 0 case ExitCode: r.exit = int(x) default: // module's custom fatal error r.setErr(err) } } func (r *Runner) open(path string, flags int, mode os.FileMode, print bool) (io.ReadWriteCloser, error) { f, err := r.Open(r.ctx(), path, flags, mode) switch err.(type) { case nil: case *os.PathError: if print { r.errf("%v\n", err) } default: // module's custom fatal error r.setErr(err) } return f, err } func (r *Runner) stat(name string) (os.FileInfo, error) { return os.Stat(r.relPath(name)) } func (r *Runner) findExecutable(file string) error { d, err := r.stat(file) if err != nil { return err } if m := d.Mode(); !m.IsDir() && m&0111 != 0 { return nil } return os.ErrPermission } // splitList is like filepath.SplitList, but always using the unix path // list separator ':'. func splitList(path string) []string { if path == "" { return []string{""} } return strings.Split(path, ":") } func (r *Runner) lookPath(file string) string { if strings.Contains(file, "/") { if err := r.findExecutable(file); err == nil { return file } return "" } path := r.getVar("PATH") for _, dir := range splitList(path) { var path string switch dir { case "", ".": // otherwise "foo" won't be "./foo" path = "." + string(filepath.Separator) + file default: path = filepath.Join(dir, file) } if err := r.findExecutable(path); err == nil { return path } } return "" }
package crawl import ( "testing" "time" . "./base" ) func _d(s string) time.Time { loc, _ := time.LoadLocation("Asia/Shanghai") d, _ := time.ParseInLocation("2006-01-02 15:04:05", s, loc) return d } func TestM1s2M5s(t *testing.T) { type Case struct { m1 []Tdata m5 []Tdata } tests := []Case{ // 09:35 [09:30, 09:35) {[]Tdata{ {Time: _d("2000-01-01 09:30:00"), Volume: 1}, {Time: _d("2000-01-01 09:31:00"), Volume: 1}, {Time: _d("2000-01-01 09:32:00"), Volume: 1}, {Time: _d("2000-01-01 09:34:59"), Volume: 1}, {Time: _d("2000-01-01 09:35:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 09:35:00"), Volume: 4}, {Time: _d("2000-01-01 09:40:00"), Volume: 1}, }}, // 11:30 [11:25, 11:35) {[]Tdata{ {Time: _d("2000-01-01 11:25:00"), Volume: 1}, {Time: _d("2000-01-01 11:26:00"), Volume: 1}, {Time: _d("2000-01-01 11:27:00"), Volume: 1}, {Time: _d("2000-01-01 11:30:00"), Volume: 1}, {Time: _d("2000-01-01 11:31:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 11:30:00"), Volume: 5}, }}, // 13:05 [13:00, 13:05) {[]Tdata{ {Time: _d("2000-01-01 13:00:00"), Volume: 1}, {Time: _d("2000-01-01 13:01:00"), Volume: 1}, {Time: _d("2000-01-01 13:02:00"), Volume: 1}, {Time: _d("2000-01-01 13:04:59"), Volume: 1}, {Time: _d("2000-01-01 13:05:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 13:05:00"), Volume: 4}, {Time: _d("2000-01-01 13:10:00"), Volume: 1}, }}, // 15:00 [14:55, 15:05) {[]Tdata{ {Time: _d("2000-01-01 14:55:00"), Volume: 1}, {Time: _d("2000-01-01 14:59:00"), Volume: 1}, {Time: _d("2000-01-01 15:00:00"), Volume: 1}, {Time: _d("2000-01-01 15:04:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 15:00:00"), Volume: 4}, }}, } for i, l := 0, len(tests); i < l; i++ { m1s := Tdatas{Data: tests[i].m1} m5s := Tdatas{} m5s.MergeFrom(&m1s, false, Minute5end) if len(m5s.Data) != len(tests[i].m5) { t.Error( "For", "case", i, "expected", "len eq", "got", "neq", m5s.Data, ) continue } for k := 0; k < len(m5s.Data); k++ { if m5s.Data[k].Volume != tests[i].m5[k].Volume { t.Error( "For", "case", i, "data[", k, "]", "expected", "voleume eq", "got", "neq", m5s.Data[k], ) } } } } func TestM1s2M30s(t *testing.T) { type Case struct { m1 []Tdata m30 []Tdata } tests := []Case{ // 10:00 [09:00, 10:00) {[]Tdata{ {Time: _d("2000-01-01 09:30:00"), Volume: 1}, {Time: _d("2000-01-01 09:31:00"), Volume: 1}, {Time: _d("2000-01-01 09:32:00"), Volume: 1}, {Time: _d("2000-01-01 09:59:59"), Volume: 1}, {Time: _d("2000-01-01 10:00:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 10:00:00"), Volume: 4}, {Time: _d("2000-01-01 10:30:00"), Volume: 1}, }}, // 11:30 [11:00, 11:35) {[]Tdata{ {Time: _d("2000-01-01 11:00:00"), Volume: 1}, {Time: _d("2000-01-01 11:29:00"), Volume: 1}, {Time: _d("2000-01-01 11:30:00"), Volume: 1}, {Time: _d("2000-01-01 11:31:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 11:30:00"), Volume: 4}, }}, // 15:00 [14:30, 15:05) {[]Tdata{ {Time: _d("2000-01-01 14:30:00"), Volume: 1}, {Time: _d("2000-01-01 14:59:00"), Volume: 1}, {Time: _d("2000-01-01 15:00:00"), Volume: 1}, {Time: _d("2000-01-01 15:04:00"), Volume: 1}, }, []Tdata{ {Time: _d("2000-01-01 15:00:00"), Volume: 4}, }}, } for i, l := 0, len(tests); i < l; i++ { m1s := Tdatas{Data: tests[i].m1} m30s := Tdatas{} m30s.MergeFrom(&m1s, false, Minute30end) if len(m30s.Data) != len(tests[i].m30) { t.Error( "For", "case", i, "expected", "len eq", "got", "neq", m30s.Data, ) continue } for k := 0; k < len(m30s.Data); k++ { if m30s.Data[k].Volume != tests[i].m30[k].Volume { t.Error( "For", "case", i, "data[", k, "]", "expected", "voleume eq", "got", "neq", m30s.Data[k], ) } } } } func TestTicks2M1s(t *testing.T) { type date_pair struct { date []string len int } tests := []date_pair{ {[]string{ "2000-01-01 10:00:00", "2000-01-02 10:00:00", "2000-01-02 10:01:00", }, 3}, } fmt := "2006-01-02 15:04:05" for i, l := 0, len(tests); i < l; i++ { stock := Stock{} stock.Ticks = stringSlice2Ticks(tests[i].date) for j := 10; j > 0; j-- { stock.Ticks2M1s() if len(stock.M1s.Data) != tests[i].len { t.Error( "For", "case", i, tests[i], "expected", "m1s.data len=", tests[i].len, "got", len(stock.M1s.Data), stock.M1s.Data, ) } for k := 0; k < len(tests[i].date); k++ { ts := stock.M1s.Data[k].Time.Format(fmt[:len(tests[i].date[k])]) if ts != tests[i].date[k] { t.Error( "For", "case", i, "date[", k, "]", "expected", tests[i].date[k], "got", ts, ) } } } } }
// +build nobootstrap // Contains routines to marshal between internal structures and // proto-generated equivalents. // The duplication is unfortunate but it's preferable to needing // to run proto / gRPC compilers at bootstrap time. package follow import ( "errors" "time" "core" pb "follow/proto/build_event" ) // toProto converts an internal test result into a proto type. func toProto(r *core.BuildResult) *pb.BuildEventResponse { t := &r.Tests return &pb.BuildEventResponse{ ThreadId: int32(r.ThreadID), Timestamp: r.Time.UnixNano(), BuildLabel: toProtoBuildLabel(r.Label), Status: pb.BuildResultStatus(r.Status), Error: toProtoError(r.Err), Description: r.Description, TestResults: &pb.TestResults{ NumTests: int32(t.NumTests), Passed: int32(t.Passed), Failed: int32(t.Failed), ExpectedFailures: int32(t.ExpectedFailures), Skipped: int32(t.Skipped), Flakes: int32(t.Flakes), Failures: toProtoTestFailures(t.Failures), Passes: t.Passes, Output: t.Output, Duration: int64(t.Duration), Cached: t.Cached, TimedOut: t.TimedOut, }, } } // toProtos converts a slice of internal test results to a slice of protos. func toProtos(results []*core.BuildResult, active, done int) []*pb.BuildEventResponse { ret := make([]*pb.BuildEventResponse, 0, len(results)) for _, r := range results { if r != nil { p := toProto(r) p.NumActive = int64(active) p.NumDone = int64(done) ret = append(ret, p) } } return ret } // toProtoTestFailures converts a slice of test failures to the proto equivalent. func toProtoTestFailures(failures []core.TestFailure) []*pb.TestFailure { ret := make([]*pb.TestFailure, len(failures)) for i, f := range failures { ret[i] = &pb.TestFailure{ Name: f.Name, Type: f.Type, Traceback: f.Traceback, Stdout: f.Stdout, Stderr: f.Stderr, } } return ret } // toProtoBuildLabel converts the internal build label type to a proto equivalent. func toProtoBuildLabel(label core.BuildLabel) *pb.BuildLabel { return &pb.BuildLabel{PackageName: label.PackageName, Name: label.Name} } // toProtoError converts an error to a string if the error is non-nil. func toProtoError(err error) string { if err != nil { return err.Error() } return "" } // fromProto converts from a proto type into the internal equivalent. func fromProto(r *pb.BuildEventResponse) *core.BuildResult { t := r.TestResults return &core.BuildResult{ ThreadID: int(r.ThreadId), Time: time.Unix(0, r.Timestamp), Label: fromProtoBuildLabel(r.BuildLabel), Status: core.BuildResultStatus(r.Status), Err: fromProtoError(r.Error), Description: r.Description, Tests: core.TestResults{ NumTests: int(t.NumTests), Passed: int(t.Passed), Failed: int(t.Failed), ExpectedFailures: int(t.ExpectedFailures), Skipped: int(t.Skipped), Flakes: int(t.Flakes), Failures: fromProtoTestFailures(t.Failures), Passes: t.Passes, Output: t.Output, Duration: time.Duration(t.Duration), Cached: t.Cached, TimedOut: t.TimedOut, }, } } // fromProtoTestFailures converts a slice of proto test failures to the internal equivalent. func fromProtoTestFailures(failures []*pb.TestFailure) []core.TestFailure { ret := make([]core.TestFailure, len(failures)) for i, f := range failures { ret[i] = core.TestFailure{ Name: f.Name, Type: f.Type, Traceback: f.Traceback, Stdout: f.Stdout, Stderr: f.Stderr, } } return ret } // fromProtoBuildLabel converts a proto build label to the internal version. func fromProtoBuildLabel(label *pb.BuildLabel) core.BuildLabel { return core.BuildLabel{PackageName: label.PackageName, Name: label.Name} } // fromProtoBuildLabels converts a series of proto build labels to a slice of internal ones. func fromProtoBuildLabels(labels []*pb.BuildLabel) []core.BuildLabel { ret := make([]core.BuildLabel, len(labels)) for i, l := range labels { ret[i] = fromProtoBuildLabel(l) } return ret } // fromProtoError converts a proto string into an error if it's non-empty. func fromProtoError(s string) error { if s != "" { return errors.New(s) } return nil } // resourceToProto converts the internal resource stats to a proto message. func resourceToProto(stats *core.SystemStats) *pb.ResourceUsageResponse { return &pb.ResourceUsageResponse{ NumCpus: int32(stats.CPU.Count), CpuUse: stats.CPU.Used, IoWait: stats.CPU.IOWait, MemTotal: stats.Memory.Total, MemUsed: stats.Memory.Used, } } // resourceFromProto converts the proto message back to the internal type. func resourceFromProto(r *pb.ResourceUsageResponse) *core.SystemStats { s := &core.SystemStats{} s.CPU.Count = int(r.NumCpus) s.CPU.Used = r.CpuUse s.CPU.IOWait = r.IoWait s.Memory.Total = r.MemTotal s.Memory.Used = r.MemUsed s.Memory.UsedPercent = 100.0 * float64(r.MemUsed) / float64(r.MemTotal) return s }
package models // RepositoryList contains code repositories implemented by a certain paper. type RepositoryList struct { Count int64 `json:"count"` Next *string `json:"next"` Previous *string `json:"previous"` Results []Repository `json:"results"` } type Repository struct { URL string `json:"url"` IsOfficial bool `json:"is_official"` Description string `json:"description"` Stars int `json:"stars"` Framework string `json:"framework"` }
package models import ( "github.com/gophergala2016/source/core/foundation" ) type UserTagRepository struct { RootRepository } func NewUserTagRepository(ctx foundation.Context) *UserTagRepository { return &UserTagRepository{ RootRepository: NewRootRepository(ctx), } } func (r *UserTagRepository) FindLatestByUserIDAndCollection(userID uint64, limit, offset int) ([]UserTag, error) { var ents []UserTag if err := r.Orm.Where("user_id = ?", userID).Limit(limit).Offset(offset).Order("score desc").Find(&ents).Error; err != nil { return ents, err } return ents, nil } func (r *UserTagRepository) GetFirstOrCreate(ent *UserTag) (*UserTag, error) { if err := r.Orm.Where("user_id = ? AND tag_id = ?", ent.UserID, ent.TagID).FirstOrCreate(ent).Error; err != nil { return nil, err } return ent, nil } func (r *UserTagRepository) GetByID(userID, tagID uint64) (*UserTag, error) { ent := new(UserTag) if err := r.Orm.Where("user_id = ? AND tag_id = ?", userID, tagID).First(ent).Error; err != nil { return nil, err } return ent, nil } func (r *UserTagRepository) UpdateByID(ent *UserTag) (*UserTag, error) { if err := r.Orm.Where("user_id = ? AND tag_id = ?", ent.UserID, ent.TagID).Save(ent).Error; err != nil { return nil, err } return ent, nil }
package main import ( "fmt" "net" "time" "github.com/rrawrriw/ite/dhcp" "github.com/rrawrriw/ite/dictator" ) func NewCluster() (dictator.Mission, dictator.ResponseChan) { response := make(dictator.ResponseChan) dhcpInAddr := net.UDPAddr{ IP: net.ParseIP("255.255.255.255"), Port: 68, } dhcpOutAddr := net.UDPAddr{ IP: net.ParseIP("255.255.255.255"), Port: 67, } mission := func(nCtx dictator.NodeContext) { log := nCtx.AppContext.Log go func() { log.Debug.Println(nCtx.NodeID, "- Start to build new cluster") ips, timeout, err := dhcp.RequestIPAddr(dhcpInAddr, dhcpOutAddr, 10*time.Second, "eth0") if err != nil { log.Error.Println(nCtx.NodeID, "-", err) return } // Wait for DHCP Server Response for { select { case <-timeout: log.Debug.Println(nCtx.NodeID, "- DHCP IP request run out of time") case ip := <-ips: log.Debug.Println(nCtx.NodeID, "- got", ip) case <-nCtx.AppContext.DoneChan: return case <-nCtx.SuicideChan: return } } // Send AssignIP commands until a slave response packet, err := dictator.NewCommandPacket(nCtx.NodeID, "AssignIP", nil) if err != nil { log.Error.Println(err) nCtx.AppContext.Done() } go func() { select { case <-nCtx.AppContext.DoneChan: return case <-nCtx.SuicideChan: return default: nCtx.UDPOut <- packet time.Sleep(1 * time.Second) } }() // Wait for a slave to response the AssingIP command for { select { case <-response: log.Debug.Println(nCtx.NodeID, "- Command successfully done") log.Debug.Println(nCtx.NodeID, "- Send reboot command") packet, err := dictator.NewCommandPacket(nCtx.NodeID, "Reboot", nil) if err != nil { log.Error.Println(err) nCtx.AppContext.Done() } nCtx.UDPOut <- packet time.Sleep(1 * time.Second) nCtx.AppContext.Done() case <-nCtx.AppContext.DoneChan: return case <-nCtx.SuicideChan: return } } }() } return mission, response } func AssignIPHandler(nCtx dictator.NodeContext, payload dictator.DictatorPayload) error { log := nCtx.AppContext.Log log.Debug.Println(nCtx.NodeID, "- Receive command AssignIP from", payload.DictatorID) response, err := dictator.NewCommandResponsePacket(payload.DictatorID, nCtx.NodeID, 1, nil) if err != nil { return err } nCtx.UDPOut <- response return nil } func RebootHandler(nCtx dictator.NodeContext, payload dictator.DictatorPayload) error { log := nCtx.AppContext.Log log.Debug.Println(nCtx.NodeID, "- Receive command Reboot from", payload.DictatorID) nCtx.AppContext.Done() return nil } func main() { inAddr := net.UDPAddr{ IP: net.ParseIP("255.255.255.255"), Port: 43001, } connIn, err := net.ListenUDP("udp", &inAddr) if err != nil { fmt.Println(err) return } outAddr := net.UDPAddr{ IP: net.ParseIP("255.255.255.255"), Port: 43001, } connOut, err := net.DialUDP("udp", nil, &outAddr) if err != nil { fmt.Println(err) return } conns := []*net.UDPConn{ connIn, connOut, } ctx := dictator.NewContextWithConn(conns) udpIn, err := dictator.UDPInbox(ctx, connIn) if err != nil { fmt.Println(err) return } udpOut, err := dictator.UDPOutbox(ctx, connOut) if err != nil { fmt.Println(err) return } cmdRouter := dictator.CommandRouter{} cmdRouter.AddHandler("AssignIP", AssignIPHandler) cmdRouter.AddHandler("Reboot", RebootHandler) m, response := NewCluster() mission := dictator.MissionSpecs{ Mission: m, CommandRouter: cmdRouter, ResponseChan: response, } dictator.Node(ctx, udpIn, udpOut, mission) <-ctx.DoneChan }
package main import ( _"github.com/go-sql-driver/mysql" "testxorm/controllers" "testxorm/db" // "testxorm/model" // "net/http" ) func main(){ // book:=model.Book{ // Name:"book2", // } // http.HandleFunc("/insert",controllers.InsertBook1) controllers.WriteIo("/book",db.GetJson) controllers.WriteIo("/insert",db.InsertBook1) // view.WriteIo("/hello",controllers.InsertBook(&book)) // view.WriteIo("/bye","bye") controllers.Run() }
package smpp34 var ( reqGNFields = []string{} ) type GenericNack struct { *Header mandatoryFields map[string]Field tlvFields map[uint16]*TLVField } func NewGenericNack(hdr *Header) (*GenericNack, error) { s := &GenericNack{Header: hdr} return s, nil } func (s *GenericNack) GetField(f string) Field { return nil } func (s *GenericNack) Fields() map[string]Field { return s.mandatoryFields } func (s *GenericNack) MandatoryFieldsList() []string { return reqGNFields } func (s *GenericNack) Ok() bool { return true } func (s *GenericNack) GetHeader() *Header { return s.Header } func (s *GenericNack) SetField(f string, v interface{}) error { return FieldValueErr } func (s *GenericNack) SetSeqNum(i uint32) { s.Header.Sequence = i } func (s *GenericNack) SetTLVField(t, l int, v []byte) error { return TLVFieldPduErr } func (s *GenericNack) TLVFields() map[uint16]*TLVField { return s.tlvFields } func (s *GenericNack) writeFields() []byte { return []byte{} } func (s *GenericNack) Writer() []byte { b := s.writeFields() h := packUi32(uint32(len(b) + 16)) h = append(h, packUi32(uint32(GENERIC_NACK))...) h = append(h, packUi32(uint32(s.Header.Status))...) h = append(h, packUi32(s.Header.Sequence)...) return append(h, b...) }
package controllers import ( "crud/models" "strconv" "strings" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/shopspring/decimal" ) type ConsultaController struct { beego.Controller } func (c *ConsultaController) Get() { c.TplName = "consulta.tpl" } func (c *ConsultaController) Post() { c.TplName = "consulta.tpl" codigo, err := strconv.Atoi(c.GetString("codigo")) p := models.Produto{Id: codigo} o := orm.NewOrm() err = o.Read(&p) if err == orm.ErrNoRows { c.Data["msg"] = "Não existe produto com esse código !" } else { codigo := strconv.Itoa(p.Id) nome := p.Nome preco := decimal.NewFromFloat(p.Preco).StringFixed(2) c.Data["codigo"] = codigo c.Data["nome"] = nome c.Data["preco"] = strings.Replace(preco, ".", ",", -1) } }
package silverfish import ( entity "silverfish/silverfish/entity" interf "silverfish/silverfish/interface" usecase "silverfish/silverfish/usecase" ) // Silverfish export type Silverfish struct { Auth *Auth Admin *Admin User *User Novel *Novel Comic *Comic } // New export func New( hashSalt *string, crawlDuration int, userInf, novelInf, comicInf *entity.MongoInf, ) *Silverfish { sf := new(Silverfish) novelFetchers := map[string]interf.INovelFetcher{ "www.77xsw.la": usecase.NewFetcher77xsw("www.77xsw.la"), "tw.hjwzw.com": usecase.NewFetcherHjwzw("tw.hjwzw.com"), "www.biquge.com.cn": usecase.NewFetcherBiquge("www.biquge.com.cn"), "tw.aixdzs.com": usecase.NewFetcherAixdzs("tw.aixdzs.com"), "www.bookbl.com": usecase.NewFetcherBookbl("www.bookbl.com"), } comicFetchers := map[string]interf.IComicFetcher{ //"www.99comic.co": usecase.NewFetcher99Comic("www.99comic.co"), "www.nokiacn.net": usecase.NewFetcherNokiacn("www.nokiacn.net"), "www.cartoonmad.com": usecase.NewFetcherCartoonmad("www.cartoonmad.com"), "comicbus.com": usecase.NewFetcherComicbus("comicbus.com"), "www.manhuaniu.com": usecase.NewFetcherManhuaniu("www.manhuaniu.com"), "www.mangabz.com": usecase.NewFetcherMangabz("www.mangabz.com"), "m.happymh.com": usecase.NewFetcherHappymh("m.happymh.com"), "www.mfhmh.com": usecase.NewFetcherMfhmh("www.mfhmh.com"), // Oops... "www.ikanwzd.top": usecase.NewFetcherIkanwzd("www.ikanwzd.top"), // Oops... } sf.Auth = NewAuth(hashSalt, userInf) sf.Novel = NewNovel(sf.Auth, novelInf, novelFetchers, crawlDuration) sf.Comic = NewComic(sf.Auth, comicInf, comicFetchers, crawlDuration) sf.Admin = NewAdmin(userInf) sf.User = NewUser(userInf) return sf }
package removeDuplicates func removeDuplicates(nums []int) int { //[1,1,2] if len(nums) <= 0 { return 0 } count := 1 i, j := 0, 0 for j = 1; j < len(nums); j++ { if nums[j] == nums[j-1] { continue } count++ i++ nums[i] = nums[j] } return count }
package main import ( "log" "os" "os/signal" "syscall" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) var ( clientset *kubernetes.Clientset ) func main() { // setup kubernetes client clsConfig, err := rest.InClusterConfig() if err != nil { log.Fatal(err) } clientset, err = kubernetes.NewForConfig(clsConfig) if err != nil { log.Fatal(err) } loadConfig() // check run mode and start controller or target log.Printf("Starting gke-service-sync in '%s' mode.", defaultConfig.RunMode) switch defaultConfig.RunMode { case runModeController: go syncServicesController() case runModeTarget: go syncServicesTarget() default: go syncServicesController() go syncServicesTarget() } // handle shutdown shutdown := make(chan os.Signal) signal.Notify(shutdown, syscall.SIGTERM, syscall.SIGINT) // wait for shutdown <-shutdown log.Printf("Exit") }
package main import "fmt" func two_string() (string, string) { return "zhong", "ting" } func main() { z, t := two_string() t, n := two_string() fmt.Println(z, t, n) var y string g, y := two_string() fmt.Println(g, y) // 结论: // 都可以实现变量重声明 }
package main import ( "fmt" "golang.org/x/tour/tree" ) // Walk walks the tree t sending all values // from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { Inorder(t, ch) } func Inorder(t *tree.Tree, ch chan int) { if t.Left != nil { Inorder(t.Left, ch) } ch <- t.Value if t.Right != nil { Inorder(t.Right, ch) } } // Same determines whether the trees // t1 and t2 contain the same values. func Same(t1, t2 *tree.Tree) bool { channel1 := make(chan int, 10) channel2 := make(chan int, 10) go Walk(t1, channel1) go Walk(t2, channel2) for i := 0; i < cap(channel1); i++ { if <-channel1 != <-channel2 { return false } } return true } func main() { result := Same(tree.New(1), tree.New(2)) if result { fmt.Println("Same") } else { fmt.Println("Not Same") } }
package sol import "testing" func TestBasic(t *testing.T) { testcases := []struct { input []int want int }{ { input: []int{7, 1, 5, 3, 6, 4}, want: 5, }, { input: []int{7, 6, 4, 3, 1}, want: 0, }, { input: []int{}, want: 0, }, { input: []int{2, 1, 4}, want: 3, }, { input: []int{2, 4, 1}, want: 2, }, { input: []int{3, 2, 6, 5, 0, 3}, want: 4, }, } for i, tt := range testcases { ans := maxProfit4(tt.input) if ans != tt.want { t.Fatalf("case %d it should be %d, but got: %d", i, tt.want, ans) } } }
package config import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/instructure-bridge/muss/testutil" ) func assertExpandWithWarnings(t *testing.T, spec, exp, expStderr, msg string) { var expanded string stderr := testutil.CaptureStderr(t, func() { expanded = expandWarnOnEmpty(spec) }) assert.Equal(t, expStderr, stderr, "warns to stderr") assert.Equal(t, exp, expanded, msg) } func TestShellVarExpand(t *testing.T) { t.Run("unsupported syntax", func(t *testing.T) { assert.PanicsWithValue(t, "Invalid interpolation format: '${MUSS_TEST_VAR:+nullorunset}'", func() { expand("[${MUSS_TEST_VAR:+nullorunset}]") }, ":+") }) t.Run("var unset", func(t *testing.T) { os.Unsetenv("MUSS_TEST_VAR") assert.Equal(t, "[]", expand("[$MUSS_TEST_VAR]"), "var") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR}]"), "braces") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR:-}]"), "default empty") assert.Equal(t, "[nullorunset]", expand("[${MUSS_TEST_VAR:-nullorunset}]"), ":-") assert.Equal(t, "[unset]", expand("[${MUSS_TEST_VAR-unset}]"), "-") assert.PanicsWithValue(t, "Variable 'MUSS_TEST_VAR' is required: nullorunset", func() { expand("[${MUSS_TEST_VAR:?nullorunset}]") }, ":?") assert.PanicsWithValue(t, "Variable 'MUSS_TEST_VAR' is required: unset", func() { expand("[${MUSS_TEST_VAR?unset}]") }, "?") assertExpandWithWarnings(t, "[${MUSS_TEST_VAR}]", "[]", "${MUSS_TEST_VAR} is blank\n", "expanded blank") }) t.Run("var blank", func(t *testing.T) { os.Setenv("MUSS_TEST_VAR", "") assert.Equal(t, "[]", expand("[$MUSS_TEST_VAR]"), "var") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR}]"), "braces") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR:-}]"), "default empty") assert.Equal(t, "[nullorunset]", expand("[${MUSS_TEST_VAR:-nullorunset}]"), ":-") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR-unset}]"), "-") assert.PanicsWithValue(t, "Variable 'MUSS_TEST_VAR' is required: nullorunset", func() { expand("[${MUSS_TEST_VAR:?nullorunset}]") }, ":?") assert.Equal(t, "[]", expand("[${MUSS_TEST_VAR?unset}]"), "?") assertExpandWithWarnings(t, "[${MUSS_TEST_VAR}]", "[]", "${MUSS_TEST_VAR} is blank\n", "expanded blank") }) t.Run("var nonblank", func(t *testing.T) { os.Setenv("MUSS_TEST_VAR", "not blank") assert.Equal(t, "[not blank]", expand("[$MUSS_TEST_VAR]"), "var") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR}]"), "braces") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR:-}]"), "default empty") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR:-nullorunset}]"), ":-") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR-unset}]"), "-") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR:?nullorunset}]"), ":?") assert.Equal(t, "[not blank]", expand("[${MUSS_TEST_VAR?nullorunset}]"), "?") assertExpandWithWarnings(t, "[${MUSS_TEST_VAR}]", "[not blank]", "", "expanded non blank") }) }
// A Tour of Go : Packages, variables, and functions // https://go-tour-jp.appspot.com/basics/1 package main import ( "fmt" "math/cmplx" "math/rand" ) // varステートメントで変数を宣言する var c, python, java bool func main() { { // パッケージ名はインポートパスの最後の要素と同じ名前になる fmt.Println("1. ", "My Favorite number is", rand.Intn(10)) } { fmt.Println("2. ", "add(10, 11) = ", add(10, 11)) } { // 関数から複数の戻り値を受け取る a, b := swap("World!!", "Hello") fmt.Println("3. ", a, b) } { var i int fmt.Println("4. ", i, c, python, java) } { // var宣言では、変数毎に初期化することができる // 初期化している場合、型の宣言を省略できる var c, python, java = true, false, "no!" fmt.Println("5. ", c, python, java) } { // 関数内ではvar宣言の代わりに、:=を使い、暗黙的な型宣言ができる var i, j int = 1, 2 k := 3 c, python, java := true, false, "no!" fmt.Println("6. ", i, j, k, c, python, java) } { // go言語の基本型(組み込み型) // bool // string // int, int8, int16, int32, int64 // uint, uint8, uint16, uint32, uint64, uintptr // byte (uint8の別名) // rune (int32の別名。Unicodeのコードポイントを表す) // float32, float64 // complex64, complex128 (複素数) // int, uint, uintptr型は32bitシステムでは32bit, 64bitシステムでは64bitになる // 符号なし整数の型は、使うための特別な理由がない限り控える var ( ToBe bool = false MaxInt uint64 = 1<<64 - 1 z complex128 = cmplx.Sqrt(-5 + 12i) ) fmt.Printf("7-1. Type: %T Value: %v\n", ToBe, ToBe) fmt.Printf("7-2. Type: %T Value: %v\n", MaxInt, MaxInt) fmt.Printf("7-3. Type: %T Value: %v\n", z, z) } { // 型変換 var i int = 42 var f float64 = float64(i) var u uint = uint(f) // 明示的な型を指定せずに変数を宣言する場合、変数の型は右側の変数から型推論される j := i fmt.Println("8. ", i, f, u, j) } { // 定数はconstキーワードを使う // 文字、文字列、boolean、数値のみ定数にできる const PI = 3.14 fmt.Println("9. Happy", PI, "Day") } } // 頭文字が大文字で始まる場合、外部から参照できる(public)。小文字だとprivate // goは変数名の後ろに型名を書く func add(x int, y int) int { return x + y } // 関数は複数の戻り値を返すことができる func swap(x, y string) (string, string) { return y, x } // 戻り値となる変数名に名前をつけることができる // 名前をつけると、returnステートメントに何も書かずに戻すことができる // 長い関数で使うと読みやすさに悪影響があるので注意 func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return }
/* Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package client import ( "bufio" "bytes" "context" "fmt" "github.com/hyperledger/fabric/common/flogging" "github.com/hyperledger/fabric/common/localmsp" "github.com/hyperledger/fabric/common/tools/protolator" "github.com/hyperledger/fabric/core/comm" mspmgmt "github.com/hyperledger/fabric/msp/mgmt" ordererConfig "github.com/hyperledger/fabric/orderer/common/localconfig" "github.com/hyperledger/fabric/protos/common" ab "github.com/hyperledger/fabric/protos/orderer" "github.com/hyperledger/fabric/protos/utils" "github.com/pkg/errors" "time" ) var logger = flogging.MustGetLogger("client") type deliverClientIntf interface { getSpecifiedBlock(num uint64) (*common.Block, error) getOldestBlock() (*common.Block, error) getNewestBlock() (*common.Block, error) Close() error } type DeliverClient struct { client ab.AtomicBroadcast_DeliverClient chainID string tlsCertHash []byte } func NewDeliverClient(chainID string) (*DeliverClient, error) { config, err := initConfig() if err != nil { return nil, err } clientConfig := comm.ClientConfig{} clientConfig.Timeout = time.Second * 3 gClient, err := comm.NewGRPCClient(clientConfig) address := fmt.Sprintf("%s:%d", config.General.ListenAddress, config.General.ListenPort) conn, err := gClient.NewConnection(address, "") if err != nil { return nil, err } dc, err := ab.NewAtomicBroadcastClient(conn).Deliver(context.TODO()) if err != nil { return nil, errors.WithMessage(err, "failed to create deliver client") } return &DeliverClient{client: dc, chainID: chainID}, nil } func seekHelper( chainID string, position *ab.SeekPosition, tlsCertHash []byte, ) *common.Envelope { seekInfo := &ab.SeekInfo{ Start: position, Stop: position, Behavior: ab.SeekInfo_BLOCK_UNTIL_READY, } env, err := utils.CreateSignedEnvelopeWithTLSBinding( common.HeaderType_CONFIG_UPDATE, chainID, localmsp.NewSigner(), seekInfo, int32(0), uint64(0), tlsCertHash) if err != nil { logger.Errorf("Error signing envelope: %s", err) return nil } return env } func (r *DeliverClient) seekSpecified(blockNumber uint64) error { return r.client.Send(seekHelper(r.chainID, &ab.SeekPosition{ Type: &ab.SeekPosition_Specified{ Specified: &ab.SeekSpecified{ Number: blockNumber}}}, r.tlsCertHash)) } func (r *DeliverClient) seekOldest() error { return r.client.Send(seekHelper(r.chainID, &ab.SeekPosition{Type: &ab.SeekPosition_Oldest{ Oldest: &ab.SeekOldest{}}}, r.tlsCertHash)) } func (r *DeliverClient) seekNewest() error { return r.client.Send(seekHelper(r.chainID, &ab.SeekPosition{Type: &ab.SeekPosition_Newest{ Newest: &ab.SeekNewest{}}}, r.tlsCertHash)) } func (r *DeliverClient) readBlock() (*common.Block, error) { msg, err := r.client.Recv() if err != nil { return nil, fmt.Errorf("Error receiving: %s", err) } switch t := msg.Type.(type) { case *ab.DeliverResponse_Status: logger.Debugf("Got status: %v", t) return nil, fmt.Errorf("can't read the block: %v", t) case *ab.DeliverResponse_Block: logger.Debugf("Received block: %v", t.Block.Header.Number) r.client.Recv() // Flush the success message return t.Block, nil default: return nil, fmt.Errorf("response error: unknown type %T", t) } } func (r *DeliverClient) GetSpecifiedBlock(num uint64) (string, error) { err := r.seekSpecified(num) if err != nil { logger.Errorf("Received error: %s", err) return "", err } var b bytes.Buffer writer := bufio.NewWriter(&b) block, err := r.readBlock() if err != nil { return "", err } protolator.DeepMarshalJSON(writer, block) if err != nil { return "", err } return string(b.Bytes()), nil } func (r *DeliverClient) GetOldestBlock() (string, error) { err := r.seekOldest() if err != nil { logger.Errorf("Received error: %s", err) return "", err } var b bytes.Buffer writer := bufio.NewWriter(&b) block, err := r.readBlock() if err != nil { return "", err } protolator.DeepMarshalJSON(writer, block) if err != nil { return "", err } return string(b.Bytes()), nil } func (r *DeliverClient) GetNewestBlock() (string, error) { err := r.seekNewest() if err != nil { logger.Errorf("Received error: %s", err) return "", err } var b bytes.Buffer writer := bufio.NewWriter(&b) block, err := r.readBlock() if err != nil { return "", err } protolator.DeepMarshalJSON(writer, block) if err != nil { return "", err } return string(b.Bytes()), nil } func (r *DeliverClient) Close() error { return r.client.CloseSend() } func initConfig() (*ordererConfig.TopLevel, error) { config, err := ordererConfig.Load() if err != nil { return nil, err } // Load local MSP err = mspmgmt.LoadLocalMsp(config.General.LocalMSPDir, config.General.BCCSP, config.General.LocalMSPID) if err != nil { // Handle errors reading the config file return nil, err } return config, nil }
package dns import ( "github.com/stretchr/testify/assert" "net" "testing" ) func TestgetKnownDomain(t *testing.T) { knownDomain, _ := getKnownDomain([]string{"ec2-52-38-207-226.us-west-2.compute.amazonaws.com"}) assert.Equal(t, "Amazon AWS", knownDomain) knownDomain, _ = getKnownDomain([]string{"arn09s10-in-f4.1e100.net"}) assert.Equal(t, "1e100.net (Google Cloud)", knownDomain) } func TestDomainName(t *testing.T) { ip := net.ParseIP("172.217.22.174") domName, _ := DomainName(&ip) assert.Equal(t, "1e100.net (Google Cloud)", domName) }
// Package kalman defines a data structure that aggregates measurements. // Averages/counts measurements that are "close." // Can quickly apply the current K & L and return the associated N^2. package kalman const EPS = 0.1 // Correction factor since KF is nonlinear type Filter struct { n int // Number of dimensions x Matrix // Kalman Filter hidden state p Matrix // Kalman Filter hidden state covariance q Matrix // Kalman Filter state noise process r Matrix // Measurement noise u Matrix // Control vector, measured mag vector in this case z float64 // Measurement, earth's mag field strength **2 U chan Matrix // Channel for sending new control values to Kalman Filter Z chan float64 // Channel for sending new measurements to Kalman Filter } // NewKalmanFilter returns a Filter struct with Kalman Filter methods for calibrating a magnetometer. // n is the number of dimensions (1, 2 for testing; 3 for reality) // n0 is the strength of the Earth's magnetic field at the current location, 1.0 is fine for testing // sigmaK0 is the initial uncertainty for k (n0*sigmaK0 for l) // sigmaK is the (small) process uncertainty for k (n0*sigmaK for l) // sigmaM is the fractional magnetometer measurement noise, so the magnetometer noise is n0*sigmaM func NewKalmanFilter(n int, n0, sigmaK0, sigmaK, sigmaM float64) (k *Filter) { k = new(Filter) k.n = n k.x = make(Matrix, 2*n) k.p = make(Matrix, 2*n) k.q = make(Matrix, 2*n) for i := 0; i < n; i++ { k.x[2*i] = []float64{1} k.x[2*i+1] = []float64{0} k.p[2*i] = make([]float64, 2*n) k.p[2*i+1] = make([]float64, 2*n) k.p[2*i][2*i] = sigmaK0 * sigmaK0 k.p[2*i+1][2*i+1] = (n0 * sigmaK0) * (n0 * sigmaK0) k.q[2*i] = make([]float64, 2*n) k.q[2*i+1] = make([]float64, 2*n) k.q[2*i][2*i] = sigmaK * sigmaK k.q[2*i+1][2*i+1] = (n0 * sigmaK) * (n0 * sigmaK) } k.r = Matrix{{(n0 * sigmaM) * (n0 * sigmaM)}} k.U = make(chan Matrix) k.Z = make(chan float64) go k.runFilter() return k } func (k *Filter) runFilter() { var ( y float64 h, s, kk, nHat Matrix ) h = make(Matrix, 1) h[0] = make([]float64, 2*k.n) id := make(Matrix, 2*k.n) for i := 0; i < 2*k.n; i++ { id[i] = make([]float64, 2*k.n) id[i][i] = 1 } for { select { case k.u = <-k.U: // Calculate estimated measurement nHat = calcMagField(k.x, k.u) // No evolution for x // Evolve p for i := 0; i < 2*k.n; i++ { for j := 0; j < 2*k.n; j++ { k.p[i][j] += k.q[i][j] } } case k.z = <-k.Z: // Calculate measurement residual y = k.z for i := 0; i < k.n; i++ { y -= nHat[i][0] * nHat[i][0] } // Calculate Jacobian for i := 0; i < k.n; i++ { h[0][2*i] = 2 * nHat[i][0] * nHat[i][0] / k.x[2*i][0] h[0][2*i+1] = -2 * nHat[i][0] * k.x[2*i][0] } // Calculate S s = matAdd(k.r, matMul(h, matMul(k.p, matTranspose(h)))) // Kalman Gain kk = matSMul(EPS/s[0][0], matMul(k.p, matTranspose(h))) // State correction k.x = matAdd(k.x, matSMul(y, kk)) // State covariance correction k.p = matMul(matAdd(id, matSMul(-1, matMul(kk, h))), k.p) } } } func calcMagField(x Matrix, u Matrix) (n Matrix) { n = make(Matrix, len(u[0])) for i := 0; i < len(u[0]); i++ { n[i] = []float64{x[2*i][0] * (u[0][i] - x[2*i+1][0])} } return n } func (k *Filter) State() (state Matrix) { return k.x } func (k *Filter) StateCovariance() (cov Matrix) { return k.p } func (k *Filter) ProcessNoise() (cov Matrix) { return k.q } func (k *Filter) SetProcessNoise(q Matrix) { k.q = q } func (k *Filter) K() (kk []float64) { v := make([]float64, k.n) for i := 0; i < k.n; i++ { v[i] = k.x[2*i][0] } return v } func (k *Filter) L() (l []float64) { v := make([]float64, k.n) for i := 0; i < k.n; i++ { v[i] = k.x[2*i+1][0] } return v } func (k *Filter) P() (p Matrix) { return k.p }
package library import ( "encoding/json" "errors" "net/http" "strings" "github.com/go-kit/kit/log" "github.com/go-kit/kit/tracing/opentracing" httptransport "github.com/go-kit/kit/transport/http" "github.com/go-zoo/bone" stdopentracing "github.com/opentracing/opentracing-go" "github.com/solher/kit-crud/client" "github.com/solher/kit-crud/pb" "github.com/solher/kit-gateway/common" "golang.org/x/net/context" ) type Handlers struct { CreateDocumentHandler http.Handler FindDocumentsHandler http.Handler FindDocumentsByIDHandler http.Handler ReplaceDocumentByIDHandler http.Handler DeleteDocumentsByIDHandler http.Handler } func MakeHTTPHandlers(ctx context.Context, e client.Endpoints, tracer stdopentracing.Tracer, logger log.Logger) Handlers { opts := []httptransport.ServerOption{ httptransport.ServerErrorEncoder(common.ServerErrorEncoder), } createDocumentHandler := httptransport.NewServer( ctx, e.CreateDocumentEndpoint, decodeHTTPCreateDocumentRequest, encodeHTTPCreateDocumentResponse, append( opts, httptransport.ServerBefore( opentracing.FromHTTPRequest(tracer, "CreateDocument", logger), common.AddHTTPAnnotations, ), )..., ) findDocumentsHandler := httptransport.NewServer( ctx, e.FindDocumentsEndpoint, decodeHTTPFindDocumentsRequest, encodeHTTPFindDocumentsResponse, append( opts, httptransport.ServerBefore( opentracing.FromHTTPRequest(tracer, "FindDocuments", logger), common.AddHTTPAnnotations, ), )..., ) findDocumentsByIDHandler := httptransport.NewServer( ctx, e.FindDocumentsByIDEndpoint, decodeHTTPFindDocumentsByIDRequest, encodeHTTPFindDocumentsByIDResponse, append( opts, httptransport.ServerBefore( opentracing.FromHTTPRequest(tracer, "FindDocumentsByID", logger), common.AddHTTPAnnotations, ), )..., ) replaceDocumentByIDHandler := httptransport.NewServer( ctx, e.ReplaceDocumentByIDEndpoint, decodeHTTPReplaceDocumentByIDRequest, encodeHTTPReplaceDocumentByIDResponse, append( opts, httptransport.ServerBefore( opentracing.FromHTTPRequest(tracer, "ReplaceDocumentByID", logger), common.AddHTTPAnnotations, ), )..., ) deleteDocumentsByIDHandler := httptransport.NewServer( ctx, e.DeleteDocumentsByIDEndpoint, decodeHTTPDeleteDocumentsByIDRequest, encodeHTTPDeleteDocumentsByIDResponse, append( opts, httptransport.ServerBefore( opentracing.FromHTTPRequest(tracer, "DeleteDocumentsByID", logger), common.AddHTTPAnnotations, ), )..., ) return Handlers{ CreateDocumentHandler: createDocumentHandler, FindDocumentsHandler: findDocumentsHandler, FindDocumentsByIDHandler: findDocumentsByIDHandler, ReplaceDocumentByIDHandler: replaceDocumentByIDHandler, DeleteDocumentsByIDHandler: deleteDocumentsByIDHandler, } } func decodeHTTPCreateDocumentRequest(_ context.Context, r *http.Request) (interface{}, error) { var document *pb.Document if err := json.NewDecoder(r.Body).Decode(document); err != nil { return nil, err } req := pb.CreateDocumentRequest{ UserId: "admin", Document: document, } return req, nil } func encodeHTTPCreateDocumentResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(*pb.CreateDocumentReply) if len(res.Err) > 0 { return common.EncodeHTTPError(ctx, w, errors.New(res.Err)) } return common.EncodeHTTPResponse(ctx, w, http.StatusCreated, documentEncoder, res.Document) } func decodeHTTPFindDocumentsRequest(_ context.Context, r *http.Request) (interface{}, error) { req := &pb.FindDocumentsRequest{ UserId: "admin", } return req, nil } func encodeHTTPFindDocumentsResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(*pb.FindDocumentsReply) if len(res.Err) > 0 { return common.EncodeHTTPError(ctx, w, errors.New(res.Err)) } return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentsEncoder, res.Documents) } func decodeHTTPFindDocumentsByIDRequest(_ context.Context, r *http.Request) (interface{}, error) { val := bone.GetValue(r, ":ids") ids := strings.Split(val, ",") req := &pb.FindDocumentsByIdRequest{ UserId: "admin", Ids: ids, } return req, nil } func encodeHTTPFindDocumentsByIDResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(*pb.FindDocumentsByIdReply) if len(res.Err) > 0 { return common.EncodeHTTPError(ctx, w, errors.New(res.Err)) } if len(res.Documents) == 1 { return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentEncoder, res.Documents[0]) } return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentsEncoder, res.Documents) } func decodeHTTPReplaceDocumentByIDRequest(_ context.Context, r *http.Request) (interface{}, error) { var document *pb.Document if err := json.NewDecoder(r.Body).Decode(document); err != nil { return nil, err } req := &pb.ReplaceDocumentByIdRequest{ UserId: "admin", Id: bone.GetValue(r, ":id"), Document: document, } return req, nil } func encodeHTTPReplaceDocumentByIDResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(*pb.ReplaceDocumentByIdReply) if len(res.Err) > 0 { return common.EncodeHTTPError(ctx, w, errors.New(res.Err)) } return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentEncoder, res.Document) } func decodeHTTPDeleteDocumentsByIDRequest(_ context.Context, r *http.Request) (interface{}, error) { val := bone.GetValue(r, ":ids") ids := strings.Split(val, ",") req := &pb.DeleteDocumentsByIdRequest{ UserId: "admin", Ids: ids, } return req, nil } func encodeHTTPDeleteDocumentsByIDResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { res := response.(*pb.DeleteDocumentsByIdReply) if len(res.Err) > 0 { return common.EncodeHTTPError(ctx, w, errors.New(res.Err)) } if len(res.Documents) == 1 { return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentEncoder, res.Documents[0]) } return common.EncodeHTTPResponse(ctx, w, http.StatusOK, documentsEncoder, res.Documents) } func documentEncoder(w http.ResponseWriter, response interface{}) error { document := response.(*pb.Document) return documentsEncoder(w, []*pb.Document{document}) } func documentsEncoder(w http.ResponseWriter, response interface{}) error { documents := response.([]*pb.Document) output := make([]struct { ID *string `json:"id"` UserID *string `json:"userId"` Content *string `json:"content"` }, len(documents)) for i := range documents { output[i].ID = &documents[i].Id output[i].UserID = &documents[i].UserId output[i].Content = &documents[i].Content } return json.NewEncoder(w).Encode(output) }
package Problem0591 func isValid(code string) bool { res := true return res }
package kata import "strings" func bandNameGenerator(word string) string { switch { case word[0] == word[len(word)-1]: { return (strings.ToUpper(string(word[0])) + string(word[1:len(word)]) + string(word[1:len(word)])) } case strings.Contains(word, "-"): { h := strings.Index(word, "-") i := h + 1 j := h + 2 return "The " + (strings.ToUpper(string(word[0]))) + string(word[1:i]) + (strings.ToUpper(string(word[i])) + string(word[j:len(word)])) } default: { return "The " + strings.ToUpper(string(word[0])) + string(word[1:len(word)]) } } }
package main import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "log" "os" ) func main() { privateKey, err := rsa.GenerateKey(rand.Reader, 128) if err != nil { log.Println(err) return } privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey) privateKeyBlock := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privateKeyDer, } privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock)) publicKey := privateKey.PublicKey publicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKey) if err != nil { log.Fatal(err) return } publicKeyBlock := pem.Block{ Type: "PUBLIC KEY", Headers: nil, Bytes: publicKeyDer, } publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock)) fmt.Println(privateKeyPem) fmt.Println(publicKeyPem) f, err := os.OpenFile("rsa.yml", os.O_RDWR|os.O_CREATE, 0755) if err != nil { log.Fatal(err) } f.WriteString("release:\n") f.WriteString(" portal_private_key: |\n") for _, v := range bytes.Split(pem.EncodeToMemory(&privateKeyBlock), []byte("\n")) { f.WriteString(" ") if _, err := f.Write(v); err != nil { log.Fatal(err) } else { f.WriteString("\n") } } if err := f.Close(); err != nil { log.Fatal(err) } }
package main import ( "fmt" "sync" ) func main() { in := gen() a := factorial(in) b := factorial(in) c := factorial(in) d := factorial(in) e := factorial(in) f := factorial(in) g := factorial(in) h := factorial(in) i := factorial(in) j := factorial(in) for n := range merge(a, b, c, d, e, f, g, h, i, j) { fmt.Println(n) } } func gen() <-chan int { out := make(chan int) go func() { for i := 0; i < 100000; i++ { for j := 3; j < 13; j++ { out <- j } } close(out) }() return out } func factorial(in <-chan int) <-chan int { out := make(chan int) go func() { for n := range in { out <- fact(n) } close(out) }() return out } func fact(n int) int { total := 1 for i := n; i > 0; i-- { total *= i } return total } func merge(cs ...<-chan int) <-chan int { out := make(chan int) var wg sync.WaitGroup wg.Add(len(cs)) for _, v := range cs { go func(c <-chan int) { for n := range c { out <- n } wg.Done() }(v) } go func() { wg.Wait() close(out) }() return out } /* CHALLENGE #1 -- Use the code above to execute 1,000 factorial computations and in parallel. -- Use the "fan out / fan in" pattern to accomplish this CHALLENGE #2 -- While running the factorial computations, try to find how much of your resources are benig used. -- Post the percentage of your ressources being used to this discussion: https://goo.gl/BxKnOL */
package main import "fmt" func main() { fmt.Println(arithmeticTriplets( []int{ 0, 1, 4, 6, 7, 10, }, 3)) } func arithmeticTriplets(nums []int, diff int) int { ans := 0 for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { for k := j + 1; k < len(nums); k++ { if nums[j]-nums[i] == diff && nums[k]-nums[j] == diff { ans++ } } } } return ans }
func maxProfit(prices []int) int { res:=0 min:=math.MaxInt16 for _,v:=range prices{ if v<min{ min=v } if v-min>res{ res=v-min } } return res }
package main import ( "context" "fmt" "time" "github.com/GlitchyGlitch/typinger/config" "github.com/GlitchyGlitch/typinger/test" "github.com/shurcooL/graphql" "golang.org/x/oauth2" ) const tdPath = "postgres/fixtures" type user struct { Typename graphql.String `graphql:"__typename"` ID graphql.String Name graphql.String Email graphql.String } type article struct { Typename graphql.String `graphql:"__typename"` ID graphql.String Title graphql.String Content graphql.String ThumbnailURL graphql.String } type image struct { Typename graphql.String `graphql:"__typename"` ID graphql.String Name graphql.String Slug graphql.String URL graphql.String MIME graphql.String } var articlesDataSet = []article{ { Typename: "Article", ID: "82ba242e-e853-499f-8873-f271c53aca6a", Title: "First article", Content: "First content.", ThumbnailURL: "http://www.example.com/path/to/photo1", }, { Typename: "Article", ID: "c3eec2ac-0fd5-41ce-829a-6f3dd74cd102", Title: "Second article", Content: "Second content.", ThumbnailURL: "http://www.example.com/path/to/photo2", }, { Typename: "Article", ID: "d50f5d60-6f59-4605-96b8-a96b9e9b17ea", Title: "Third article", Content: "Third content.", ThumbnailURL: "http://www.example.com/path/to/photo3", }, } var userDataSet = []user{ { Typename: "User", ID: "e5f1c9af-fa8a-4a58-9909-d887ddf7e961", Name: "First User", Email: "first@example.com", }, { Typename: "User", ID: "d1451907-e1ec-4291-ab14-a9a314b56b6a", Name: "Second User", Email: "second@example.com", }, { Typename: "User", ID: "0e38a4bd-87a0-447f-93fd-b904c9f7f303", Name: "Third User", Email: "third@example.com", }, } var imageDataSet = []image{ { Typename: "Image", ID: "0cf191b8-b60c-4aec-b698-ca2b64a3d0f7", Name: "First image", Slug: "first-slug", URL: "http://0.0.0.0/img/first-slug", MIME: "image/svg+xml", }, { Typename: "Image", ID: "60b390de-cd44-4cc2-9fbb-fd9bcaa42819", Name: "Second image", Slug: "second-slug", URL: "http://0.0.0.0/img/second-slug", MIME: "image/webp", }, { Typename: "Image", ID: "72e641f1-09ac-4444-b980-98be375f8efd", Name: "Third image", Slug: "third-slug", URL: "http://0.0.0.0/img/third-slug", MIME: "image/webp", }, } var forbiddenErr = "Operation forbidden." var notFoundErr = "No data found." var existsErr = "Resource already exists." func setup(auth bool, conf *config.Config) *graphql.Client { test.RenewTestData(conf.DBURL, tdPath) go startServer(conf, 2) time.Sleep(100 * time.Millisecond) // Wait for server startup url := fmt.Sprintf("http://%s/graphql", conf.Addr()) if !auth { return graphql.NewClient(url, nil) } loginClient := graphql.NewClient(url, nil) var loginMut struct { Login graphql.String `graphql:"login(input: {email: \"first@example.com\", password:\"first\"})"` } err := loginClient.Mutate(context.Background(), &loginMut, nil) if err != nil { panic(err) } src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: string(loginMut.Login)}, ) httpClient := oauth2.NewClient(context.Background(), src) // Setup authenticated client return graphql.NewClient(url, httpClient) } func teardown(conf *config.Config) { test.MigrateTestData("down", conf.DBURL, tdPath) }
package main import ( "flag" "net/http" "encoding/json" "log" "time" "os" "strconv" "io" "io/ioutil" "github.com/cloudfoundry-community/go-cfclient" ) var done chan bool var target chan []TargetGroup var ( ApiAddress = flag.String( "api.address", "", "Cloud Foundry API Address ($API_ADDRESS).", ) ClientID = flag.String( "api.id", "", "Cloud Foundry UAA ClientID ($CF_CLIENT_ID).", ) ClientSecret = flag.String( "api.secret", "", "Cloud Foundry UAA ClientSecret ($CF_CLIENT_SECRET).", ) SkipSSL = flag.Bool( "skip.ssl", false, "Disalbe SSL validation ($SKIP_SSL).", ) Frequency = flag.Uint( "update.frequency", 3, "SD Update frequency in minutes ($FREQUENCY).", ) OutputFile = flag.String( "out.file", "/tmp/cf_targets.json", "Location to write target json ($OUTPUT_FILE).", ) ) // TargetGroup is the target group read by Prometheus. type TargetGroup struct { Targets []string `json:"targets,omitempty"` Labels map[string]string `json:"labels,omitempty"` } type SpaceInfo struct { Name string `json:"name"` OrgName string `json:"orgname"` } func overrideFlagsWithEnvVars() { overrideWithEnvVar("API_ADDRESS", ApiAddress) overrideWithEnvVar("CF_CLIENT_ID", ClientID) overrideWithEnvVar("CF_CLIENT_SECRET", ClientSecret) overrideWithEnvBool("SKIP_SSL", SkipSSL) overrideWithEnvUint("FREQUENCY", Frequency) overrideWithEnvVar("OUTPUT_FILE", OutputFile) } func overrideWithEnvVar(name string, value *string) { envValue := os.Getenv(name) if envValue != "" { *value = envValue } } func overrideWithEnvUint(name string, value *uint) { envValue := os.Getenv(name) if envValue != "" { intValue, err := strconv.Atoi(envValue) if err != nil { log.Fatalln("Invalid `%s`: %s", name, err) } *value = uint(intValue) } } func overrideWithEnvBool(name string, value *bool) { envValue := os.Getenv(name) if envValue != "" { var err error *value, err = strconv.ParseBool(envValue) if err != nil { log.Fatalf("Invalid `%s`: %s", name, err) } } } func updateTargetList (client *cfclient.Client, apiaddress string) { //Create one right away go createTargetList(client, apiaddress) //Start the timer, default 3 min to update. If previous runs still going then don't launch another tick := time.Tick(time.Duration(*Frequency) * time.Minute) for { select { case <-tick: select { case <- done: go createTargetList(client, apiaddress) default: log.Printf("Previous run not finished. Skipping....") } } } } func createTargetList(client *cfclient.Client, apiaddress string) { var applistchunks [][]cfclient.App var tgroups []TargetGroup // create a couple maps for org/space lookup rather than using inline-depth on the api calls. This speeds things up significantly log.Println("Generating target list") apps,err := client.ListAppsByQuery(nil) if err != nil { log.Printf("Error generating list of apps from CF: %v", err) } orgs,err := client.ListOrgs() if err != nil { log.Printf("Error generating list of orgs from CF: %v", err) } // create map of org guid to org name orgmap := map[string]string{} for _, org := range orgs { orgmap[org.Guid] = org.Name } spaces,err := client.ListSpaces() if err != nil { log.Printf("Error generating list of spaces from CF: %v", err) } // create a map of space guid to space name and org name spacemap := map[string]SpaceInfo{} for _, space := range spaces { spacemap[space.Guid] = SpaceInfo { Name:space.Name , OrgName: orgmap[space.OrganizationGuid] } } // removed apps which aren't started from the list....this way we know the number of goroutines to wait for startedapps := apps[:0] for _, n := range apps { if n.State == "STARTED" { startedapps = append(startedapps, n) } } // split the app list into chunks to parallelize the appstats calls. Use max of 10 goroutines chunkSize := 1000 if len(startedapps) < 1000 { chunkSize = 100 } else { chunkSize = len(startedapps) / 9 } for i := 0; i < len(startedapps); i += chunkSize { end := i + chunkSize if end > len(startedapps) { end = len(startedapps) } applistchunks = append(applistchunks, startedapps[i:end]) } log.Printf("Found %v started apps, using chunksize of %v and %v goroutines", len(startedapps), chunkSize, len(applistchunks)) // launch a thread for each chunk of X apps to create target lists in parallel and put them on the channel for _, chunk := range applistchunks { go func (client *cfclient.Client, chunk []cfclient.App, apiaddress string, spacemap map[string]SpaceInfo) { var tgroups []TargetGroup var targets []string for _, app := range chunk { stats,err := client.GetAppStats(app.Guid) if err != nil { log.Printf("Error generating stats for app %v. %v", app.Name, err) } for _, stat := range stats { route := stat.Stats.Host + ":" + strconv.Itoa(stat.Stats.Port) targets = append(targets, route) } tgroups = append(tgroups, TargetGroup { Targets: targets, Labels: map[string]string{"job": app.Name, "cf": apiaddress, "space": spacemap[app.SpaceGuid].Name, "org": spacemap[app.SpaceGuid].OrgName}, }) targets = nil } target <- []TargetGroup(tgroups) }(client, chunk, apiaddress, spacemap) } //take the individual chunked appstats off the channel and combine, waiting for all chunks to complete for i := 0; i < len(applistchunks); i++ { select { case apptarget := <-target: tgroups = append(tgroups,apptarget...) } } targetlist, err := json.MarshalIndent(tgroups, "", " ") if err != nil { log.Fatal(err) } log.Printf("Done generating target list") err = ioutil.WriteFile(*OutputFile, targetlist, 0644) if err != nil { log.Printf("File cant be written: %v", err) os.Exit(1) } done <- true } func main() { flag.Parse() overrideFlagsWithEnvVars() var port string c := &cfclient.Config{ ApiAddress: *ApiAddress, ClientID: *ClientID, ClientSecret: *ClientSecret, SkipSslValidation: *SkipSSL, } client, err := cfclient.NewClient(c) if err != nil { log.Fatal("Error connecting to API: %s", err.Error()) os.Exit(1) } done = make(chan bool) target = make(chan []TargetGroup) go updateTargetList(client, *ApiAddress) if port = os.Getenv("PORT"); len(port) == 0 { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Cloud Foundry Target Generator for Prometehus Service Discovery") }) log.Fatal(http.ListenAndServe(":" + port, nil)) }
package services_test import ( "errors" "github.com/cloudfoundry-incubator/notifications/fakes" "github.com/cloudfoundry-incubator/notifications/models" "github.com/cloudfoundry-incubator/notifications/web/services" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Updater", func() { Describe("#Update", func() { var fakeTemplatesRepo *fakes.FakeTemplatesRepo var template models.Template var updater services.TemplateUpdater BeforeEach(func() { fakeTemplatesRepo = fakes.NewFakeTemplatesRepo() template = models.Template{ Name: "gobble." + models.UserBodyTemplateName, Text: "gobble", HTML: "<p>gobble</p>", Overridden: true, } updater = services.NewTemplateUpdater(fakeTemplatesRepo, fakes.NewDatabase()) }) It("Inserts templates into the templates repo", func() { Expect(fakeTemplatesRepo.Templates).ToNot(ContainElement(template)) err := updater.Update(template) Expect(err).ToNot(HaveOccurred()) Expect(fakeTemplatesRepo.Templates).To(ContainElement(template)) }) It("propagates errors from repo", func() { expectedErr := errors.New("Boom!") fakeTemplatesRepo.UpsertError = expectedErr err := updater.Update(template) Expect(err).To(Equal(expectedErr)) }) }) })
package types import "math/big" const ( AergoSystem = "aergo.system" AergoName = "aergo.name" AergoEnterprise = "aergo.enterprise" MaxCandidates = 30 votePrefixLen = 2 VoteBP = "v1voteBP" VoteGasPrice = "v1voteGasPrice" VoteNumBP = "v1voteNumBP" VoteNamePrice = "v1voteNamePrice" VoteMinStaking = "v1voteMinStaking" ) //var AllVotes = [...]string{VoteBP, VoteGasPrice, VoteNumBP, VoteNamePrice, VoteMinStaking} var AllVotes = [...]string{VoteBP} func (vl VoteList) Len() int { return len(vl.Votes) } func (vl VoteList) Less(i, j int) bool { result := new(big.Int).SetBytes(vl.Votes[i].Amount).Cmp(new(big.Int).SetBytes(vl.Votes[j].Amount)) if result == -1 { return true } else if result == 0 { if len(vl.Votes[i].Candidate) == 39 /*peer id length*/ { return new(big.Int).SetBytes(vl.Votes[i].Candidate[7:]).Cmp(new(big.Int).SetBytes(vl.Votes[j].Candidate[7:])) > 0 } return new(big.Int).SetBytes(vl.Votes[i].Candidate).Cmp(new(big.Int).SetBytes(vl.Votes[j].Candidate)) > 0 } return false } func (vl VoteList) Swap(i, j int) { vl.Votes[i], vl.Votes[j] = vl.Votes[j], vl.Votes[i] } func (v Vote) GetAmountBigInt() *big.Int { return new(big.Int).SetBytes(v.Amount) }
package skapt_test import ( "bytes" "errors" "io" "github.com/hoenirvili/skapt" "github.com/hoenirvili/skapt/argument" "github.com/hoenirvili/skapt/flag" gc "gopkg.in/check.v1" ) type appSuite struct{} var _ = gc.Suite(&appSuite{}) func handler(ctx *skapt.Context) error { return nil } func (a appSuite) defaultApplication(stdout, stderr io.Writer) *skapt.Application { return &skapt.Application{ Name: "test", Description: "test description", Handler: func(ctx *skapt.Context) error { return nil }, Stdout: stdout, Stderr: stderr, } } func (a appSuite) TestExecValidateWithErrors(c *gc.C) { stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} apps := []skapt.Application{ {}, {Name: "test"}, { Name: "test", Handler: handler, Stdout: stdout, Stderr: stderr, }, { Name: "test", Handler: handler, Flags: flag.Flags{{}}, }, } for _, app := range apps { err := app.Exec(nil) c.Assert(err, gc.NotNil) } so, se := stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert(se, gc.DeepEquals, "No arguments to execute") } func (a appSuite) TestExec(c *gc.C) { args := []string{"./test"} stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} app := skapt.Application{ Name: "test", Handler: func(ctx *skapt.Context) error { s, l := ctx.Bool("u"), ctx.Bool("url") c.Assert(s, gc.Equals, false) c.Assert(l, gc.Equals, false) c.Assert(ctx.Args, gc.DeepEquals, args) return nil }, Flags: flag.Flags{ {Short: "u", Long: "url", Type: argument.Bool}, }, Stdout: stdout, Stderr: stderr, } err := app.Exec(args) c.Assert(err, gc.IsNil) so, se := stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert(se, gc.DeepEquals, "") app.Stdout, app.Stderr = nil, nil err = app.Exec(args) c.Assert(err, gc.IsNil) } func (a appSuite) TestExecHandler(c *gc.C) { args := []string{ "./downloader", "-u", "https://someexternalink.com", "--times=3", "--debug", "--hint=10", "merge-link", "another-arg", } stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} app := skapt.Application{ Name: "test", Flags: flag.Flags{ {Short: "u", Type: argument.String}, {Long: "times", Type: argument.Int}, {Long: "debug", Type: argument.Bool}, {Long: "hint", Type: argument.Int}, }, NArgs: 2, Handler: func(ctx *skapt.Context) error { u := ctx.String("u") t := ctx.Int("times") d := ctx.Bool("debug") h := ctx.Int("hint") c.Assert(u, gc.DeepEquals, "https://someexternalink.com") c.Assert(t, gc.DeepEquals, 3) c.Assert(d, gc.Equals, true) c.Assert(h, gc.DeepEquals, 10) c.Assert(ctx.Args, gc.DeepEquals, []string{"./downloader", "merge-link", "another-arg"}) return nil }, Stdout: stdout, Stderr: stderr, } err := app.Exec(args) c.Assert(err, gc.IsNil) so, se := stdout.String(), stdout.String() c.Assert(so, gc.Equals, "") c.Assert(se, gc.Equals, "") } func (a appSuite) TestExecWithErrors(c *gc.C) { args := []string{"./test"} stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} app := skapt.Application{ Name: "test", Handler: func(ctx *skapt.Context) error { s, l := ctx.Bool("u"), ctx.Bool("url") c.Assert(s, gc.Equals, false) c.Assert(l, gc.Equals, false) c.Assert(ctx.Args, gc.DeepEquals, args) return nil }, NArgs: 2, Flags: flag.Flags{ {Short: "u", Long: "url", Type: argument.Bool}, }, Stdout: stdout, Stderr: stderr, } err := app.Exec(args) c.Assert(err, gc.NotNil) so, se := stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert(se, gc.DeepEquals, "Expecting at least 2 additional arguments") stdout.Reset() stderr.Reset() app.Flags[0].Type = argument.Int app.Handler = func(ctx *skapt.Context) error { s, l := ctx.Int("u"), ctx.Int("url") c.Assert(s, gc.Equals, 0) c.Assert(l, gc.Equals, 0) c.Assert(ctx.Args, gc.DeepEquals, []string{"./test"}) return nil } err = app.Exec([]string{"./test", "-u", "huifsdh1"}) c.Assert(err, gc.NotNil) so, se = stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert((len(se) > 0), gc.Equals, true) } var ( expectedHelp = ` Usage: test [OPTIONS] [ARG...] test [ --help | -h | -v | --version ] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur in dolor lobortis, non ultrices nibh condimentum. Fusce suscipit ultrices. Sed a malesuada urna. Lorem ipsum dolor sit consectetur adipiscing elit. Vivamus laoreet tellus vel sem euismod, accumsan odio pulvinar. Donec eget ante venenatis, gravida eros sagittis elit. Nam nec arcu augue. Sed mattis lobortis at malesuada leo bibendum at. Pellentesque et condimentum erat. feugiat id ex non iaculis. Donec efficitur ac lectus hendrerit. Sed feugiat augue nec nibh rutrum, in ornare viverra. Options: -l --long-description Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur in dolor lobortis, non ultrices nibh condimentum. Fusce suscipit ultrices. Sed a malesuada urna. Lorem ipsum dolor sit consectetur adipiscing elit. Vivamus laoreet tellus vel sem euismod, accumsan odio pulvinar. Donec eget ante venenatis, gravida eros sagittis elit. Nam nec arcu augue. Sed mattis lobortis at malesuada leo bibendum at. Pellentesque et condimentum erat. feugiat id ex non iaculis. Donec efficitur ac lectus hendrerit. Sed feugiat augue nec nibh rutrum, in ornare viverra. -h --help Print out the help menu -v --version Print out the version of the program `[1:] expectedVersion = ` Version 1.0.0 `[1:] ) const description = ` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur in dolor lobortis, non ultrices nibh condimentum. Fusce suscipit ultrices. Sed a malesuada urna. Lorem ipsum dolor sit consectetur adipiscing elit. Vivamus laoreet tellus vel sem euismod, accumsan odio pulvinar. Donec eget ante venenatis, gravida eros sagittis elit. Nam nec arcu augue. Sed mattis lobortis at malesuada leo bibendum at. Pellentesque et condimentum erat. feugiat id ex non iaculis. Donec efficitur ac lectus hendrerit. Sed feugiat augue nec nibh rutrum, in ornare viverra. ` func (a appSuite) TestExecRender(c *gc.C) { stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} app := skapt.Application{ Name: "test", Description: description, Handler: func(ctx *skapt.Context) error { return nil }, Flags: flag.Flags{ { Short: "l", Long: "long-description", Description: description, }, }, Stdout: stdout, Stderr: stderr, } args := []string{"./test", "--help"} err := app.Exec(args) c.Assert(err, gc.IsNil) se := stderr.String() so := stdout.String() c.Assert(so, gc.DeepEquals, expectedHelp) c.Assert(se, gc.DeepEquals, "") stdout.Reset() stderr.Reset() args = []string{"./test", "--version"} app.Version = "1.0.0" err = app.Exec(args) c.Assert(err, gc.IsNil) so = stdout.String() se = stderr.String() c.Assert(so, gc.DeepEquals, expectedVersion) c.Assert(se, gc.DeepEquals, "") } type deferErr struct{} func (d deferErr) Write([]byte) (int, error) { return 0, deferr } var deferr = errors.New("err") func (a appSuite) TestExecDeferError(c *gc.C) { app := skapt.Application{ Name: "test", Description: "test description", Handler: func(ctx *skapt.Context) error { return nil }, Stderr: &deferErr{}, } err := app.Exec(nil) c.Assert(err, gc.DeepEquals, deferr) } func (a appSuite) TestExecRequired(c *gc.C) { stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} app := a.defaultApplication(stdout, stderr) app.Flags = flag.Flags{ {Short: "e", Long: "expl", Required: true}, } err := app.Exec([]string{"./test"}) c.Assert(err, gc.NotNil) so, se := stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert(se, gc.DeepEquals, "Option -e --expl is required") stdout.Reset() stderr.Reset() err = app.Exec([]string{"./test", "-e"}) c.Assert(err, gc.IsNil) so, se = stdout.String(), stderr.String() c.Assert(so, gc.DeepEquals, "") c.Assert(se, gc.DeepEquals, "") }
package main import ( "log" "os" "github.com/abdullah2993/goias3/ias3" ) var ( accessKey = os.Getenv("IAS3_ACCESS_KEY") secretKey = os.Getenv("IAS3_SECRET_KEY") ) func init() { log.SetFlags(log.LstdFlags | log.Lshortfile) } func main() { if accessKey == "" || secretKey == "" { log.Fatalf("unable to find the access/secret key") } f, err := os.Open("./uploads/file.mp4") if err != nil { log.Fatalf("unable to read file") } err = ias3.NewReq(). AutoCreateBucket(). WithMeta("title", "Test Upload"). WithCreds(accessKey, secretKey). UploadFile("test_loaylty_exe_1/file.mp4", f) if err != nil { log.Fatalf("upload filed: %v", err) } }
package grapheme import ( "bufio" "bytes" "strconv" "strings" "testing" "unicode" "github.com/gioui/uax/internal/testdata" "github.com/gioui/uax/internal/tracing" "github.com/gioui/uax/segment" ) func TestGraphemeClasses(t *testing.T) { tracing.SetTestingLog(t) c1 := LClass if c1.String() != "LClass" { t.Errorf("String(LClass) should be 'LClass', is %s", c1) } if !unicode.Is(Control, '\t') { t.Error("<TAB> should be identified as control character") } hangsyl := '\uac1c' if c := ClassForRune(hangsyl); c != LVClass { t.Errorf("Hang syllable GAE should be of class LV, is %s", c) } if c := ClassForRune(0); c != eot { t.Errorf("\\0x00 should be of class eot, is %s", c) } } func TestGraphemes1(t *testing.T) { tracing.SetTestingLog(t) onGraphemes := NewBreaker(1) input := bytes.NewReader([]byte("개=Hang Syllable GAE")) seg := segment.NewSegmenter(onGraphemes) seg.Init(input) seg.Next() t.Logf("Next() = %s\n", seg.Text()) if seg.Err() != nil { t.Errorf("segmenter.Next() failed with error: %s", seg.Err()) } if seg.Text() != "개" { t.Errorf("expected first grapheme of string to be '개' (Hang GAE), is '%v'", seg.Text()) } } func TestGraphemes2(t *testing.T) { tracing.SetTestingLog(t) onGraphemes := NewBreaker(1) input := bytes.NewReader([]byte("Hello\tWorld!")) seg := segment.NewSegmenter(onGraphemes) seg.BreakOnZero(true, false) seg.Init(input) output := "" for seg.Next() { t.Logf("Next() = %s\n", seg.Text()) output += "_" + seg.Text() } if seg.Err() != nil { t.Errorf("segmenter.Next() failed with error: %s", seg.Err()) } if output != "_H_e_l_l_o_\t_W_o_r_l_d_!" { t.Errorf("expected grapheme for every char pos, have %s", output) } } func TestGraphemesTestFile(t *testing.T) { tracing.SetTestingLog(t) file, err := testdata.UCDReader("auxiliary/GraphemeBreakTest.txt") if err != nil { t.Fatal(err) } onGraphemes := NewBreaker(5) seg := segment.NewSegmenter(onGraphemes) //seg.BreakOnZero(true, false) //failcnt, i, from, to := 0, 0, 1, 1000 failcnt, i, from, to := 0, 0, 1, 1000 scan := bufio.NewScanner(file) for scan.Scan() { line := scan.Text() line = strings.TrimSpace(line) if line[0] == '#' { // ignore comment lines continue } i++ if i >= from { parts := strings.Split(line, "#") testInput, comment := parts[0], parts[1] //TC().Infof("#######################################################") tracing.Infof(comment) in, out := breakTestInput(testInput) success := executeSingleTest(t, seg, i, in, out) _, shouldFail := knownFailure[testInput] shouldSucceed := !shouldFail if success != shouldSucceed { failcnt++ if shouldFail { t.Logf("expected %q to fail, but succeeded", testInput) } } } if i >= to { break } } if err := scan.Err(); err != nil { tracing.Infof("reading input: %v", err) } if failcnt > 0 { t.Errorf("%d TEST CASES OUT of %d FAILED", failcnt, i-from+1) } t.Logf("%d TEST CASES IGNORED", len(knownFailure)) } var knownFailure = map[string]struct{}{ "÷ 0600 × 0020 ÷\t": {}, "÷ 0600 × 1F1E6 ÷\t": {}, "÷ 0600 × 0600 ÷\t": {}, "÷ 0600 × 1100 ÷\t": {}, "÷ 0600 × 1160 ÷\t": {}, "÷ 0600 × 11A8 ÷\t": {}, "÷ 0600 × AC00 ÷\t": {}, "÷ 0600 × AC01 ÷\t": {}, "÷ 0600 × 231A ÷\t": {}, "÷ 0600 × 0378 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 0020 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 000D ÷\t": {}, "÷ D800 ÷ 0308 ÷ 000A ÷\t": {}, "÷ D800 ÷ 0308 ÷ 0001 ÷\t": {}, "÷ D800 ÷ 034F ÷\t": {}, "÷ D800 ÷ 0308 × 034F ÷\t": {}, "÷ D800 ÷ 0308 ÷ 1F1E6 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 0600 ÷\t": {}, "÷ D800 ÷ 0903 ÷\t": {}, "÷ D800 ÷ 0308 × 0903 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 1100 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 1160 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 11A8 ÷\t": {}, "÷ D800 ÷ 0308 ÷ AC00 ÷\t": {}, "÷ D800 ÷ 0308 ÷ AC01 ÷\t": {}, "÷ D800 ÷ 0308 ÷ 231A ÷\t": {}, "÷ D800 ÷ 0300 ÷\t": {}, "÷ D800 ÷ 0308 × 0300 ÷\t": {}, "÷ D800 ÷ 200D ÷\t": {}, "÷ D800 ÷ 0308 × 200D ÷\t": {}, "÷ D800 ÷ 0308 ÷ 0378 ÷\t": {}, "÷ D800 ÷ 0308 ÷ D800 ÷\t": {}, "÷ 0061 ÷ 0600 × 0062 ÷\t": {}, } func breakTestInput(ti string) (string, []string) { //fmt.Printf("breaking up %s\n", ti) sc := bufio.NewScanner(strings.NewReader(ti)) sc.Split(bufio.ScanWords) out := make([]string, 0, 10) inp := bytes.NewBuffer(make([]byte, 0, 20)) run := bytes.NewBuffer(make([]byte, 0, 20)) for sc.Scan() { token := sc.Text() if token == "÷" { if run.Len() > 0 { out = append(out, run.String()) run.Reset() } } else if token == "×" { // do nothing } else { n, _ := strconv.ParseUint(token, 16, 64) run.WriteRune(rune(n)) inp.WriteRune(rune(n)) } } //fmt.Printf("input = '%s'\n", inp.String()) //fmt.Printf("output = %#v\n", out) return inp.String(), out } func executeSingleTest(t *testing.T, seg *segment.Segmenter, tno int, in string, out []string) bool { tracing.Infof("expecting %v", ost(out)) seg.Init(strings.NewReader(in)) i := 0 ok := true for seg.Next() { if i >= len(out) { t.Logf("broken lexemes longer than expected output") } else if out[i] != seg.Text() { p0, p1 := seg.Penalties() t.Logf("test #%d: penalties = %d|%d", tno, p0, p1) t.Logf("test #%d: '%x' should be '%x'", tno, string(seg.Bytes()), out[i]) ok = false } i++ } return ok } func ost(out []string) string { s := "" first := true for _, o := range out { if first { first = false } else { s += "-" } s += "[" + o + "]" } return s }
package main import "fmt" func combinationSum(candidates []int, target int) [][]int { res := [][]int{} cur := []int{} combination2(candidates, target, cur, &res, 0) return res } func combination2(candidates []int, target int, cur []int, res *[][]int, begin int) { if target == 0 { temp := make([]int, len(cur)) copy(temp, cur) *res = append(*res, temp) return } else if target < 0 { return } for i := begin; i < len(candidates); i++ { cur = append(cur, candidates[i]) combination2(candidates, target-candidates[i], cur, res, i) //i,因为可以包括自身,对比problem77 cur = cur[:len(cur)-1] } } func main() { num := []int{2, 3, 5} fmt.Println(combinationSum(num, 8)) }
package leetcode /*Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has. Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy.  (The total amount of candy a person has is the sum of the sizes of candy bars they have.) Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange. If there are multiple answers, you may return any one of them.  It is guaranteed an answer exists. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fair-candy-swap 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ import "sort" func fairCandySwap(A []int, B []int) []int { res := make([]int, 2) sort.Ints(A) sort.Ints(B) sumA, sumB := 0, 0 sizeA, sizeB := len(A), len(B) for i := 0; i < sizeA; i++ { sumA += A[i] } for i := 0; i < sizeB; i++ { sumB += B[i] } diff := (sumA - sumB) / 2 for i := 0; i < sizeA; i++ { find := binarySearch(B, A[i]-diff) if find != -1 { res[0] = A[i] res[1] = B[find] break } } return res } func binarySearch(arr []int, target int) int { begin := 0 end := len(arr) - 1 for begin <= end { mid := (begin + end) / 2 if arr[mid] == target { return mid } else if arr[mid] < target { begin = mid + 1 } else { end = mid - 1 } } return -1 }
/** * * Create BY YooDing * * Des: 远程配置文件json数据 * * Time: 2019/7/6 11:19 AM. * * <a href="https://github.com/YooDing/gone">Github</a> */ package model import ( "github.com/bitly/go-simplejson" "gone/utils" "os" "net/http" "io/ioutil" ) // //type ZipUrl struct { // ZipName string // ZipPath string //} type ConfigData struct { Version string Jdk string Tomcat string Tcpa_package string Tcpa_kernel_bash string } var ( res *simplejson.Json Server ConfigData ) func init() { //init model Server = parsing(getJson()) } func parsing(jsonStr string) ConfigData { res, _ = simplejson.NewJson([]byte(jsonStr)) version, err := res.Get("version").String() jdk, _ := res.Get("jdk").String() tomcat, _ := res.Get("tomcat").String() tcpa_package, _ := res.Get("tcpa_package").String() tcpa_kernel_bash, _ := res.Get("tcpa_kernel_bash").String() if err != nil { utils.Error("程序解析远程仓库配置json文件失败!!!!请你稍后重试!") //发生错误程序退出 os.Exit(1) } return ConfigData{version, jdk, tomcat,tcpa_package,tcpa_kernel_bash} } func getJson() string { //send get request resp, err := http.Get("https://raw.githubusercontent.com/YooDing/gone/master/config.json") if err != nil { utils.Error("连接远程服务器失败!请你稍后重试!") //发生错误程序退出 os.Exit(1) } //The last execution defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { utils.Error("解析最新资源失败!请你稍后重试!") //发生错误程序退出 os.Exit(1) } return string(body) }
/* This challenge is a slightly different kind of Code Golf challenge. Rather than coding to match IO, you code to match an interface. Background Finite state machines are very useful design models for modeling event-based programming. A state machine is defined by a set of states and tranitions between them. The machine can be in one and only one state at any given time: the current state. Naturally, the machine has an initial state. When an event occurs, it may change it's state to another state; this is called a transition. A Moore machine is simply a FSM which can produce output; each state can produce an output. For example, consider the following state machine which models a turnstile: Image of a turnstile Basic state machine example The Locked state is the initial state of the machine. Whenever the turnstile is Pushed from this state, we do nothing (go back to the Locked state). However, if we receive a Coin, we transition to the Un-locked state. Extra Coins do nothing, but a Push puts us back into the Locked state. It's not explicitly stated, but this FSM does have output: the Locked state has an output that tells the turnstile to lock it's arms, wheras the Un-locked state has an output that allows the turnstile to turn. Task You must implement a state machine class. This means that only languages with objects can compete. If there is an accepted alternative to objects in your language, that is valid (e.g. C can use structs with member functions). You must be able to access the functions of the object via obj.function or obj->function or whatever the accessor character for your language is. You are allowed to use a state machine library if it exists for your language, but you aren't allowed to use a class from the library "as your own" (don't just point at a premade class and say that that's your solution). You must implement the following methods with exactly the specified names and signatures. However, you may capitalize the first letter or switch to snake_case (e.g. mapOutput, MapOutput, or map_output are all valid). Additionally, you may take an explicit this parameter as the first parameter: map(State from, Event event, State to) Defines a transition from from to to on the event event. If from and event have both been previously passed to this method before, you may do anything at all. mapOutput(State state, Output output) Assigns the given output to the given state. If state has been previously passed to this method before, you may do anything at all. processEvent(Event event) Advances the state machine according to the transitions defined via map. Basically, if the current state of the state machine is from, then event sets the current state to the state defined by a previously called map(from, event, to). Throws an exception or fails violently if there is no mapping for the current state and given event. getOutput() Gets the output for the current state, as defined via mapOutput. Returns null or equivalent if there is no output defined for the given state. This may be an Optional type or similar if your language has one. Some sort of initial-state setting. This may be done in the constructor for your class, you may require State to have a default constructor, or you may provide some other way of setting the initial state. The idea of State, Event, and Output is that they are generic types. You don't have to support generics per se, but this means that the user of your state machine will only pass in the type State for states, the type Event for events, and the type Output for outputs. However, the state machine is expected to be "generic" in that it should be possible to use any type as a State, any type as an Event, and any type as an Output. Additionally, you map implement the map and mapOutput methods in a separate builder class, but I don't foresee that saving any bytes. Test cases Note: don't trust my code. It's untested. It's intended mostly to give an idea of what you state machine will be used like Java, classname StateMachine, initial-state passed via constructor: // States are ints, Events are chars, Outputs are ints StateMachine machine = new StateMachine(0); machine.map(0, '0', 1); machine.map(0, '1', 2); machine.map(0, '2', 3); machine.map(1, '3', 0); machine.map(1, '4', 2); machine.map(2, '5', 0); machine.map(2, '6', 1); machine.map(2, '7', 2); machine.mapOutput(1, 1); machine.mapOutput(2, 10); machine.mapOutput(3, 0); // At this point, there should be absolutely no errors at all. System.out.println(machine.getOutput()); // Should output `null` machine.processEvent('0'); // Don't count on reference equality here... System.out.println(machine.getOutput()); // Should output `1` machine.processEvent('4'); System.out.println(machine.getOutput()); // Should output `10` machine.processEvent('7'); System.out.println(machine.getOutput()); // Should output `10` machine.processEvent('6'); System.out.println(machine.getOutput()); // Should output `1` machine.processEvent('3'); System.out.println(machine.getOutput()); // Should output `null` machine.processEvent('1'); System.out.println(machine.getOutput()); // Should output `10` machine.processEvent('5'); System.out.println(machine.getOutput()); // Should output `null` machine.processEvent('2'); System.out.println(machine.getOutput()); // Should output `0` // Now any calls to processEvent should cause an exception to be thrown. machine.processEvent('0'); // Throws an exception or crashes the program. Ruby, classname SM, initial-state through attr_writer on i: sm = SM.new sm.i = :init # All states will be symbols in this case. [ [:init, [], :init], [:init, [1], :state1], [:init, [2, 3], :state2], [:state1, [], :init], [:state1, [1], :state1], [:state1, [2, 3], :state2], [:state2, [], :init], [:state2, [1], :state1], [:state2, [2, 3], :state2] ].each { |from, trigger, to| sm.map(from, trigger, to) } sm.mapOutput(:state1, [1]) sm.mapOutput(:state2, [[2, 3], 4, 5]) p sm.getOutput # => nil sm.processEvent [] p sm.getOutput # => nil sm.processEvent [1] p sm.getOutput # => [1] sm.processEvent [1] p sm.getOutput # => [1] sm.processEvent [2, 3] p sm.getOutput # => [[2, 3], 4, 5] sm.processEvent [2, 3] p sm.getOutput # => [[2, 3], 4, 5] sm.processEvent [] p sm.getOutput # => nil sm.processEvent [2, 3] p sm.getOutput # => [[2, 3], 4, 5] sm.processEvent [1] p sm.getOutput # => [1] sm.processEvent [] p sm.getOutput # => nil Note that even though there are only a few test cases, you must support arbitrary input to these functions. */ package main func main() { m := NewMoore("0") m.Map("0", "0", "1") m.Map("0", "1", "2") m.Map("0", "2", "3") m.Map("1", "3", "0") m.Map("1", "4", "2") m.Map("2", "5", "0") m.Map("2", "6", "1") m.Map("2", "7", "2") m.Hook("1", "1") m.Hook("2", "10") m.Hook("3", "0") assert(m.Output() == "") assert(m.Process("0")) assert(m.Output() == "1") assert(m.Process("4")) assert(m.Output() == "10") assert(m.Process("7")) assert(m.Output() == "10") assert(m.Process("6")) assert(m.Output() == "1") assert(m.Process("3")) assert(m.Output() == "") assert(m.Process("1")) assert(m.Output() == "10") assert(m.Process("5")) assert(m.Output() == "") assert(m.Process("2")) assert(m.Output() == "0") assert(!m.Process("0")) } func assert(x bool) { if !x { panic("assertion failed") } } type Moore struct { state string transition map[[2]string]string output map[string]string } func NewMoore(state string) *Moore { return &Moore{ state: state, transition: make(map[[2]string]string), output: make(map[string]string), } } func (m *Moore) Map(from, event, to string) { key := [2]string{from, event} m.transition[key] = to } func (m *Moore) Hook(state, output string) { m.output[state] = output } func (m *Moore) Process(event string) bool { key := [2]string{m.state, event} if _, found := m.transition[key]; !found { return false } m.state = m.transition[key] return true } func (m *Moore) Output() string { return m.output[m.state] }
/* Copyright 2019 Dmitry Kolesnikov, All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Package gouldian is Go combinator library for building HTTP services. The library is a thin layer of purely functional abstractions to building simple and declarative api implementations in the absence of pattern matching for traditional and serverless applications. Inspiration The library is heavily inspired by Scala Finch https://github.com/finagle/finch. Getting started Here is minimal "Hello World!" example that matches any HTTP requests to /hello endpoint. package main import ( µ "github.com/fogfish/gouldian" "github.com/fogfish/gouldian/server/httpd" "net/http" ) func main() { http.ListenAndServe(":8080", httpd.Serve(hello()), ) } func hello() µ.Endpoint { return µ.GET( µ.URI(µ.Path("hello")), func(ctx µ.Context) error { return µ.Status.OK(µ.WithText("Hello World!")) }, ) } See examples folder for advanced use-case. Next steps ↣ Study Endpoint type and its composition, see User Guide ↣ Check build-in collection of endpoints to deal with HTTP request. See types: HTTP, APIGateway ↣ Endpoint always returns some `Output` that defines HTTP response. There are three cases of output: HTTP Success, HTTP Failure and general error. See Output, Issue types. */ package gouldian
package main import ( "bytes" "os" "path/filepath" "reflect" "strings" "testing" ) const minimalSocketFilter = `__attribute__((section("socket"), used)) int main() { return 0; }` func TestCompile(t *testing.T) { dir := mustWriteTempFile(t, "test.c", minimalSocketFilter) var dep bytes.Buffer err := compile(compileArgs{ cc: clangBin(t), dir: dir, source: filepath.Join(dir, "test.c"), dest: filepath.Join(dir, "test.o"), dep: &dep, }) if err != nil { t.Fatal("Can't compile:", err) } stat, err := os.Stat(filepath.Join(dir, "test.o")) if err != nil { t.Fatal("Can't stat output:", err) } if stat.Size() == 0 { t.Error("Compilation creates an empty file") } if dep.Len() == 0 { t.Error("Compilation doesn't generate depinfo") } if _, err := parseDependencies(dir, &dep); err != nil { t.Error("Can't parse dependencies:", err) } } func TestReproducibleCompile(t *testing.T) { clangBin := clangBin(t) dir := mustWriteTempFile(t, "test.c", minimalSocketFilter) err := compile(compileArgs{ cc: clangBin, dir: dir, source: filepath.Join(dir, "test.c"), dest: filepath.Join(dir, "a.o"), }) if err != nil { t.Fatal("Can't compile:", err) } err = compile(compileArgs{ cc: clangBin, dir: dir, source: filepath.Join(dir, "test.c"), dest: filepath.Join(dir, "b.o"), }) if err != nil { t.Fatal("Can't compile:", err) } aBytes, err := os.ReadFile(filepath.Join(dir, "a.o")) if err != nil { t.Fatal(err) } bBytes, err := os.ReadFile(filepath.Join(dir, "b.o")) if err != nil { t.Fatal(err) } if !bytes.Equal(aBytes, bBytes) { t.Error("Compiling the same file twice doesn't give the same result") } } func TestTriggerMissingTarget(t *testing.T) { dir := mustWriteTempFile(t, "test.c", `_Pragma(__BPF_TARGET_MISSING);`) err := compile(compileArgs{ cc: clangBin(t), dir: dir, source: filepath.Join(dir, "test.c"), dest: filepath.Join(dir, "a.o"), }) if err == nil { t.Fatal("No error when compiling __BPF_TARGET_MISSING") } } func TestParseDependencies(t *testing.T) { const input = `main.go: /foo/bar baz frob: /gobble \ gubble nothing: ` have, err := parseDependencies("/foo", strings.NewReader(input)) if err != nil { t.Fatal("Can't parse dependencies:", err) } want := []dependency{ {"/foo/main.go", []string{"/foo/bar", "/foo/baz"}}, {"/foo/frob", []string{"/gobble", "/foo/gubble"}}, {"/foo/nothing", nil}, } if !reflect.DeepEqual(have, want) { t.Logf("Have: %#v", have) t.Logf("Want: %#v", want) t.Error("Result doesn't match") } output, err := adjustDependencies("/foo", want) if err != nil { t.Error("Can't adjust dependencies") } const wantOutput = `main.go: \ bar \ baz frob: \ ../gobble \ gubble nothing: ` if have := string(output); have != wantOutput { t.Logf("Have:\n%s", have) t.Logf("Want:\n%s", wantOutput) t.Error("Output doesn't match") } } func mustWriteTempFile(t *testing.T, name, contents string) string { t.Helper() tmp, err := os.MkdirTemp("", "bpf2go") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(tmp) }) tmpFile := filepath.Join(tmp, name) if err := os.WriteFile(tmpFile, []byte(contents), 0660); err != nil { t.Fatal(err) } return tmp }
// +build !windows package server import ( "context" "io" "io/ioutil" "log" "os" "path/filepath" "testing" "github.com/devspace-cloud/devspace/sync/remote" "github.com/devspace-cloud/devspace/sync/util" ) func TestDownstreamServer(t *testing.T) { fromDir, err := ioutil.TempDir("", "") if err != nil { t.Fatal(err) } toDir, err := ioutil.TempDir("", "") if err != nil { t.Fatal(err) } defer os.RemoveAll(fromDir) defer os.RemoveAll(toDir) err = createFiles(fromDir, fileStructure) if err != nil { t.Fatal(err) } err = createFiles(toDir, overwriteFileStructure) if err != nil { t.Fatal(err) } // Upload tar with client clientReader, clientWriter := io.Pipe() serverReader, serverWriter := io.Pipe() go func() { err := StartDownstreamServer(serverReader, clientWriter, &DownstreamOptions{ RemotePath: fromDir, ExcludePaths: []string{"emptydir"}, ExitOnClose: false, }) if err != nil { t.Fatal(err) } }() conn, err := util.NewClientConnection(clientReader, serverWriter) if err != nil { t.Fatal(err) } // Count changes client := remote.NewDownstreamClient(conn) amount, err := client.ChangesCount(context.Background(), &remote.Empty{}) if err != nil { t.Fatal(err) } if amount.Amount != 6 { t.Fatalf("Unexpected change amount, expected 6, got %d", amount.Amount) } changesClient, err := client.Changes(context.Background(), &remote.Empty{}) if err != nil { t.Fatal(err) } log.Println("Created downstream server & client") changes, err := getAllChanges(changesClient) if err != nil { t.Fatal(err) } log.Println("Got all changes") // Download all the changed files downloadClient, err := client.Download(context.Background()) if err != nil { t.Fatal(err) } for _, change := range changes { if change.ChangeType != remote.ChangeType_CHANGE { t.Fatal("Expected only changes with type change") } err := downloadClient.Send(&remote.Paths{ Paths: []string{ change.Path, }, }) if err != nil { t.Fatal(err) } } err = downloadClient.CloseSend() if err != nil { t.Fatal(err) } log.Println("Sent all download paths") // Tar pipe r, w, err := os.Pipe() if err != nil { t.Fatal(err) } defer r.Close() for { chunk, err := downloadClient.Recv() if err == io.EOF { break } else if err != nil { t.Fatal(err) } _, err = w.Write(chunk.Content) if err != nil { t.Fatal(err) } } w.Close() log.Println("Downloaded complete file") err = untarAll(r, &UpstreamOptions{UploadPath: toDir}) if err != nil { t.Fatal(err) } log.Println("Untared the downloaded file") delete(fileStructure.Children, "emptydir") err = compareFiles(toDir, fileStructure) if err != nil { t.Fatal(err) } // Check for changes again changesClient, err = client.Changes(context.Background(), &remote.Empty{}) if err != nil { t.Fatal(err) } changes, err = getAllChanges(changesClient) if err != nil { t.Fatal(err) } if len(changes) > 0 { t.Fatal("Expected 0 changes") } // Change file err = ioutil.WriteFile(filepath.Join(fromDir, "test.txt"), []byte("overidden"), 0755) if err != nil { t.Fatal(err) } err = os.Remove(filepath.Join(fromDir, "emptydir2")) if err != nil { t.Fatal(err) } log.Println("Get changes again") // Check for changes again changesClient, err = client.Changes(context.Background(), &remote.Empty{}) if err != nil { t.Fatal(err) } changes, err = getAllChanges(changesClient) if err != nil { t.Fatal(err) } if len(changes) != 2 { t.Fatalf("Expected 2 changes, got %d changes", len(changes)) } } func getAllChanges(changesClient remote.Downstream_ChangesClient) ([]*remote.Change, error) { changes := make([]*remote.Change, 0, 32) for { changeChunk, err := changesClient.Recv() if changeChunk != nil { for _, change := range changeChunk.Changes { changes = append(changes, change) } } if err == io.EOF { break } else if err != nil { return nil, err } } return changes, nil }
package cmd import ( "log" "github.com/spf13/cobra" "github.com/yugabyte/yugabyte-db/managed/yba-installer/common" ) func cleanCmd() *cobra.Command { var removeData bool clean := &cobra.Command{ Use: "clean [--all]", Short: "The clean command uninstalls your YugabyteDB Anywhere instance.", Long: ` The clean command performs a complete removal of your YugabyteDB Anywhere Instance by stopping all services and (optionally) removing data directories.`, Args: cobra.MaximumNArgs(1), // Confirm with the user before deleting ALL data. PreRun: func(cmd *cobra.Command, args []string) { if removeData { prompt := "--all was specified. This will delete all data with no way to recover. Continue?" if !common.UserConfirm(prompt, common.DefaultNo) { log.Fatal("Stopping clean") } } }, Run: func(cmd *cobra.Command, args []string) { // TODO: Only clean up per service. // Clean up services in reverse order. serviceNames := []string{} for i := len(serviceOrder) - 1; i >= 0; i-- { services[serviceOrder[i]].Uninstall(removeData) serviceNames = append(serviceNames, services[serviceOrder[i]].Name()) } common.Uninstall(serviceNames, removeData) }, } clean.Flags().BoolVar(&removeData, "all", false, "also clean out data (default: false)") return clean } func init() { // Clean must be run from installed yba-ctl if common.RunFromInstalled() { rootCmd.AddCommand(cleanCmd()) } }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/8/15 4:25 下午 # @File : lt_4_有序数组的中位数.go # @Description : # @Attention : */ package offer func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { l1, l2 := len(nums1), len(nums2) left, right := 0, 0 start1, start2 := 0, 0 for i := 0; i <= (l1+l2)>>1; i++ { left = right if start1 < l1 && (nums1[start1] < nums2[start2] || start2 >= l2) { right = nums1[start1] start1++ } else { right = nums2[start2] start2++ } } if (l1+l2)&1 == 0 { return float64(left+right) / 2.0 } return float64(right) }
/** Copyright @ 2014 OPS, Qunar Inc. (qunar.com) Author: tingfang.bao <tingfang.bao@qunar.com> DateTime: 14-8-20 下午2:57 */ package utils import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "reflect" "regexp" ) /** 正则表达式分组工具 例如 正则表达式(已经编译过):"(?P<name>[A-Za-z]+)-(?P<age>\\d+)" name和page都是属性名称 字符串str:CGC-30 返回结果:map[string]string{"name":CGC,"age":30} */ func NamedRegexpGroup(str string, reg *regexp.Regexp) (ng map[string]string, matched bool) { rst := reg.FindStringSubmatch(str) //fmt.Printf("%s => %s => %s\n\n", reg, str, rst) if len(rst) < 1 { return } ng = make(map[string]string) lenRst := len(rst) names := reg.SubexpNames() for index, name := range names { /** names是一个字符串数据,["","name","age"] 所以要过滤到第一个空的分组,这是默认分组 */ if index == 0 || name == "" { continue } if index+1 > lenRst { break } ng[name] = rst[index] } matched = true return } //func main() { // reg := regexp.MustCompile("(?P<name>[A-Za-z]+)-(?P<age>\\d+)") // ng, matched := NamedRegexpGroup("CGC-30", reg) // // fmt.Println(ng) // fmt.Println(matched) //} /** 检测文件是否存在 */ func FileExists(path_ string) (bool, error) { _, err := os.Stat(path_) if err == nil { return true, nil } /** 判断返回的是否为文件或目录找不到的错误 */ if os.IsNotExist(err) { return false, nil } return false, err } /** 驼峰命名换成下划线命名方式 例如:"HelloWorld" to "hello_world" */ func SnakeCasedName(name string) string { new_str := make([]rune, 0) firstTime := true for _, chr := range name { if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { if firstTime == true { firstTime = false } else { new_str = append(new_str, '_') } chr -= ('A'-'a') } new_str = append(new_str, chr) } return string(new_str) } /** map转化为struct:https://github.com/sdegutis/go.mapstruct */ func MapToStruct(m map[string]interface{}, s interface{}) { v := reflect.Indirect(reflect.ValueOf(s)) for i := 0; i < v.NumField(); i++ { key := v.Type().Field(i).Name v.Field(i).Set(reflect.ValueOf(m[key])) } } /** struct转化为map 内部使用 注意:s必须为struct,不能为指针 */ func rawStructToMap(s interface{}, snakeCasedKey bool) map[string]interface{} { v := reflect.ValueOf(s) /** 这里尝试进行了指针转换为struct */ for v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { panic(fmt.Sprintf("param s must be struct, but got %s", s)) } m := make(map[string]interface{}) for i := 0; i < v.NumField(); i++ { key := v.Type().Field(i).Name if snakeCasedKey { key = SnakeCasedName(key) } val := v.Field(i).Interface() m[key] = val } return m } /** struct转化为map,转化后的map的key,与struct的字段名称一致 */ func StructToMap(s interface{}) map[string]interface{} { return rawStructToMap(s, false) } /** struct转化为map,转化后的map的key为全小写,下划线分割格式 */ func StructToSnakeKeyMap(s interface{}) map[string]interface{} { return rawStructToMap(s, true) } /** 获取struct的name */ func StructName(s interface{}) string { v := reflect.TypeOf(s) for v.Kind() == reflect.Ptr { v = v.Elem() } return v.Name() } /** 加载json文件到map,格式如下 { "ServerConfig": { "Addr": ":8888", "ReadTimeout": "20ms", "WriteTimeout": "20ms", "MaxHeaderBytes": 110, "StaticPath": "mystatic", "ViewPath": "myview", "Layout": "mylayout", "LogLevel": 3, "Debug": true } } */ func LoadJsonFile(filePath string) (map[string]interface{}, error) { fi, err := os.Stat(filePath) if err != nil { return nil, err } else if fi.IsDir() { return nil, errors.New(filePath+" is not a file.") } var content []byte content, err = ioutil.ReadFile(filePath) if err != nil { return nil, err } var conf map[string]interface{} err = json.Unmarshal(content, &conf) if err != nil { return nil, err } return conf, nil } /** 辅助工具类,如果从map中获取不到key对应的value,返回默认值 */ func getOrDefault(m map[string]string, key, defaultVal string) string { msg, ok := m[key] if ok && msg != "" { return msg } return defaultVal }
// Copyright 2016 by caixw, All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. // Package syntax 负责对标签语法的解析操作。 package syntax import ( "log" "github.com/issue9/is" "github.com/tanxiaolong/apidoc/locale" "github.com/tanxiaolong/apidoc/types" "github.com/tanxiaolong/apidoc/vars" ) // Input 由外界提供的与标签语法相关的内容。 type Input struct { File string // 该段代码所在的文件 Line int // 该段代码在文件中的行号 Data []rune // 需要解析的代码段 Error *log.Logger // 出错时的输出通道 Warn *log.Logger // 警告信息的输出通道 } // Parse 分析一段代码,并将结果保存到 d 中。 // // 若出错,则会在 Input.Error 中输出错误信息,并中断解析, // 也不会在 d 中添加任何内容;若是警告信息,会继续执行。 func Parse(input *Input, d *types.Doc) { l := newLexer(input) for { switch { case l.matchTag(vars.APIDoc): if !l.scanAPIDoc(d) { return } case l.matchTag(vars.API): api, ok := l.scanAPI() if !ok || api == nil { // 当有 ignore 标签时,会返回 nil,true return } d.NewAPI(api) case l.match(vars.API): l.backup() l.syntaxWarn(locale.ErrUnknownTag, l.readWord()) l.readTag() // 指针移到下一个标签处 default: if l.atEOF() { return } l.pos++ // 去掉无用的字符。 } } // end for } // 解析 @apidoc 及其子标签 // // @apidoc title of doc // @apiVersion 2.0 // @apiBaseURL https://api.caixw.io // @apiLicense MIT https://opensource.org/licenses/MIT // // @apiContent // content1 // content2 func (l *lexer) scanAPIDoc(d *types.Doc) bool { if len(d.Title) > 0 || len(d.Version) > 0 { l.syntaxError(locale.ErrDuplicateTag, vars.APIDoc) return false } t := l.readTag() d.Title = t.readLine() if len(d.Title) == 0 { l.syntaxError(locale.ErrTagArgNotEnough, vars.APIDoc) return false } if !t.atEOF() { l.syntaxError(locale.ErrTagArgTooMuch, vars.APIDoc) return false } for { switch { case l.matchTag(vars.APIVersion): t := l.readTag() d.Version = t.readLine() if len(d.Version) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APIVersion) return false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIVersion) return false } case l.matchTag(vars.APIBaseURL): t := l.readTag() d.BaseURL = t.readLine() if len(d.BaseURL) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APIBaseURL) return false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIBaseURL) return false } case l.matchTag(vars.APILicense): t := l.readTag() d.LicenseName = t.readWord() d.LicenseURL = t.readLine() if len(d.LicenseName) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APILicense) return false } if len(d.LicenseURL) > 0 && !is.URL(d.LicenseURL) { t.syntaxError(locale.ErrSecondArgMustURL) return false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APILicense) return false } case l.matchTag(vars.APIContent): d.Content = l.readEnd() case l.match(vars.API): // 不认识的标签 l.backup() l.syntaxError(locale.ErrUnknownTag, l.readWord()) return false default: if l.atEOF() { return true } l.pos++ // 去掉无用的字符。 } } // end for } // 解析 @api 及其子标签 func (l *lexer) scanAPI() (*types.API, bool) { api := &types.API{} t := l.readTag() api.Method = t.readWord() api.URL = t.readWord() api.Summary = t.readLine() if len(api.Method) == 0 || len(api.URL) == 0 || len(api.Summary) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.API) return nil, false } api.Description = t.readEnd() LOOP: for { switch { case l.matchTag(vars.APIIgnore): return nil, true case l.matchTag(vars.APIGroup): if !l.scanGroup(api) { return nil, false } case l.matchTag(vars.APIQuery): if !l.scanAPIQueries(api) { return nil, false } case l.matchTag(vars.APIParam): if !l.scanAPIParams(api) { return nil, false } case l.matchTag(vars.APIRequest): req, ok := l.scanAPIRequest() if !ok { return nil, false } api.Request = req case l.matchTag(vars.APIError): resp, ok := l.scanResponse(vars.APIError) if !ok { return nil, false } api.Error = resp case l.matchTag(vars.APISuccess): resp, ok := l.scanResponse(vars.APISuccess) if !ok { return nil, false } api.Success = resp case l.match(vars.API): // 不认识的标签 l.backup() l.syntaxWarn(locale.ErrUnknownTag, l.readWord()) l.readTag() // 指针移到下一个标签处 default: if l.atEOF() { break LOOP } l.pos++ // 去掉无用的字符。 } } // end for if api.Success == nil { l.syntaxError(locale.ErrSuccessNotEmpty) return nil, false } if len(api.Group) == 0 { api.Group = vars.DefaultGroupName } return api, true } func (l *lexer) scanGroup(api *types.API) bool { t := l.readTag() api.Group = t.readWord() if len(api.Group) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APIGroup) return false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIGroup) return false } return true } func (l *lexer) scanAPIQueries(api *types.API) bool { if api.Queries == nil { api.Queries = make([]*types.Param, 0, 1) } if p, ok := l.scanAPIParam(vars.APIQuery); ok { api.Queries = append(api.Queries, p) return true } return false } func (l *lexer) scanAPIParams(api *types.API) bool { if api.Params == nil { api.Params = make([]*types.Param, 0, 1) } if p, ok := l.scanAPIParam(vars.APIParam); ok { api.Params = append(api.Params, p) return true } return false } // 解析 @apiRequest 及其子标签 func (l *lexer) scanAPIRequest() (*types.Request, bool) { t := l.readTag() r := &types.Request{ Type: t.readLine(), Headers: map[string]string{}, Params: []*types.Param{}, Examples: []*types.Example{}, } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIRequest) return nil, false } LOOP: for { switch { case l.matchTag(vars.APIHeader): t := l.readTag() key := t.readWord() val := t.readLine() if len(key) == 0 || len(val) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APIHeader) return nil, false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIHeader) return nil, false } r.Headers[string(key)] = string(val) case l.matchTag(vars.APIParam): p, ok := l.scanAPIParam(vars.APIParam) if !ok { return nil, false } r.Params = append(r.Params, p) case l.matchTag(vars.APIExample): e, ok := l.scanAPIExample() if !ok { return nil, false } r.Examples = append(r.Examples, e) case l.match(vars.API): // 其它 api*,退出。 l.backup() break LOOP default: if l.atEOF() { break LOOP } l.pos++ // 去掉无用的字符。 } // end switch } // end for return r, true } // 解析 @apiSuccess 或是 @apiError 及其子标签。 func (l *lexer) scanResponse(tagName string) (*types.Response, bool) { tag := l.readTag() resp := &types.Response{ Code: tag.readWord(), Summary: tag.readLine(), Headers: map[string]string{}, Params: []*types.Param{}, Examples: []*types.Example{}, } if len(resp.Code) == 0 || len(resp.Summary) == 0 { tag.syntaxError(locale.ErrTagArgNotEnough, tagName) return nil, false } if !tag.atEOF() { tag.syntaxError(locale.ErrTagArgTooMuch, tagName) return nil, false } LOOP: for { switch { case l.matchTag(vars.APIHeader): t := l.readTag() key := t.readWord() val := t.readLine() if len(key) == 0 || len(val) == 0 { t.syntaxError(locale.ErrTagArgNotEnough, vars.APIHeader) return nil, false } if !t.atEOF() { t.syntaxError(locale.ErrTagArgTooMuch, vars.APIHeader) return nil, false } resp.Headers[key] = val case l.matchTag(vars.APIParam): p, ok := l.scanAPIParam(vars.APIParam) if !ok { return nil, false } resp.Params = append(resp.Params, p) case l.matchTag(vars.APIExample): e, ok := l.scanAPIExample() if !ok { return nil, false } resp.Examples = append(resp.Examples, e) case l.match(vars.API): // 其它 api*,退出。 l.backup() break LOOP default: if l.atEOF() { break LOOP } l.pos++ // 去掉无用的字符。 } } return resp, true } // 解析 @apiExample 标签 func (l *lexer) scanAPIExample() (*types.Example, bool) { tag := l.readTag() example := &types.Example{ Type: tag.readWord(), Code: tag.readEnd(), } if len(example.Type) == 0 || len(example.Code) == 0 { tag.syntaxError(locale.ErrTagArgNotEnough, vars.APIExample) return nil, false } return example, true } // 解析 @apiParam 标签 func (l *lexer) scanAPIParam(tagName string) (*types.Param, bool) { p := &types.Param{} tag := l.readTag() p.Name = tag.readWord() p.Type = tag.readWord() p.Summary = tag.readEnd() if len(p.Name) == 0 || len(p.Type) == 0 || len(p.Summary) == 0 { tag.syntaxError(locale.ErrTagArgNotEnough, tagName) return nil, false } return p, true }
package action import ( "errors" "github.com/agiledragon/trans-dsl" "github.com/agiledragon/trans-dsl/test/context" ) type StubActivateSomething struct { } func (this *StubActivateSomething) Exec(transInfo *transdsl.TransInfo) error { stubInfo := transInfo.AppInfo.(*context.StubInfo) if stubInfo.X == "test" { return errors.New("something wrong") } stubInfo.SpecialNum = 20 stubInfo.LoopValue++ return nil } func (this *StubActivateSomething) Rollback(transInfo *transdsl.TransInfo) { }
package resource import ( "time" ) // DriveData holds the properties of a team drive. type DriveData struct { Name string `json:"name"` Created time.Time `json:"created,omitempty"` Permissions []Permission `json:"permissions,omitempty"` }