text
stringlengths
11
4.05M
package adding // Post defines the storage form of a post type Post struct { ID string `json:"id"` Body string `json:"body"` }
package car import ( "errors" "fmt" "io/ioutil" "log" "strings" "sync" "time" "github.com/shanghuiyang/go-speech/oauth" "github.com/shanghuiyang/go-speech/speech" "github.com/shanghuiyang/image-recognizer/recognizer" "github.com/shanghuiyang/rpi-devices/dev" "github.com/shanghuiyang/rpi-devices/util" cv "github.com/shanghuiyang/rpi-devices/util/cv/mock" "github.com/shanghuiyang/rpi-devices/util/geo" ) // Car ... type Car struct { engine *dev.L298N horn *dev.Buzzer led *dev.Led light *dev.Led camera *dev.Camera lc12s *dev.LC12S chOp chan Op // self-driving servo *dev.SG90 dmeter dev.DistMeter encoder *dev.Encoder gy25 *dev.GY25 collisions []*dev.Collision selfdriving bool servoAngle int // speed-driving asr *speech.ASR tts *speech.TTS imgr *recognizer.Recognizer speechdriving bool volume int // self-tracking tracker *cv.Tracker selftracking bool // nav gps *dev.GPS dest *geo.Point lastLoc *geo.Point gpslogger *util.GPSLogger selfnav bool } // New ... func New(cfg *Config) *Car { car := &Car{ engine: cfg.Engine, horn: cfg.Horn, led: cfg.Led, light: cfg.Led, camera: cfg.Camera, lc12s: cfg.LC12S, servo: cfg.Servo, dmeter: cfg.DistMeter, gy25: cfg.GY25, collisions: cfg.Collisions, gps: cfg.GPS, servoAngle: 0, selfdriving: false, speechdriving: false, selftracking: false, selfnav: false, chOp: make(chan Op, chSize), } return car } // Start ... func (c *Car) Start() error { go c.start() go c.servo.Roll(0) go c.blink() go c.joystick() go c.setVolume(40) c.speed(30) return nil } // Do ... func (c *Car) Do(op Op) { c.chOp <- op } // Stop ... func (c *Car) Stop() error { close(c.chOp) c.engine.Stop() return nil } // GetState ... func (c *Car) GetState() (selfDriving, selfTracking, speechDriving bool) { return c.selfdriving, c.selftracking, c.speechdriving } // SetDest ... func (c *Car) SetDest(dest *geo.Point) { if c.selfnav { return } c.dest = dest } func (c *Car) start() { for op := range c.chOp { switch op { case forward: c.forward() case backward: c.backward() case left: c.left() case right: c.right() case stop: c.stop() case beep: go c.beep() case servoleft: go c.servoLeft() case servoright: go c.servoRight() case servoahead: go c.servoAhead() case musicon: go c.musicOn() case musicoff: go c.musicOff() case selfdrivingon: go c.selfDrivingOn() case selfdrivingoff: go c.selfDrivingOff() case selftrackingon: go c.selfTrackingOn() case selftrackingoff: go c.selfTrackingOff() case speechdrivingon: go c.speechDrivingOn() case speechdrivingoff: go c.speechDrivingOff() case selfnavon: go c.selfNavOn() case selfnavoff: go c.selfNavOff() default: log.Printf("[car]invalid op") } } } // forward ... func (c *Car) forward() { log.Printf("[car]forward") c.engine.Forward() } // backward ... func (c *Car) backward() { log.Printf("[car]backward") c.engine.Backward() } // left ... func (c *Car) left() { log.Printf("[car]left") c.engine.Left() } // right ... func (c *Car) right() { log.Printf("[car]right") c.engine.Right() } // stop ... func (c *Car) stop() { log.Printf("[car]stop") c.engine.Stop() } func (c *Car) speed(s uint32) { log.Printf("[car]speed %v%%", s) c.engine.Speed(s) } // beep ... func (c *Car) beep() { log.Printf("[car]beep") if c.horn == nil { return } c.horn.Beep(5, 100) } func (c *Car) blink() { for { if c.speechdriving { util.DelayMs(2000) continue } c.led.Blink(1, 1000) } } func (c *Car) musicOn() { log.Printf("[car]music on") util.PlayMp3("./music/*.mp3") } func (c *Car) musicOff() { log.Printf("[car]music off") util.StopMp3() time.Sleep(1 * time.Second) } func (c *Car) servoLeft() { angle := c.servoAngle - 15 if angle < -90 { angle = -90 } c.servoAngle = angle log.Printf("[car]servo roll %v", angle) if c.servo == nil { return } c.servo.Roll(angle) } func (c *Car) servoRight() { angle := c.servoAngle + 15 if angle > 90 { angle = 90 } c.servoAngle = angle log.Printf("[car]servo roll %v", angle) if c.servo == nil { return } c.servo.Roll(angle) } func (c *Car) servoAhead() { c.servoAngle = 0 log.Printf("[car]servo roll %v", 0) if c.servo == nil { return } c.servo.Roll(0) } func (c *Car) selfDriving() { if c.dmeter == nil { log.Printf("[car]can't self-driving without the distance sensor") return } // make a warning before running into self-driving mode c.horn.Beep(3, 300) var ( fwd bool retry int mindAngle int maxdAngle int mind float64 maxd float64 op = forward chOp = make(chan Op, 4) ) for c.selfdriving || c.selftracking { select { case p := <-chOp: op = p for len(chOp) > 0 { log.Printf("[car]skip op: %v", <-chOp) // _ = <-chOp } default: // do nothing } log.Printf("[car]op: %v", op) switch op { case backward: fwd = false c.stop() util.DelayMs(20) c.backward() util.DelayMs(500) chOp <- stop continue case stop: fwd = false c.stop() util.DelayMs(20) chOp <- scan continue case scan: fwd = false mind, maxd, mindAngle, maxdAngle = c.scan() log.Printf("[car]mind=%.0f, maxd=%.0f, mindAngle=%v, maxdAngle=%v", mind, maxd, mindAngle, maxdAngle) if mind < 10 && mindAngle != 90 && mindAngle != -90 && retry < 4 { chOp <- backward retry++ continue } chOp <- turn retry = 0 case turn: fwd = false c.turn(maxdAngle) util.DelayMs(150) chOp <- forward continue case forward: if !fwd { c.forward() fwd = true go c.detecting(chOp) } util.DelayMs(50) continue case pause: fwd = false util.DelayMs(500) continue } } c.stop() util.DelayMs(1000) close(chOp) } func (c *Car) speechDriving() { var ( op = stop fwd = false chOp = make(chan Op, 4) wg sync.WaitGroup ) wg.Add(1) go c.detectSpeech(chOp, &wg) for c.speechdriving { select { case p := <-chOp: op = p for len(chOp) > 0 { // log.Printf("[car]len(chOp)=%v", len(chOp)) _ = <-chOp } default: // do nothing } log.Printf("[car]op: %v", op) switch op { case forward: if !fwd { c.forward() fwd = true go c.detecting(chOp) } util.DelayMs(50) continue case backward: fwd = false c.stop() util.DelayMs(20) c.backward() util.DelayMs(600) chOp <- stop continue case left: fwd = false c.stop() util.DelayMs(20) c.turn(-90) util.DelayMs(20) chOp <- forward continue case right: fwd = false c.stop() util.DelayMs(20) c.turn(90) util.DelayMs(20) chOp <- forward continue case roll: fwd = false c.engine.Left() util.DelayMs(3000) chOp <- stop continue case stop: fwd = false c.stop() util.DelayMs(500) continue } } c.stop() wg.Wait() close(chOp) } func (c *Car) selfDrivingOn() { if c.selfdriving { return } c.selftracking = false c.speechdriving = false util.DelayMs(1000) // wait for self-tracking and speech-driving quit c.selfdriving = true log.Printf("[car]self-drving on") c.speed(30) c.selfDriving() } func (c *Car) selfDrivingOff() { c.selfdriving = false c.servo.Roll(0) log.Printf("[car]self-drving off") } func (c *Car) selfTrackingOn() { if c.selftracking { return } util.StopMotion() c.selfdriving = false c.speechdriving = false c.selfnav = false util.DelayMs(1000) // wait to quit self-driving & speech-driving // start slef-tracking t, err := cv.NewTracker(lh, ls, lv, hh, hs, hv) if err != nil { log.Printf("[carapp]failed to create a tracker, error: %v", err) return } c.tracker = t c.selftracking = true log.Printf("[car]self-tracking on") c.speed(30) c.selfDriving() } func (c *Car) selfTrackingOff() { c.selftracking = false c.tracker.Close() c.servo.Roll(0) util.DelayMs(500) if err := util.StartMotion(); err != nil { log.Printf("[car]failed to start motion, error: %v", err) } log.Printf("[car]self-tracking off") } func (c *Car) speechDrivingOn() { if c.speechdriving { return } c.selfdriving = false c.selftracking = false util.DelayMs(1000) // wait for self-driving and self-tracking quit c.speechdriving = true log.Printf("[car]speech-drving on") c.speed(30) c.speechDriving() } func (c *Car) speechDrivingOff() { c.speechdriving = false c.servo.Roll(0) log.Printf("[car]speech-drving off") } func (c *Car) detecting(chOp chan Op) { chQuit := make(chan bool, 4) var wg sync.WaitGroup wg.Add(1) go c.detectCollision(chOp, chQuit, &wg) wg.Add(1) go c.detectObstacles(chOp, chQuit, &wg) if c.selftracking { wg.Add(1) go c.trackingObj(chOp, chQuit, &wg) } wg.Wait() close(chQuit) } func (c *Car) detectObstacles(chOp chan Op, chQuit chan bool, wg *sync.WaitGroup) { defer wg.Done() for c.selfdriving || c.selftracking || c.speechdriving { for _, angle := range aheadAngles { select { case quit := <-chQuit: if quit { return } default: // do nothing } c.servo.Roll(angle) util.DelayMs(70) d := c.dmeter.Dist() if d < 20 { chOp <- backward chQuit <- true chQuit <- true return } if d < 40 { chOp <- stop chQuit <- true chQuit <- true return } } } } func (c *Car) detectCollision(chOp chan Op, chQuit chan bool, wg *sync.WaitGroup) { defer wg.Done() for c.selfdriving || c.selftracking || c.speechdriving { select { case quit := <-chQuit: if quit { return } default: // do nothing } for _, collision := range c.collisions { if collision.Collided() { chOp <- backward go c.horn.Beep(1, 100) log.Printf("[car]crashed") chQuit <- true chQuit <- true return } } util.DelayMs(10) } } func (c *Car) trackingObj(chOp chan Op, chQuit chan bool, wg *sync.WaitGroup) { defer wg.Done() angle := 0 for c.selftracking { select { case quit := <-chQuit: if quit { return } default: // do nothing } ok, _ := c.tracker.Locate() if !ok { continue } // found a ball log.Printf("[car]found a ball") chQuit <- true chQuit <- true chOp <- pause c.stop() firstTime := true // see a ball at the first time for c.selftracking { ok, rect := c.tracker.Locate() if !ok { // lost the ball, looking for it by turning 360 degree log.Printf("[car]lost the ball") firstTime = true if angle < 360 { c.turn(30) angle += 30 util.DelayMs(200) continue } chOp <- scan return } angle = 0 if rect.Max.Y > 580 { c.stop() c.horn.Beep(1, 300) continue } if firstTime { go c.horn.Beep(2, 100) } firstTime = false x, y := c.tracker.MiddleXY(rect) log.Printf("[car]found a ball at: (%v, %v)", x, y) if x < 200 { log.Printf("[car]turn right to the ball") c.engine.Right() util.DelayMs(100) c.engine.Stop() continue } if x > 400 { log.Printf("[car]turn left to the ball") c.engine.Left() util.DelayMs(100) c.engine.Stop() continue } log.Printf("[car]forward to the ball") c.engine.Forward() util.DelayMs(100) c.engine.Stop() } } } func (c *Car) detectSpeech(chOp chan Op, wg *sync.WaitGroup) { defer wg.Done() speechAuth := oauth.New(baiduSpeechAppKey, baiduSpeechSecretKey, oauth.NewCacheMan()) c.asr = speech.NewASR(speechAuth) c.tts = speech.NewTTS(speechAuth) imgAuth := oauth.New(baiduImgRecognitionAppKey, baiduImgRecognitionSecretKey, oauth.NewCacheMan()) c.imgr = recognizer.New(imgAuth) for c.speechdriving { log.Printf("[car]start recording") go c.led.On() wav := "car.wav" if err := util.Record(2, wav); err != nil { log.Printf("[car]failed to record the speech: %v", err) continue } go c.led.Off() log.Printf("[car]stop recording") text, err := c.asr.ToText(wav) if err != nil { log.Printf("[car]failed to recognize the speech, error: %v", err) continue } log.Printf("[car]speech: %v", text) switch { case strings.Index(text, "前") >= 0: chOp <- forward case strings.Index(text, "后") >= 0: chOp <- backward case strings.Index(text, "左") >= 0: chOp <- left case strings.Index(text, "右") >= 0: chOp <- right case strings.Index(text, "停") >= 0: chOp <- stop case strings.Index(text, "转圈") >= 0: chOp <- roll case strings.Index(text, "是什么") >= 0: c.recognize() case strings.Index(text, "开灯") >= 0: c.light.On() case strings.Index(text, "关灯") >= 0: c.light.Off() case strings.Index(text, "大声") >= 0: c.volumeUp() case strings.Index(text, "小声") >= 0: c.volumeDown() case strings.Index(text, "唱歌") >= 0: go util.PlayWav("./music/xiaomaolv.wav") default: // do nothing } } } // scan for geting the min & max distance, and their corresponding angles // mind: the min distance // maxd: the max distance // mindAngle: the angle correspond to the mind // maxdAngle: the angle correspond to the maxd func (c *Car) scan() (mind, maxd float64, mindAngle, maxdAngle int) { mind = 9999 maxd = -9999 for _, ang := range scanningAngles { c.servo.Roll(ang) util.DelayMs(100) d := c.dmeter.Dist() for i := 0; d < 0 && i < 3; i++ { util.DelayMs(100) d = c.dmeter.Dist() } if d < 0 { continue } log.Printf("[car]scan: angle=%v, dist=%.0f", ang, d) if d < mind { mind = d mindAngle = ang } if d > maxd { maxd = d maxdAngle = ang } } c.servo.Roll(0) util.DelayMs(50) return } func (c *Car) turn(angle int) { turnf := c.engine.Right if angle < 0 { turnf = c.engine.Left angle *= (-1) } yaw, _, _, err := c.gy25.Angles() if err != nil { log.Printf("[car]failed to get angles from gy-25, error: %v", err) return } retry := 0 for { turnf() yaw2, _, _, err := c.gy25.Angles() if err != nil { log.Printf("[car]failed to get angles from gy-25, error: %v", err) if retry < 3 { retry++ continue } break } ang := c.gy25.IncludedAngle(yaw, yaw2) if ang >= float64(angle) { break } time.Sleep(100 * time.Millisecond) c.engine.Stop() time.Sleep(100 * time.Millisecond) } c.engine.Stop() return } func (c *Car) turnLeft(angle int) { n := angle/5 - 1 c.encoder.Start() defer c.encoder.Stop() c.chOp <- left for i := 0; i < n; { i += c.encoder.Count1() } return } func (c *Car) turnRight(angle int) { n := angle/5 - 1 c.encoder.Start() defer c.encoder.Stop() c.chOp <- right for i := 0; i < n; { i += c.encoder.Count1() } return } func (c *Car) recognize() error { log.Printf("[car]take photo") imagef, err := c.camera.TakePhoto() if err != nil { log.Printf("[car]failed to take phote, error: %v", err) return err } util.PlayWav(letMeThinkWav) log.Printf("[car]recognize image") objname, err := c.recognizeImg(imagef) if err != nil { log.Printf("[car]failed to recognize image, error: %v", err) util.PlayWav(errorWav) return err } log.Printf("[car]object: %v", objname) if err := c.playText("这是" + objname); err != nil { log.Printf("[car]failed to play text, error: %v", err) return err } return nil } func (c *Car) setVolume(v int) error { if err := util.SetVolume(v); err != nil { log.Printf("[car]failed to set volume, error: %v", err) return err } c.volume = v return nil } func (c *Car) volumeUp() { v := c.volume + 10 if v > 100 { v = 100 } c.setVolume(v) go c.playText(fmt.Sprintf("音量%v%%", v)) } func (c *Car) volumeDown() { v := c.volume - 10 if v < 0 { v = 0 } c.setVolume(v) go c.playText(fmt.Sprintf("音量%v%%", v)) } func (c *Car) recognizeImg(imageFile string) (string, error) { if c.imgr == nil { return "", errors.New("invalid image recognizer") } name, err := c.imgr.Recognize(imageFile) if err != nil { return "", err } return name, nil } func (c *Car) toSpeech(text string) (string, error) { data, err := c.tts.ToSpeech(text) if err != nil { log.Printf("[car]failed to convert text to speech, error: %v", err) return "", err } if err := ioutil.WriteFile(thisIsXWav, data, 0644); err != nil { log.Printf("[car]failed to save %v, error: %v", thisIsXWav, err) return "", err } return thisIsXWav, nil } func (c *Car) playText(text string) error { wav, err := c.toSpeech(text) if err != nil { log.Printf("[car]failed to tts, error: %v", err) return err } if err := util.PlayWav(wav); err != nil { log.Printf("[car]failed to play wav: %v, error: %v", wav, err) return err } return nil } func (c *Car) joystick() { if c.lc12s == nil { return } c.lc12s.Wakeup() defer c.lc12s.Sleep() for { time.Sleep(200 * time.Millisecond) if c.selfdriving { continue } data, err := c.lc12s.Receive() if err != nil { log.Printf("[car]failed to receive data from LC12S, error: %v", err) continue } log.Printf("[car]LC12S received: %v", data) if len(data) != 1 { log.Printf("[car]invalid data from LC12S, data len: %v", len(data)) continue } op := (data[0] >> 4) speed := data[0] & 0x0F switch op { case 0: c.chOp <- stop case 1: c.chOp <- forward case 2: c.chOp <- backward case 3: c.chOp <- left case 4: c.chOp <- right case 5: if c.selfdriving { c.chOp <- selfdrivingoff continue } c.chOp <- selfdrivingon default: c.chOp <- stop } c.speed(uint32(speed * 10)) } } func (c *Car) selfNavOn() { if c.selfnav { return } if c.gps == nil { log.Printf("[car]failed to nav, error: without gps device") return } c.selfdriving = false c.selftracking = false c.speechdriving = false util.DelayMs(1000) // wait for self-tracking and speech-driving quit c.selfnav = true log.Printf("[car]nav on") if err := c.selfNav(); err != nil { return } c.selfnav = false } func (c *Car) selfNavOff() { c.selfnav = false log.Printf("[car]nav off") } func (c *Car) selfNav() error { if c.dest == nil { log.Printf("[car]destination didn't be set, stop nav") return errors.New("destination isn't set") } c.horn.Beep(3, 300) if !bbox.IsInside(c.dest) { log.Printf("[car]destination isn't in bbox, stop nav") return errors.New("destination isn't in bbox") } c.gpslogger = util.NewGPSLogger() if c.gpslogger == nil { log.Printf("[car]failed to new a tracker, stop nav") return errors.New("gpslogger is nil") } defer c.gpslogger.Close() var org *geo.Point for c.selfnav { pt, err := c.gps.Loc() if err != nil { log.Printf("[car]gps sensor is not ready") util.DelayMs(1000) continue } c.gpslogger.AddPoint(org) if !bbox.IsInside(pt) { log.Printf("current loc(%v) isn't in bbox(%v)", pt, bbox) continue } org = pt break } if !c.selfnav { return errors.New("nav abort") } c.lastLoc = org path, err := findPath(org, c.dest) if err != nil { log.Printf("[car]failed to find a path, error: %v", err) return errors.New("failed to find a path") } turns := turnPoints(path) var turnPts []*geo.Point var str string for _, xy := range turns { pt := xy2geo(xy) str += fmt.Sprintf("(%v) ", pt) turnPts = append(turnPts, pt) } log.Printf("[car]turn points(lat,lon): %v", str) c.chOp <- forward util.DelayMs(1000) for i, p := range turnPts { if err := c.navTo(p); err != nil { log.Printf("[car]failed to nav to (%v), error: %v", p, err) break } if i < len(turnPts)-1 { // turn point go c.horn.Beep(2, 100) } else { // destination go c.horn.Beep(5, 300) } } c.chOp <- stop return nil } func (c *Car) navTo(dest *geo.Point) error { retry := 8 for c.selfnav { loc, err := c.gps.Loc() if err != nil { c.chOp <- stop log.Printf("[car]gps sensor is not ready") util.DelayMs(1000) continue } if !bbox.IsInside(loc) { c.chOp <- stop log.Printf("current loc(%v) isn't in bbox(%v)", loc, bbox) util.DelayMs(1000) continue } c.gpslogger.AddPoint(loc) log.Printf("[car]current loc: %v", loc) d := loc.DistanceWith(c.lastLoc) log.Printf("[car]distance to last loc: %.2f m", d) if d > 4 && retry < 5 { c.chOp <- stop log.Printf("[car]bad gps signal, waiting for better gps signal") retry++ util.DelayMs(1000) continue } retry = 0 d = loc.DistanceWith(dest) log.Printf("[car]distance to destination: %.2f m", d) if d < 4 { c.chOp <- stop log.Printf("[car]arrived at the destination, nav done") return nil } side := geo.Side(c.lastLoc, loc, dest) angle := int(180 - geo.Angle(c.lastLoc, loc, dest)) if angle < 10 { side = geo.MiddleSide } log.Printf("[car]nav angle: %v, side: %v", angle, side) switch side { case geo.LeftSide: c.turnLeft(angle) case geo.RightSide: c.turnRight(angle) case geo.MiddleSide: // do nothing } c.chOp <- forward util.DelayMs(1000) c.lastLoc = loc } c.chOp <- stop return nil }
package element type Message struct { ID int64 `json:"-" db:"id"` User string `json:"user" db:"user"` Body string `json:"body" db:"body"` }
package main import ( "fmt" "log" "net/http" "strconv" ) func bankInitial() int { errors := 0 for i := 1; i <= 100; i++ { _, err := master.Insert("accounts", []interface{}{i, 100000}) if err != nil { log.Println(err) errors++ } } return errors } func problemHandler(w http.ResponseWriter, r *http.Request) { resp, _ := node.Call("problem", []interface{}{}) fmt.Fprintf(w, "%v", resp) } func bankHandler(w http.ResponseWriter, r *http.Request) { resp, _ := node.Call("info", []interface{}{}) fmt.Fprintf(w, "%v", resp) log.Println("Request") } func txHandler(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() from, _ := strconv.Atoi(query.Get("from")) to, _ := strconv.Atoi(query.Get("to")) _, err := node.Call("send", []interface{}{from, to, 1}) if err != nil { log.Printf("tx error: %v, switched to slave", err) node = slave node.Call("stop", []interface{}{}) // heavy code emulation //time.Sleep(1500 * time.Millisecond) node.Call("send", []interface{}{from, to, 1}) } }
package main const esbuildVersion = "0.8.21"
// Copyright 2014 Marc-Antoine Ruel. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. package main import ( "fmt" "github.com/maruel/subcommands" ) var cmdAsk = &subcommands.Command{ UsageLine: "ask <subcommand>", ShortDesc: "asks questions", LongDesc: "Asks one of the known subquestion.", CommandRun: func() subcommands.CommandRun { c := &askRun{} c.Init() return c }, } type askRun struct { CommonFlags who string } func (c *askRun) main(a SampleApplication, args []string) error { if err := c.Parse(a, false); err != nil { return err } fmt.Fprintf(a.GetOut(), "TODO: Implement me!\n") return nil } // 'ask' is itself an application with subcommands. type askApplication struct { SampleApplication } func (q askApplication) GetName() string { return q.SampleApplication.GetName() + " ask" } func (q askApplication) GetCommands() []*subcommands.Command { // Keep in alphabetical order of their name. return []*subcommands.Command{ cmdAskApple, cmdAskBeer, subcommands.CmdHelp, } } func (c *askRun) Run(a subcommands.Application, args []string, env subcommands.Env) int { d := a.(SampleApplication) // Create an inner application. return subcommands.Run(askApplication{d}, args) }
package main /* @Time : 2020-04-04 16:50 @Author : audiRStony @File : 04_reflectElem.go @Software: GoLand */ import ( "fmt" "reflect" ) func modifyValue(x interface{}) { /*反射接收的是动态的类型以及类型的值 原始类型为int64,所以修改时,只能修改为同类型不同值,不可跨类型 */ v := reflect.ValueOf(x) fmt.Println(v.Kind()) if v.Kind() == reflect.Ptr { //判断kind是否为指针 v.Elem().SetInt(12) //Elem()方法用来修改指针地址,提供了修改值的方法 } } func main() { var a int64 = 100 modifyValue(&a) fmt.Println(a) }
package webapp import ( "gosearch/pkg/crawler" "gosearch/pkg/engine" "gosearch/pkg/index/fakeindex" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" ) var ( client = &http.Client{Timeout: time.Second} indx = fakeindex.New() data = []crawler.Document{ crawler.Document{ ID: uint64(1), Title: "Как использовать git?", URL: "http://localhost", }, crawler.Document{ ID: uint64(2), Title: "Прикладное применение подорожника как лекарство", URL: "http://localhost", }, crawler.Document{ ID: uint64(3), Title: "Криптовалюта как будущее финансовой системы?", URL: "http://localhost", }, } engn = engine.New(indx, data) host = "0.0.0.0" port = "8000" ) type Case struct { Method string Path string Status int Result string } func TestIndex(t *testing.T) { wa := New(*engn) ts := httptest.NewServer(wa.handlers()) defer ts.Close() tests := []Case{ { Method: "GET", Path: "/index", Status: http.StatusOK, Result: "", }, { Method: "POST", Path: "/index", Status: http.StatusMethodNotAllowed, Result: "", }, { Method: "GET", Path: "/indexx", Status: http.StatusNotFound, Result: "page not found", }, } for idx, tt := range tests { req, err := http.NewRequest(tt.Method, ts.URL+tt.Path, nil) if err != nil { t.Errorf("[%d] request generating error: %v", idx, err) continue } resp, err := client.Do(req) if err != nil { t.Errorf("[%d] request error: %v", idx, err) continue } defer resp.Body.Close() if resp.StatusCode != tt.Status { t.Errorf("[%d] expected http status %v, got %v", idx, tt.Status, resp.StatusCode) continue } if tt.Status != http.StatusOK { body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("[%d] reading body error: %v", idx, err) continue } sbody := string(body) if !strings.Contains(sbody, tt.Result) { t.Errorf("[%d] results not match\nGot: %#v\nExpected: %#v", idx, sbody, tt.Result) continue } } } } func TestDocs(t *testing.T) { wa := New(*engn) ts := httptest.NewServer(wa.handlers()) defer ts.Close() tests := []Case{ { Method: "GET", Path: "/index", Status: http.StatusOK, Result: "", }, { Method: "POST", Path: "/docs", Status: http.StatusMethodNotAllowed, Result: "", }, { Method: "GET", Path: "/docss", Status: http.StatusNotFound, Result: "page not found", }, } for idx, tt := range tests { req, err := http.NewRequest(tt.Method, ts.URL+tt.Path, nil) if err != nil { t.Errorf("[%d] request generating error: %v", idx, err) continue } resp, err := client.Do(req) if err != nil { t.Errorf("[%d] request error: %v", idx, err) continue } defer resp.Body.Close() if resp.StatusCode != tt.Status { t.Errorf("[%d] expected http status %v, got %v", idx, tt.Status, resp.StatusCode) continue } if tt.Status != http.StatusOK { // пропуск кейса в ответе на который не приходит тело if tt.Result == "" { continue } body, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("[%d] reading body error: %v", idx, err) continue } sbody := string(body) if !strings.Contains(sbody, tt.Result) { t.Errorf("[%d] results not match\nGot: %#v\nExpected: %#v", idx, sbody, tt.Result) continue } } } }
package commands import ( "os" "path/filepath" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/pkg/errors" ini "gopkg.in/ini.v1" ) func getSubFromAzDir(root string) (string, error) { subConfig, err := ini.Load(filepath.Join(root, "clouds.config")) if err != nil { return "", errors.Wrap(err, "error decoding cloud subscription config") } cloudConfig, err := ini.Load(filepath.Join(root, "config")) if err != nil { return "", errors.Wrap(err, "error decoding cloud config") } cloud := getSelectedCloudFromAzConfig(cloudConfig) return getCloudSubFromAzConfig(cloud, subConfig) } func getSelectedCloudFromAzConfig(f *ini.File) string { selectedCloud := "AzureCloud" if cloud, err := f.GetSection("cloud"); err == nil { if name, err := cloud.GetKey("name"); err == nil { if s := name.String(); s != "" { selectedCloud = s } } } return selectedCloud } func getCloudSubFromAzConfig(cloud string, f *ini.File) (string, error) { cfg, err := f.GetSection(cloud) if err != nil { return "", errors.New("could not find user defined subscription id") } sub, err := cfg.GetKey("subscription") if err != nil { return "", errors.Wrap(err, "error reading subscription id from cloud config") } return sub.String(), nil } func getAuthorizer() (autorest.Authorizer, error) { if os.Getenv("AZURE_AUTH_LOCATION") != "" { authorizer, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint) if err != nil { return nil, errors.Wrap(err, "error reading auth file") } return authorizer, nil } authorizer, err := auth.NewAuthorizerFromCLI() if err != nil { return nil, errors.Wrap(err, "could not get authorizer from azure CLI or environment") } return authorizer, nil }
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-25 09:49 * Description: *****************************************************************/ package rpcPoint import ( "errors" "github.com/go-xe2/x/container/xarray" "github.com/go-xe2/x/container/xpool" "github.com/go-xe2/x/os/xlog" "github.com/go-xe2/x/utils/xrand" "github.com/go-xe2/xthrift/regcenter" "time" ) // 访问服务客户端线程池 type tHostClientPool struct { server *TEndPointServer pool *xpool.TPool hosts []*regcenter.THostStoreToken readTimeout time.Duration writeTimeout time.Duration connectTimeout time.Duration ConnectFailRetry time.Duration keepAlive time.Duration // 心跳频率 heartbeat time.Duration // 允许丢失心跳的最大次数 heartbeatLoss int } func newHostClientPool(server *TEndPointServer, hosts []*regcenter.THostStoreToken, readTimeout, writeTimeout, connectTimeout, failReTry, keeyAlive, heartbeat time.Duration, hearbeatLoss int) *tHostClientPool { inst := &tHostClientPool{ hosts: hosts, server: server, readTimeout: readTimeout, writeTimeout: writeTimeout, connectTimeout: connectTimeout, ConnectFailRetry: failReTry, keepAlive: keeyAlive, heartbeat: heartbeat, heartbeatLoss: hearbeatLoss, } inst.pool = xpool.New(heartbeat, inst.poolNewFun, inst.poolExpireFun) return inst } func (p *tHostClientPool) poolNewFun() (interface{}, error) { tmpArr := xarray.New(true) tryItems := make([]*regcenter.THostStoreToken, 0) now := time.Now() for _, host := range p.hosts { if host.CanUse(now) { tmpArr.PushLeft(host) } else { tryItems = append(tryItems, host) } } idx := 0 if tmpArr.Len() == 0 { // 无可用资源时,尝试使用连接失败的服务 for _, h := range tryItems { tmpArr.PushLeft(h) } } if tmpArr.Len() > 1 { idx = xrand.N(0, tmpArr.Len()-1) } for { if tmpArr.Len() <= 0 { return nil, errors.New("没有可用服务") } cur := tmpArr.Get(idx).(*regcenter.THostStoreToken) c, err := p.newHostClient(cur) if err == nil && c.IsOpen() { cur.SetConnectSuccess() c.expire = time.Now().Add(p.keepAlive) return c, nil } // 失败的节点,2分钟后再重试使用链接 cur.SetConnectFail(time.Now().Add(p.ConnectFailRetry)) tmpArr.Remove(idx) idx = 0 if tmpArr.Len() > 1 { idx = xrand.N(0, tmpArr.Len()) } } } func (p *tHostClientPool) Get() *tInnerClient { v, err := p.pool.Get() if err != nil || v == nil { return nil } return v.(*tInnerClient) } func (p *tHostClientPool) Put(item *tInnerClient) { p.pool.Put(item) } func (p *tHostClientPool) newHostClient(host *regcenter.THostStoreToken) (*tInnerClient, error) { return newInnerClient(p, p.server.inProtoFac, host.Host, host.Port, p.writeTimeout, p.readTimeout, p.connectTimeout, p.heartbeatLoss) } func (p *tHostClientPool) poolExpireFun(item interface{}) { c := item.(*tInnerClient) if !c.IsOpen() { // 连接已经断开 return } now := time.Now() if now.After(c.expire) { // 连接空闲超时,关闭连接 xlog.Debug("连接空闲超时,断开链接") if err := c.Close(); err != nil { xlog.Error(err) } } else { // 放回线程池 // 心跳检查 if p.heartbeat > 0 { now := time.Now() if p.heartbeatLoss == 0 { p.heartbeatLoss = 3 } if now.After(c.lastAlive.Add(p.heartbeat)) { if p.heartbeatLoss > 0 && c.heartFailCount > p.heartbeatLoss { // 心跳丢失次数过多, 关闭当前链接 if err := c.Close(); err != nil { xlog.Error(err) } return } // 发送心跳 c.sendHeartbeat() } } // 放回线程池 p.Put(c) } }
package db_query_loan import ( "bankBigData/BankServerJournal/entity" "bankBigData/BankServerJournal/table" "gitee.com/johng/gf/g" ) // 系统里的所有用户 func QueryPageUserInfo_Pt(start, limit int) (g.List, error) { db := g.DB(table.PSDBName) sql := db.Table(table.PtCustomerInfo).Limit(start, limit) sql.OrderBy("id asc") r, err := sql.All() return r.ToList(), err } // 获取用户信息 func GetUserInfo(userId int) (entity.Customer_info, error) { db := g.DB(table.PSDBName) sql := db.Table(table.PtCustomerInfo).Where("id=?", userId) r, err := sql.One() data := entity.Customer_info{} _ = r.ToStruct(&data) return data, err } // 获取客户信息(业务经理填写) func GetUserInfo_buss(userId int) (entity.Customer_info, error) { db := g.DB(table.PSDBName) sql := db.Table(table.BussCustomerInfo).Where("customer_id=?", userId) r, err := sql.One() data := entity.Customer_info{} _ = r.ToStruct(&data) return data, err } // 获取用户创业信息 func GetUserInfoJob(userId int) (entity.Customer_info_job, error) { db := g.DB(table.PSDBName) sql := db.Table(table.PtCustomerInfoJob).Where("customer_id=?", userId) r, err := sql.One() data := entity.Customer_info_job{} _ = r.ToStruct(&data) return data, err } // 获取用户的创业信息(业务经理填写) func GetUserInfo_buss_job(userId int) (entity.Customer_info_job, error) { db := g.DB(table.PSDBName) sql := db.Table(table.BussCustomerInfoJob).Where("customer_id=?", userId) r, err := sql.One() data := entity.Customer_info_job{} _ = r.ToStruct(&data) return data, err } // 用户的评级授信 func GetPtCustomerInfoFiling(userId int) (entity.Pt_customer_info_filing, error) { db := g.DB(table.PSDBName) sql := db.Table(table.PtCustomerInfoFiling).Where("customer_id=?", userId) r, err := sql.One() data := entity.Pt_customer_info_filing{} _ = r.ToStruct(&data) return data, err } // 网点信息 func GetOrgDepartmentInfo(id int) (entity.Org_department_info, error) { db := g.DB(table.PSDBName) sql := db.Table(table.OrgDepartmentInfo).Where("id=?", id) r, err := sql.One() data := entity.Org_department_info{} _ = r.ToStruct(&data) return data, err }
package testdata import ( "github.com/frk/gosql" ) type SelectCountWithFilterQuery struct { Count int `rel:"test_user:u"` gosql.Filter }
package rhythm import ( "github.com/almerlucke/kallos" "github.com/almerlucke/kallos/generators/tools" ) // Bouncer represents a bouncing ball like rhythm // duration ramp represents the hit the ground duration, // pause ramp is the mid air duration // wait ramp is the time between a new throw type Bouncer struct { durRamp *tools.Ramp pauseRamp *tools.Ramp waitRamp *tools.Ramp pause bool reset bool } // NewBouncer creates a new bouncer func NewBouncer(durationRamp *tools.Ramp, pauseRamp *tools.Ramp, waitRamp *tools.Ramp) *Bouncer { return &Bouncer{ durRamp: durationRamp, pauseRamp: pauseRamp, waitRamp: waitRamp, } } // GenerateValue generate a value func (b *Bouncer) GenerateValue() kallos.Value { var k float64 var d bool if b.reset { b.pauseRamp.Reset() b.durRamp.Reset() b.pause = false b.reset = false k, d = b.waitRamp.Generate() if !d { b.waitRamp.Reset() } k = -k } else { if b.pause { k, d = b.pauseRamp.Generate() if d { b.pause = !b.pause } else { b.reset = true } k = -k } else { k, d = b.durRamp.Generate() if d { b.pause = !b.pause } else { b.reset = true } } } return kallos.Value{k} } // IsContinuous is true func (b *Bouncer) IsContinuous() bool { return true } // Done is false func (b *Bouncer) Done() bool { return false } // Reset is empty func (b *Bouncer) Reset() { }
package repository import "github.com/costap/healthcheckapp/model" type ServiceInfoRepository struct { services map[string]model.ServiceInfo } func NewServiceInfoRepository() *ServiceInfoRepository { return &ServiceInfoRepository{services: make(map[string]model.ServiceInfo)} } func (r *ServiceInfoRepository) Save(si model.ServiceInfo) { r.services[si.Name] = si } func (r *ServiceInfoRepository) List() []model.ServiceInfo { l := make([]model.ServiceInfo, 0) for _, v := range r.services { l = append(l, v) } return l }
// Package cmn provides common constants, types, and utilities for AIS clients // and AIStore. /* * Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. */ package cmn // used in multi-object (list|range) operations type ( // List of object names, or // Prefix, Regex, and Range for a Range Operation ListRangeMsg struct { ObjNames []string `json:"objnames"` Template string `json:"template"` } // ArchiveMsg contains parameters for archiving source objects as one of the supported // archive cos.ArchExtensions types at the destination ArchiveMsg struct { ListRangeMsg ToBck Bck `json:"tobck"` ArchName string `json:"archname"` // must have one of the cos.ArchExtensions Mime string `json:"mime"` // user-specified mime type takes precedence if defined } ) // NOTE: empty ListRangeMsg{} corresponds to (range = entire bucket) func (lrm *ListRangeMsg) IsList() bool { return len(lrm.ObjNames) > 0 } func (lrm *ListRangeMsg) HasTemplate() bool { return lrm.Template != "" }
package balaur import ( "fmt" "github.com/fatih/color" "github.com/golang/glog" "github.com/zenazn/goji/web" ) var neededConfigs = []string{"app", "route", "middleware"} func NewApp(dir string, configs map[string]string, rr RouteRegistrar, mr MiddlewareRegistrar) *App { app := &App{ appConfig: map[string]Config{}, Controllers: map[string]interface{}{}, Middlewares: map[string]interface{}{}, Mux: web.New(), AppRouteRegistrar: rr, AppMiddlewareRegistrar: mr, } if rr == nil { app.AppRouteRegistrar = NewBasicRouteRegistrar() } if mr == nil { app.AppMiddlewareRegistrar = NewBasicMiddlewareRegistrar() } // load all given configs checkNeededConfigs(configs) for k, p := range configs { app.appConfig[k] = NewConfig(fmt.Sprintf("%s/%s", dir, p)) } app.Name = app.Config("app").Get("name", false) return app } func checkNeededConfigs(configs map[string]string) { for _, k := range neededConfigs { _, ok := configs[k] if !ok { glog.Fatalf("Please set config for %s", k) } } } type App struct { Name string Priority int Controllers map[string]interface{} Middlewares map[string]interface{} ControllerMethodWrapper func(method ControllerMethod) web.HandlerFunc Mux *web.Mux AppRouteRegistrar RouteRegistrar AppMiddlewareRegistrar MiddlewareRegistrar appConfig map[string]Config } func (a *App) Boot() { color.Green("Booting app %s(priority %d)\n", a.Name, a.Priority) a.registerRoutes() a.registerMiddlewares() AddApp(a) } func (a *App) Config(section string) Config { conf, ok := a.appConfig[section] if !ok { glog.Fatalf("Config (%s) is not set", section) } return conf } func (a *App) registerRoutes() { conf := a.Config("route") a.AppRouteRegistrar.RegisterRoutes(a.Mux, conf.GetChildren("route", false), a.Controllers) } func (a *App) registerMiddlewares() { conf := a.Config("middleware") a.AppMiddlewareRegistrar.RegisterMiddlewares(a.Mux, conf.GetChildren("middleware", false), a.Middlewares) }
package pie import ( "fmt" "time" ) type Tag struct { Name string `json:"name"` NumPosts int `json:"num_posts"` LastActivity time.Time `json:"last_activity"` } func buildAllTagsRequest(token string) *request{ return &request{ Url: "/tags", Token: token, } } func buildOwnTagsRequest(user_id int, token string) *request{ return &request{ Url: fmt.Sprintf("/users/%d/tags", user_id), Token: token, } } // Returns all tags for the current user. func GetAllTags(token string) (tags []*Tag, err error) { tags = []*Tag{} err = buildAllTagsRequest(token).doGet(&tags) return } // Returns all tags for the current user. Returns raw response. func GetRawAllTags(token string) (res string, err error) { res, err = buildAllTagsRequest(token).doGetRaw() return } // Returns all tags for the current user. func GetOwnTags(user_id int, token string) (tags []*Tag, err error) { tags = []*Tag{} err = buildOwnTagsRequest(user_id, token).doGet(&tags) return } // Returns all tags for the current user. Returns raw response. func GetRawOwnTags(user_id int, token string) (res string, err error) { res, err = buildOwnTagsRequest(user_id, token).doGetRaw() return }
package main import ( "context" "log" "time" pb "github.com/thanhftu/go-client/ecommerce" "google.golang.org/grpc" ) const ( address = "localhost:50051" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connected %v", err) } defer conn.Close() c := pb.NewProductInfoClient(conn) name := "Apple 11" price := float32(1000) description := "Meet Apple 11" ctx, canncel := context.WithTimeout(context.Background(), time.Second) defer canncel() r, err := c.AddProduct(ctx, &pb.Product{ Name: name, Description: description, Price: price, }) if err != nil { log.Fatalf("Could not add product %v", err) } log.Printf("Product ID: %s added successfully", r.Value) product, err := c.GetProduct(ctx, &pb.ProductID{Value: r.Value}) if err != nil { log.Fatalf("Could not get product: %v", err) } log.Printf("Product: %s ", product.String()) }
package middleware import ( "fmt" "github.com/gin-gonic/gin" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" "github.com/uber/jaeger-client-go" "github.com/uber/jaeger-client-go/config" "io" ) func initTraceConfig() (opentracing.Tracer, io.Closer) { cfg:= &config.Configuration{ ServiceName: "hello trace", Sampler: &config.SamplerConfig{ Type: jaeger.SamplerTypeConst, Param: 1, }, Reporter: &config.ReporterConfig{ LogSpans: true, LocalAgentHostPort: "127.0.0.1:6831", }, } tracer, closer, err := cfg.NewTracer(config.Logger(jaeger.StdLogger)) if err != nil { panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err)) } opentracing.SetGlobalTracer(tracer) return tracer, closer } func SetupTrace()gin.HandlerFunc{ return func(c *gin.Context){ var parentSpan opentracing.Span tracer, closer := initTraceConfig() defer closer.Close() carrier := opentracing.HTTPHeadersCarrier(c.Request.Header) spCtx, err := tracer.Extract(opentracing.HTTPHeaders, carrier) if err != nil { parentSpan = tracer.StartSpan(c.Request.URL.Path) defer parentSpan.Finish() } else { parentSpan = opentracing.StartSpan( c.Request.URL.Path, opentracing.ChildOf(spCtx), opentracing.Tag{Key: string(ext.Component), Value: "HTTP"}, ext.SpanKindRPCServer, ) defer parentSpan.Finish() } c.Set("Tracer", tracer) c.Set("ParentSpanContext", parentSpan.Context()) c.Next() } }
package tax import ( "fmt" "strings" "github.com/Knetic/govaluate" taxmodel "github.com/syariatifaris/shopeetax/app/model/tax" ) //CalculateTax calculates tax based on product input and its rule func CalculateTax(input *TaxableProductInput, taxes map[int64]*taxmodel.Tax) (*taxmodel.TaxableProduct, error) { rule, ok := taxes[input.TaxCategoryID] if !ok { return nil, fmt.Errorf("unable to find tax with category id %d", input.TaxCategoryID) } taxProduct := &taxmodel.TaxableProduct{ Price: input.InitialPrice, TaxCategoryID: input.TaxCategoryID, ProductName: input.ProductName, } if input.InitialPrice <= rule.MinPrice { taxProduct.TaxPrice = 0 } else { replacer := strings.NewReplacer( "${", "", "}", "", ) rule.Expression = replacer.Replace(rule.Expression) expression, err := govaluate.NewEvaluableExpression(rule.Expression) if err != nil { return nil, err } parameters := make(map[string]interface{}, 1) parameters["price"] = input.InitialPrice result, err := expression.Evaluate(parameters) if err != nil { return nil, err } taxProduct.TaxPrice = result.(float64) } taxProduct.TotalPrice = taxProduct.Price + taxProduct.TaxPrice return taxProduct, nil } //CalculateProductSummary calculates taxable product summary func CalculateProductSummary(products []*taxmodel.TaxableProduct) *TaxableProductSummary { var totalAmt, totalTaxAmt, grandTotal float64 for _, product := range products { totalAmt += product.Price totalTaxAmt += product.TaxPrice } grandTotal = totalAmt + totalTaxAmt return &TaxableProductSummary{ GrandTotal: grandTotal, TotalAmount: totalAmt, TotalTaxAmount: totalTaxAmt, } } //GetTaxCategoryCode gets tax category code func GetTaxCategoryCode(id int64, taxes map[int64]*taxmodel.Tax) (string, error) { tax, ok := taxes[id] if !ok { return "", fmt.Errorf("unable to get tax code for id %d", id) } return tax.Code, nil }
package main import ( "flag" "github.com/BurntSushi/toml" "log" "simple_websocket/internal/chat" ) var configPath string func init() { flag.StringVar(&configPath, "path", "configs/conf.toml", "provide path to config file") } func main() { flag.Parse() config := chat.NewConfig() _, err := toml.DecodeFile(configPath, config) if err != nil { log.Println("Не найден файл конфигурации. Будут использованы настройки по умолчанию") } server := chat.New(config) log.Fatal(server.Start()) }
package main import ( "testing" ) func TestOpenAndCloseQueue(t *testing.T) { q := OpenQueue() q.Close() } func TestCreateTask(t *testing.T) { q := OpenQueue() q.NewTask(0, "") q.Close() } func ReadTask(t *testing.T) { q := OpenQueue() task := q.NewTask(0, "") q.readTask(task.ID) q.Close() }
package configuration import ( "encoding/json" "flag" "fmt" "os" ) type Config struct { Host string `json:"Host,required"` Port uint `json:"Port,required"` Database string `json:"Database,required"` DBHost string `json:"DBHost,required"` DBPort uint `json:"DBPort,required"` User string `json:"User,required"` Password string `json:"Password,required"` } func Usage() { } func ReadCmd(args []string) (*Config, error) { fileCommand := flag.NewFlagSet("file", flag.ExitOnError) cmdCommand := flag.NewFlagSet("cmd", flag.ExitOnError) fileTextPtr := fileCommand.String("from", "", "Path for configuration file.") cmdHostPtr := cmdCommand.String("host", "", "Hostname") cmdPortPtr := cmdCommand.Uint("port", 0, "Port") cmdDBPtr := cmdCommand.String("dbname", "", "Database name") cmdDBHost := cmdCommand.String("dbhost", "127.0.0.1", "Database hostname") cmdDBPort := cmdCommand.Uint("dbport", 5432, "Database port") cmdUserPtr := cmdCommand.String("user", "", "Username") cmdPassPtr := cmdCommand.String("pass", "", "Password") if len(args) < 2 { return &Config{ Host: "127.0.0.1", Port: 5432, Database: "movie_rental", DBHost: "127.0.0.1", DBPort: 5432, User: "postgres", Password: "postgres", }, nil } switch args[1] { case "file": fileCommand.Parse(args[2:]) case "cmd": cmdCommand.Parse(args[2:]) default: flag.PrintDefaults() os.Exit(1) } if fileCommand.Parsed() { if fileTextPtr == nil { fileCommand.PrintDefaults() os.Exit(1) } return ReadConfig(*fileTextPtr) } if cmdCommand.Parsed() { if cmdHostPtr != nil && cmdPortPtr != nil && cmdDBPtr != nil && cmdUserPtr != nil && cmdPassPtr != nil { return &Config{ Host: *cmdHostPtr, Port: *cmdPortPtr, Database: *cmdDBPtr, DBHost: *cmdDBHost, DBPort: *cmdDBPort, User: *cmdUserPtr, Password: *cmdPassPtr, }, nil } } //flag.PrintDefaults() return nil, fmt.Errorf("Read usage!") } func ReadConfig(path string) (*Config, error) { file, err := os.Open(path) if err != nil { return nil, err } config := Config{} decoder := json.NewDecoder(file) err = decoder.Decode(&config) if err != nil { return nil, err } return &config, nil }
package game import ( "math" "math/rand" "github.com/grahamjenson/asteroids/vector2d" ) /// // Asteroid /// type Asteroid struct { template *vector2d.Polygon Projection *vector2d.Polygon x, y float64 velocityX, velocityY, rotationD, rotation float64 width, height int scale float64 } func (s *Asteroid) XY() (float64, float64) { return s.x, s.y } func (s *Asteroid) Init(width, height int, scale float64) { s.width = width s.height = height s.scale = scale xOffset := rand.Intn(500) yOffset := rand.Intn(500) if rand.Intn(2) == 0 { s.x = float64(width - xOffset) } else { s.x = float64(xOffset) } if rand.Intn(2) == 0 { s.y = float64(height - yOffset) } else { s.y = float64(yOffset) } initSpeed := 150 s.velocityX = float64(rand.Intn(initSpeed*2) - (initSpeed)) s.velocityY = float64(rand.Intn(initSpeed*2) - (initSpeed)) s.rotationD = rand.Float64() * (math.Pi / 2) s.template = vector2d.NewPolygon( 40, -40, 120, -20, 120, 40, 80, 80, 20, 80, -40, 100, -80, 60, -60, 00, -20, -40, ) s.template.Scale(scale, scale) s.Projection = s.template.Clone() } func (s *Asteroid) Update(dt float64, pressedButtons map[int]bool) { s.x += s.velocityX * dt s.y += s.velocityY * dt s.rotation += s.rotationD * dt // BOUNDS // We limit rotation to tau s.rotation = math.Mod(s.rotation, (2 * math.Pi)) s.x, s.y = WrapXY(s.x, s.y, s.width, s.height) // update Projection s.Projection = s.template.Clone().Translate(s.x, s.y).Rotate(s.rotation) }
package client import ( "crypto/rand" "encoding/base64" "fmt" "log" "net/http" "os" "strings" "golang.org/x/oauth2" ) const ( cKeyState = "staffio_state" cKeyToken = "staffio_token" cKeyUser = "staffio_user" ) var ( conf *oauth2.Config oAuth2Endpoint oauth2.Endpoint infoUrl string ) func init() { prefix := envOr("STAFFIO_PREFIX", "https://staffio.work") oAuth2Endpoint = oauth2.Endpoint{ AuthURL: fmt.Sprintf("%s/%s", prefix, "authorize"), TokenURL: fmt.Sprintf("%s/%s", prefix, "token"), } clientID := envOr("STAFFIO_CLIENT_ID", "") clientSecret := envOr("STAFFIO_CLIENT_SECRET", "") if clientID == "" || clientSecret == "" { log.Print("Warning: STAFFIO_CLIENT_ID or STAFFIO_CLIENT_SECRET not found in environment") } infoUrl = fmt.Sprintf("%s/%s", prefix, "info/me") redirectURL := envOr("STAFFIO_REDIRECT_URL", "") scopes := strings.Split(envOr("STAFFIO_SCOPES", ""), ",") if clientID != "" && clientSecret != "" { Setup(redirectURL, clientID, clientSecret, scopes) } } func randToken() string { b := make([]byte, 12) rand.Read(b) return base64.URLEncoding.EncodeToString(b) } func GetOAuth2Config() *oauth2.Config { return conf } // Setup oauth2 config func Setup(redirectURL, clientID, clientSecret string, scopes []string) { conf = &oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL, Scopes: scopes, Endpoint: oAuth2Endpoint, } } func LoginHandler(w http.ResponseWriter, r *http.Request) { fakeUser := &User{Name: randToken()} fakeUser.Refresh() state, _ := fakeUser.Encode() http.SetCookie(w, &http.Cookie{ Name: cKeyState, Value: state, Path: "/", HttpOnly: true, }) // g6F1oKFu2SxkalR3cms5dkIxSW1KcmppWUFxOThnNUlBS0lFNE5EV1VpUkgzMVdxc1VBPaFo0luyTHg // g6F1oKFusDZVa0J6MDNVLTZ1Q2lKN1ShaNJbsldv sess := SessionLoad(r) sess.Set(cKeyState, state) SessionSave(sess, w) location := GetAuthCodeURL(state) w.Header().Set("refresh", fmt.Sprintf("1; %s", location)) w.Write([]byte("<html><title>Staffio</title> <body style='padding: 2em;'> <p>Waiting...</p> <a href='" + location + "'><button style='font-size: 14px;'> Login with Staffio! </button></a></body></html>")) } func GetAuthCodeURL(state string) string { return conf.AuthCodeURL(state) } func envOr(key, dft string) string { v := os.Getenv(key) if v == "" { return dft } return v }
// // Copyright 2020 The AVFS authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package test import ( "math/rand" "strconv" "testing" "github.com/avfs/avfs" ) func (sfs *SuiteFS) BenchAll(b *testing.B) { sfs.RunBenchs(b, UsrTest, sfs.BenchCreate) sfs.RunBenchs(b, UsrTest, sfs.BenchMkdir) } // BenchMkdir benchmarks Mkdir function. func (sfs *SuiteFS) BenchMkdir(b *testing.B, testDir string) { vfs := sfs.vfsTest b.Run("Mkdir", func(b *testing.B) { dirs := make([]string, 0, b.N) dirs = append(dirs, testDir) for n := 0; n < b.N; n++ { nbDirs := int32(len(dirs)) parent := dirs[rand.Int31n(nbDirs)] //nolint:gosec // No security-sensitive function. path := vfs.Join(parent, strconv.FormatUint(rand.Uint64(), 10)) //nolint:gosec // No security-sensitive function. dirs = append(dirs, path) } b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { _ = vfs.Mkdir(dirs[n], avfs.DefaultDirPerm) } }) } // BenchCreate benchmarks Create function. func (sfs *SuiteFS) BenchCreate(b *testing.B, testDir string) { vfs := sfs.vfsTest b.Run("Create", func(b *testing.B) { files := make([]string, 0, b.N) for n := 0; n < b.N; n++ { path := vfs.Join(testDir, strconv.FormatInt(int64(n), 10)) files = append(files, path) } b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { fileName := files[n] f, err := vfs.Create(fileName) if err != nil { b.Fatalf("Create %s, want error to be nil, got %v", fileName, err) } err = f.Close() if err != nil { b.Fatalf("Close %s, want error to be nil, got %v", fileName, err) } } }) }
package main import ( "encoding/json" "flag" "fmt" "io" "log" "os" "path/filepath" "github.com/mcandre/stank" ) var flagPrettyPrint = flag.Bool("pp", false, "Prettyprint smell records") var flagEOL = flag.Bool("eol", false, "Report presence/absence of final end of line sequence") var flagCR = flag.Bool("cr", false, "Report presence/absence of any CR/CRLF's") var flagHelp = flag.Bool("help", false, "Show usage information") var flagVersion = flag.Bool("version", false, "Show version information") // Stinker holds configuration for a stinky walk. type Stinker struct { EOLCheck bool CRCheck bool PrettyPrint bool } // Walk sniffs a path, // printing the smell of the script. // // If PrettyPrint is false, then the smell is minified. func (o Stinker) Walk(pth string, info os.FileInfo, err error) error { smell, err := stank.Sniff(pth, stank.SniffConfig{EOLCheck: o.EOLCheck, CRCheck: o.CRCheck}) if err != nil && err != io.EOF { log.Print(err) return err } if smell.Directory { return nil } var smellBytes []byte if o.PrettyPrint { smellBytes, _ = json.MarshalIndent(smell, "", " ") } else { smellBytes, _ = json.Marshal(smell) } smellJSON := string(smellBytes) fmt.Println(smellJSON) return err } func main() { flag.Parse() stinker := Stinker{} if *flagPrettyPrint { stinker.PrettyPrint = true } if *flagEOL { stinker.EOLCheck = true } if *flagCR { stinker.CRCheck = true } switch { case *flagVersion: fmt.Println(stank.Version) os.Exit(0) case *flagHelp: flag.PrintDefaults() os.Exit(0) } paths := flag.Args() var err error for _, pth := range paths { err = filepath.Walk(pth, stinker.Walk) if err != nil && err != io.EOF { log.Print(err) } } }
type LRUCache struct { Capacity int Size int Pairs map[int]*Node Head *Node Tail *Node } type Node struct{ Val int Key int Pre *Node Next *Node } func Constructor(capacity int) LRUCache { head:= &Node{} tail:=&Node{Pre:head} head.Next = tail return LRUCache{ Capacity: capacity, Pairs: make(map[int]*Node), Size:0, Head: head, Tail: tail, } } func (this *LRUCache) moveToHead(n *Node){ if this.Head.Next != n{ next := n.Next pre := n.Pre pre.Next = next next.Pre = pre n.Pre = this.Head n.Next = this.Head.Next this.Head.Next.Pre = n this.Head.Next = n } } func (this *LRUCache) addToHead(n *Node){ n.Pre = this.Head n.Next = this.Head.Next this.Head.Next.Pre=n this.Head.Next = n } func (this *LRUCache) removeTail(){ delete(this.Pairs, this.Tail.Pre.Key) nt:=this.Tail.Pre.Pre this.Tail.Pre = nt nt.Next=this.Tail } func (this *LRUCache) Get(key int) int { node:=this.Pairs[key] if node!=nil{ this.moveToHead(node) return node.Val } return -1 } func (this *LRUCache) Put(key int, value int) { if n,ok:=this.Pairs[key];ok{ n.Val=value this.moveToHead(n) return } node:=&Node{Val:value,Key:key} if this.Size==this.Capacity{ this.removeTail() }else{ this.Size++ } this.addToHead(node) this.Pairs[key]=node } /** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */
package main import ( "bufio" "fmt" "encoding/hex" "github.com/lt/go-cryptopals/cryptopals" "os" ) func main() { if len(os.Args) < 2 { fmt.Println("Usage: go run challenge4.go <path to 4.txt>") os.Exit(1) } file, err := os.Open(os.Args[1]) if err != nil { fmt.Println(err) os.Exit(1) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { for i := 0; i < 256; i++ { trial, err := hex.DecodeString(scanner.Text()) if err != nil { fmt.Println(err) os.Exit(1) } trial = cryptopals.XorByte(trial, byte(i)) score := cryptopals.ScoreEnglish(trial) if score > 3 { fmt.Println(string(trial)) } } } if err := scanner.Err(); err != nil { fmt.Println(err) os.Exit(1) } }
package waktu // fmtInt formats v into the tail of buf. // It returns the index where the output begins. func fmtInt(buf []byte, v uint64) int { w := len(buf) if v == 0 { w-- buf[w] = '0' } else { for v > 0 { w-- const ten = 10 buf[w] = byte(v%ten) + '0' v /= 10 } } return w }
package config import ( "os" "time" "github.com/garyburd/redigo/redis" "github.com/iris-contrib/logger" "github.com/iris-contrib/middleware/cors" "github.com/iris-contrib/middleware/i18n" "github.com/iris-contrib/middleware/recovery" "github.com/kataras/iris" "gopkg.in/pg.v4" mLogger "github.com/iris-contrib/middleware/logger" ) type Database struct { Enabled bool Driver string ConnString string Addr string Name string User string Pass string SSL bool Pool int } type Redis struct { Enabled bool Addr string Pass string } type Web struct { Addr string RootDir string PublicDir string JwtSecret string } // Config Server Configuration type Config struct { Debug bool Database Database Redis Redis Web Web } func Default() Config { return Config{ Debug: true, Database: DefaultDatabase(), Redis: DefaultRedis(), Web: DefaultWeb(), } } func DefaultDatabase() Database { return Database{ Enabled: true, Driver: "postgres", Addr: "127.0.0.1", Name: "starter", User: "postgres", Pass: "123123123", SSL: false, Pool: 16, } } func DefaultRedis() Redis { return Redis{ Enabled: true, Addr: "127.0.0.1:6397", Pass: "123123123", } } func DefaultWeb() Web { return Web{ Addr: "0.0.0.0:8822", RootDir: ".", PublicDir: "./public", JwtSecret: "aasdgwsgevwsfsetw", } } //ConfigureDatabase setup db connection func ConfigureDatabase(cfg *Config) *pg.DB { if !cfg.Database.Enabled { return nil } db := pg.Connect(&pg.Options{ Addr: cfg.Database.Addr, Database: cfg.Database.Name, User: cfg.Database.User, Password: cfg.Database.Pass, PoolSize: cfg.Database.Pool, }) iris.UseFunc(func(c *iris.Context) { c.Set("db", db) c.Next() }) return db } //ConfigureRedis setup redis connection func ConfigureRedis(cfg *Config) *redis.Pool { if !cfg.Redis.Enabled { return nil } rds := &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", cfg.Redis.Addr) if err != nil { return nil, err } if _, err := c.Do("AUTH", cfg.Redis.Pass); err != nil { c.Close() return nil, err } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } iris.UseFunc(func(c *iris.Context) { c.Set("rds", rds) c.Next() }) return rds } //ConfigureIris setup iris opts func ConfigureIris(cfg *Config) { // set the template engine iris.Config.Render.Template.Engine = iris.DefaultEngine // or iris.DefaultEngine iris.Config.Render.Template.Layout = cfg.Web.RootDir + "/layouts/layout.html" // = ./templates/layouts/layout.html iris.Use(recovery.New(os.Stderr)) // optional iris.Use(i18n.New(i18n.Config{Default: "en-US", Languages: map[string]string{ "en-US": cfg.Web.RootDir + "/locales/locale_en-US.ini", "zh-CN": cfg.Web.RootDir + "/locales/locale_zh-CN.ini"}})) // register cors middleware iris.Use(cors.New(cors.Options{})) // iris.UseTemplate(html.New(html.Config{Layout: "layout.html"})).Directory("./templates", ".html") // set the favicon iris.Favicon(cfg.Web.PublicDir + "/images/favicon.ico") // set static folder(s) iris.Static("/public", cfg.Web.PublicDir, 1) // logCfg := logger.Config{ // EnableColors: false, //enable it to enable colors for all, disable colors by iris.Logger.ResetColors(), defaults to false // // Status displays status code // Status: true, // // IP displays request's remote address // IP: true, // // Method displays the http method // Method: true, // // Path displays the request path // Path: true, // } // set the global middlewares iris.Use(mLogger.New(logger.New(logger.DefaultConfig()))) // set the custom errors iris.OnError(iris.StatusNotFound, func(ctx *iris.Context) { ctx.Render("errors/404.html", iris.Map{"Title": iris.StatusText(iris.StatusNotFound)}) }) iris.OnError(iris.StatusInternalServerError, func(ctx *iris.Context) { ctx.Render("errors/500.html", nil) }) iris.UseFunc(func(c *iris.Context) { c.Set("cfg", cfg) c.Next() }) }
// Copyright 2021 Google LLC // // 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 unit import ( "encoding/json" "fmt" "strconv" "testing" "github.com/GoogleCloudPlatform/anthos-samples/anthos-bm-gcp-terraform/util" "github.com/GoogleCloudPlatform/anthos-samples/anthos-bm-gcp-terraform/validation" "github.com/gruntwork-io/terratest/modules/gcp" "github.com/gruntwork-io/terratest/modules/terraform" testStructure "github.com/gruntwork-io/terratest/modules/test-structure" "github.com/icrowley/fake" ) func TestUnit_LoadbalancerModule_ControlPlane(goTester *testing.T) { goTester.Parallel() moduleDir := testStructure.CopyTerraformFolderToTemp(goTester, "../../", "modules/loadbalancer") projectID := gcp.GetGoogleProjectIDFromEnvVar(goTester) // from GOOGLE_CLOUD_PROJECT region := "test_region" zone := "test_zone" loadbalancerType := "controlplanelb" namePrefix := "cp-loadbalancer" externalIPName := "cp-lb-externalip" network := "default" healthCheckPath := "/health_check" healthCheckPort := util.GetRandomPort() backendProtocol := "TCP" randomVMHostNameOne := gcp.RandomValidGcpName() randomVMHostNameTwo := gcp.RandomValidGcpName() randomVMHostNameThree := gcp.RandomValidGcpName() randomVMIpNumOne := fake.IPv4() randomVMIpNumTwo := fake.IPv4() randomVMIpNumThree := fake.IPv4() randomVMPortNumOne := strconv.Itoa(util.GetRandomPort()) randomVMPortNumTwo := strconv.Itoa(util.GetRandomPort()) randomVMPortNumThree := strconv.Itoa(util.GetRandomPort()) expectedVMHostNames := []string{ randomVMHostNameOne, randomVMHostNameTwo, randomVMHostNameThree} expectedVMIps := []string{ randomVMIpNumOne, randomVMIpNumTwo, randomVMIpNumThree} expectedVMPorts := []string{ randomVMPortNumOne, randomVMPortNumTwo, randomVMPortNumThree} lbEndpointInstances := []interface{}{ map[string]string{ "name": randomVMHostNameOne, "ip": randomVMIpNumOne, "port": randomVMPortNumOne, }, map[string]string{ "name": randomVMHostNameTwo, "ip": randomVMIpNumTwo, "port": randomVMPortNumTwo, }, map[string]string{ "name": randomVMHostNameThree, "ip": randomVMIpNumThree, "port": randomVMPortNumThree, }, } forwardingRulePorts := []int{ util.GetRandomPort(), util.GetRandomPort(), util.GetRandomPort(), } // Variables to pass to our Terraform code using -var options tfVarsMap := map[string]interface{}{ "type": loadbalancerType, "project": projectID, "region": region, "zone": zone, "name_prefix": namePrefix, "ip_name": externalIPName, "network": network, "lb_endpoint_instances": lbEndpointInstances, "health_check_path": healthCheckPath, "health_check_port": healthCheckPort, "backend_protocol": backendProtocol, "forwarding_rule_ports": forwardingRulePorts, } testContainer := map[string]interface{}{ "vmNames": expectedVMHostNames, "vmIps": expectedVMIps, "vmPorts": expectedVMPorts, } tfPlanOutput := "terraform_test.tfplan" tfPlanOutputArg := fmt.Sprintf("-out=%s", tfPlanOutput) tfOptions := terraform.WithDefaultRetryableErrors(goTester, &terraform.Options{ TerraformDir: moduleDir, Vars: tfVarsMap, PlanFilePath: tfPlanOutput, }) // Terraform init and plan only terraform.Init(goTester, tfOptions) terraform.RunTerraformCommand( goTester, tfOptions, terraform.FormatArgs(tfOptions, "plan", tfPlanOutputArg)..., ) tfPlanJSON, err := terraform.ShowE(goTester, tfOptions) util.LogError(err, fmt.Sprintf("Failed to parse the plan file %s into JSON format", tfPlanOutput)) var loadBalancerPlan util.LoadBalancerPlan err = json.Unmarshal([]byte(tfPlanJSON), &loadBalancerPlan) util.LogError(err, "Failed to parse the JSON plan into the LoadBalancerPlan struct in unit/module_loadbalancer.go") /** * Pro tip: * Write the json to a file using the util.WriteToFile() method to easily debug * util.WriteToFile(tfPlanJSON, "../../plan.json") */ validation.ValidateLoadBalancerVariables(goTester, &loadBalancerPlan) validation.ValidateLoadBalancerVariableValues(goTester, &loadBalancerPlan, &tfVarsMap, &testContainer) moduleResources := map[string]string{ "google_compute_backend_service": "lb-backend", "google_compute_global_forwarding_rule": "lb-forwarding-rule", "google_compute_health_check": "lb-health-check", "google_compute_network_endpoint": "lb-network-endpoint", "google_compute_network_endpoint_group": "lb-neg", "google_compute_target_tcp_proxy": "lb-target-tcp-proxy[0]", } validation.ValidateLoadBalancerPlanConfigurations(goTester, &loadBalancerPlan, &moduleResources, len(lbEndpointInstances)) } func TestUnit_LoadbalancerModule_Ingress(goTester *testing.T) { goTester.Parallel() moduleDir := testStructure.CopyTerraformFolderToTemp(goTester, "../../", "modules/loadbalancer") projectID := gcp.GetGoogleProjectIDFromEnvVar(goTester) // from GOOGLE_CLOUD_PROJECT region := "test_region" zone := "test_zone" loadbalancerType := "ingresslb" namePrefix := "cp-loadbalancer" externalIPName := "cp-lb-externalip" network := "default" healthCheckPath := "/health_check" healthCheckPort := util.GetRandomPort() backendProtocol := "HTTP" randomVMHostNameOne := gcp.RandomValidGcpName() randomVMHostNameTwo := gcp.RandomValidGcpName() randomVMHostNameThree := gcp.RandomValidGcpName() randomVMIpNumOne := fake.IPv4() randomVMIpNumTwo := fake.IPv4() randomVMIpNumThree := fake.IPv4() randomVMPortNumOne := strconv.Itoa(util.GetRandomPort()) randomVMPortNumTwo := strconv.Itoa(util.GetRandomPort()) randomVMPortNumThree := strconv.Itoa(util.GetRandomPort()) lbEndpointInstances := []interface{}{ map[string]string{ "name": randomVMHostNameOne, "ip": randomVMIpNumOne, "port": randomVMPortNumOne, }, map[string]string{ "name": randomVMHostNameTwo, "ip": randomVMIpNumTwo, "port": randomVMPortNumTwo, }, map[string]string{ "name": randomVMHostNameThree, "ip": randomVMIpNumThree, "port": randomVMPortNumThree, }, } forwardingRulePorts := []int{ util.GetRandomPort(), util.GetRandomPort(), util.GetRandomPort(), } // Variables to pass to our Terraform code using -var options tfVarsMap := map[string]interface{}{ "type": loadbalancerType, "project": projectID, "region": region, "zone": zone, "name_prefix": namePrefix, "ip_name": externalIPName, "network": network, "lb_endpoint_instances": lbEndpointInstances, "health_check_path": healthCheckPath, "health_check_port": healthCheckPort, "backend_protocol": backendProtocol, "forwarding_rule_ports": forwardingRulePorts, } tfPlanOutput := "terraform_test.tfplan" tfPlanOutputArg := fmt.Sprintf("-out=%s", tfPlanOutput) tfOptions := terraform.WithDefaultRetryableErrors(goTester, &terraform.Options{ TerraformDir: moduleDir, Vars: tfVarsMap, PlanFilePath: tfPlanOutput, }) // Terraform init and plan only terraform.Init(goTester, tfOptions) terraform.RunTerraformCommand( goTester, tfOptions, terraform.FormatArgs(tfOptions, "plan", tfPlanOutputArg)..., ) tfPlanJSON, err := terraform.ShowE(goTester, tfOptions) util.LogError(err, fmt.Sprintf("Failed to parse the plan file %s into JSON format", tfPlanOutput)) var loadBalancerPlan util.LoadBalancerPlan err = json.Unmarshal([]byte(tfPlanJSON), &loadBalancerPlan) util.LogError(err, "Failed to parse the JSON plan into the LoadBalancerPlan struct in unit/module_loadbalancer.go") /** * Pro tip: * Write the json to a file using the util.WriteToFile() method to easily debug * util.WriteToFile(tfPlanJSON, "../../plan.json") */ moduleResources := map[string]string{ "google_compute_backend_service": "lb-backend", "google_compute_global_forwarding_rule": "lb-forwarding-rule", "google_compute_health_check": "lb-health-check", "google_compute_network_endpoint": "lb-network-endpoint", "google_compute_network_endpoint_group": "lb-neg", "google_compute_target_http_proxy": "lb-target-http-proxy[0]", "google_compute_url_map": "ingress-lb-urlmap[0]", } validation.ValidateLoadBalancerPlanConfigurations(goTester, &loadBalancerPlan, &moduleResources, len(lbEndpointInstances)) }
package main import "testing" /** * author: will fan * created: 2020/1/13 21:04 * description: */ func TestNames(t *testing.T) { name := getName() if name != "Hello" { t.Error("Response from getName is unexpected value") } }
package shuffle import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) type KCO struct { C_array []ECPoint c0 ECPoint e *big.Int z_array []*big.Int s *big.Int } func ComMul(com Common, x_array []*big.Int, r0 *big.Int) ECPoint { res := com.g2.Mult(r0) for i:=0;i<len(x_array);i++{ res = res.Add(com.g1.Mult(x_array[i])) } return res } // argument of knowledge of commitment openings // <linear algebra with Sub-linear Zero-Knowledge Arguments> 2009 A func KCO_proof(com Common, x_array []*big.Int, r_array []*big.Int) KCO { C_array := []ECPoint{} m := len(x_array) for i:=0;i<m;i++{ C_array = append(C_array, Com(com, x_array[i], r_array[i])) } r0, err := rand.Int(rand.Reader, EC.N) check(err) // x0 is array in the article x0, err := rand.Int(rand.Reader, EC.N) check(err) c0 := Com(com, x0, r0) x1_array := []*big.Int{x0} x1_array = append(x1_array,x_array...) r1_array := []*big.Int{r0} r1_array = append(r1_array,r_array...) c_array := []ECPoint{c0} c_array = append(c_array,C_array...) //TODO: e should be modified GHString := com.g1.X.String()+com.g1.Y.String()+com.g2.X.String()+com.g2.Y.String() var xString string for i:=0;i<=m;i++{ xString = xString + x1_array[i].String() } var rString string for i:=0;i<=m;i++{ rString = rString + r1_array[i].String() } var cString string for i:=0;i<=m;i++{ cString = cString + c_array[i].X.String() + c_array[i].Y.String() } c := sha256.Sum256([]byte(GHString+xString+rString+cString)) intc := new(big.Int).SetBytes(c[:]) e := intc z_array := []*big.Int{} for i:=0;i<=m;i++{ z_array = append(z_array, new(big.Int).Mul(new(big.Int).Exp(e, big.NewInt(int64(i)),nil),x1_array[i])) } s := big.NewInt(0) for i:=0;i<=m;i++{ s = new(big.Int).Add(s, new(big.Int).Mul(new(big.Int).Exp(e, big.NewInt(int64(i)),nil),r1_array[i])) } k := KCO{ C_array: c_array, e: e, z_array: z_array, s:s, } fmt.Println("KCO generated") return k } func VerifyKCO(com Common, kco KCO) bool{ v_left := EC.G.Mult(big.NewInt(0)) for i:=0;i<len(kco.C_array);i++{ v_left = v_left.Add(kco.C_array[i].Mult(new(big.Int).Exp(kco.e, big.NewInt(int64(i)) ,nil))) } v_right := ComMul(com, kco.z_array, kco.s) if !v_left.Equal(v_right){ fmt.Println("Verify KCO failed") return false } fmt.Println("Verify KCO Succeed") return true }
package replaytutorial import ( "context" "database/sql" "flag" "io" "math/rand" "os" "os/signal" "syscall" "time" "github.com/corverroos/replay" replay_server "github.com/corverroos/replay/server" "github.com/corverroos/truss" "github.com/luno/jettison/errors" "github.com/luno/jettison/log" "github.com/luno/reflex" "github.com/luno/reflex/rsql" "github.com/corverroos/replaytutorial/lib/filenotifier" ) var dbURL = flag.String("db_url", "mysql://root@unix(/tmp/mysql.sock)/", "mysql db url (without DB name)") var dbName = flag.String("db_name", "replay_tutorial", "db schema name") var dbRestart = flag.Bool("db_refresh", false, "Whether to drop the existing DB on startup") var runLoops = flag.Bool("server_loops", true, "Whether to not to run the replay server loops. Note only a single active process may run the server loops") type State struct { DBC *sql.DB Replay replay.Client Cursors reflex.CursorStore AppCtxFunc func() context.Context } // Main calls the mainFunc with the tutorial state. It support additional application logic sql migrations. func Main(mainFunc func(context.Context, State) error, migrations ...string) { flag.Parse() ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT) defer cancel() dbc, err := connectDB(ctx, migrations...) if err != nil { log.Error(ctx, err) os.Exit(1) } cstore := rsql.NewCursorsTable("cursors", rsql.WithCursorAsyncDisabled()).ToStore(dbc) notifier, err := filenotifier.New() if err != nil { log.Error(ctx, errors.Wrap(err, "notifier")) os.Exit(1) } rcl := replay_server.NewDBClient(dbc, rsql.WithEventsNotifier(notifier)) appCtxFunc := func() context.Context { return ctx } if *runLoops { rcl.StartLoops(appCtxFunc, cstore, "") } rand.Seed(time.Now().UnixNano()) state := State{ DBC: dbc, Replay: rcl, Cursors: cstore, AppCtxFunc: appCtxFunc, } err = mainFunc(ctx, state) if ctx.Err() != nil { log.Info(ctx, "app context canceled") } else if err != nil { log.Error(ctx, err) os.Exit(1) } } // AwaitComplete streams all events and returns on the first RunCompleted event. func AwaitComplete(ctx context.Context, cl replay.Client, run string) error { sc, err := cl.Stream("", "", "")(ctx, "") if err != nil { return err } for { e, err := sc.Recv() if err != nil { return err } // Use the replay event handling functions. err = replay.Handle(e, replay.HandleRunCompleted(func(_, _, r string) error { if run == r { return io.EOF } return nil })) if errors.Is(err, io.EOF) { return nil } else if err != nil { return err } } } func connectDB(ctx context.Context, migrations ...string) (*sql.DB, error) { dbc, err := truss.Connect(*dbURL) if err != nil { return nil, errors.Wrap(err, "initial db connect") } if *dbRestart { _, err := dbc.ExecContext(ctx, "DROP DATABASE IF EXISTS "+*dbName) if err != nil { return nil, err } } _, err = dbc.ExecContext(ctx, "CREATE DATABASE IF NOT EXISTS "+*dbName+" CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;") if err != nil { return nil, err } dbc, err = truss.Connect(*dbURL + *dbName + "?parseTime=true") if err != nil { return nil, errors.Wrap(err, "db connect") } err = truss.Migrate(ctx, dbc, append(defaultMigrations, migrations...)) if err != nil { return nil, errors.Wrap(err, "migrate") } return dbc, nil } var defaultMigrations = []string{` CREATE TABLE replay_events ( id BIGINT NOT NULL AUTO_INCREMENT, ` + "`key`" + ` VARCHAR(512) NOT NULL, namespace VARCHAR(255) NOT NULL, workflow VARCHAR(255) NOT NULL, run VARCHAR(255), iteration INT NOT NULL, type INT NOT NULL, timestamp DATETIME(3) NOT NULL, message MEDIUMBLOB, PRIMARY KEY (id), UNIQUE by_type_key (type, ` + "`key`" + `), INDEX (type, namespace, workflow, run, iteration) ); `, ` CREATE TABLE replay_sleeps ( id BIGINT NOT NULL AUTO_INCREMENT, ` + "`key`" + ` VARCHAR(512) NOT NULL, created_at DATETIME(3) NOT NULL, complete_at DATETIME(3) NOT NULL, completed BOOL NOT NULL, PRIMARY KEY (id), UNIQUE by_key (` + "`key`" + `), INDEX (completed, complete_at) ); `, ` CREATE TABLE replay_signal_awaits ( id BIGINT NOT NULL AUTO_INCREMENT, ` + "`key`" + ` VARCHAR(512) NOT NULL, created_at DATETIME(3) NOT NULL, timeout_at DATETIME(3) NOT NULL, status TINYINT NOT NULL, PRIMARY KEY (id), UNIQUE by_key (` + "`key`" + `), INDEX (status) ); `, ` CREATE TABLE replay_signals ( id BIGINT NOT NULL AUTO_INCREMENT, namespace VARCHAR(255) NOT NULL, hash BINARY(128) NOT NULL, workflow VARCHAR(255) NOT NULL, run VARCHAR(255) NOT NULL, type TINYINT NOT NULL, external_id VARCHAR(255) NOT NULL, message MEDIUMBLOB, created_at DATETIME(3) NOT NULL, check_id BIGINT, PRIMARY KEY (id), UNIQUE uniq (namespace, hash) ); `, ` CREATE TABLE cursors ( id VARCHAR(255) NOT NULL, last_event_id BIGINT NOT NULL, updated_at DATETIME(3) NOT NULL, PRIMARY KEY (id) ); `, }
package dcode type JSONValue struct { data []byte } func NewJSONValue(b []byte) JSONValue { return JSONValue{data: b} } type Decoder func(JSONValue) (interface{}, error) // func Field(name string, decoder Decoder) Decoder { // } func DecodeString(d Decoder, s string) (interface{}, error) { return DecodeBytes(d, []byte(s)) } func DecodeBytes(d Decoder, b []byte) (interface{}, error) { jsonVal := NewJSONValue(b) return d(jsonVal) }
package basicauth import ( "encoding/base64" "net/http" "strings" ) type Config struct { UserName string Password string } type AuthFunc func(r *http.Request) bool func New(cfg Config) AuthFunc { return cfg.Auth } func (d *Config) Auth(r *http.Request) bool { aHeader := r.Header.Get("Authorization") if aHeader == "" || !strings.HasPrefix(aHeader, "Basic ") { return false } if aHeader != "Basic "+base64.StdEncoding.EncodeToString([]byte(d.UserName+":"+d.Password)) { return false } return true }
package main import ( "time" "fmt" ) func main() { t := time.Now() fmt.Println(t.Format("2006-01-02 15:04:05")) //OUTPUT: //2018-09-05 11:37:53 }
package lease import ( "context" "github.com/gookit/gcli/v3" "github.com/ovrclk/akash/x/market/types" "github.com/ovrclk/akcmd/client" "github.com/ovrclk/akcmd/flags" ) func QueryCmd() *gcli.Command { cmd := &gcli.Command{ Name: "lease", Desc: "Market lease query commands", Func: func(cmd *gcli.Command, args []string) error { cmd.ShowHelp() return nil }, Subs: []*gcli.Command{ListCMD(), GetCMD()}, } return cmd } func ListCMD() *gcli.Command { var pageOpts flags.PaginationOpts cmd := &gcli.Command{ Name: "list", Desc: "Query for all leases", Config: func(cmd *gcli.Command) { flags.AddQueryFlagsToCmd(cmd) pageOpts = flags.AddPaginationFlagsToCmd(cmd, "leases") flags.AddLeaseFilterFlags(cmd) }, Func: func(cmd *gcli.Command, args []string) error { clientCtx, err := client.GetClientQueryContext() if err != nil { return err } queryClient := types.NewQueryClient(clientCtx) lfilters, err := flags.LeaseFiltersFromFlags() if err != nil { return err } pageReq, err := flags.ReadPageRequest(pageOpts) if err != nil { return err } params := &types.QueryLeasesRequest{ Filters: lfilters, Pagination: pageReq, } res, err := queryClient.Leases(context.Background(), params) if err != nil { return err } return clientCtx.PrintProto(res) }, } return cmd } func GetCMD() *gcli.Command { cmd := &gcli.Command{ Name: "get", Desc: "Query lease", Config: func(cmd *gcli.Command) { flags.AddQueryFlagsToCmd(cmd) flags.AddQueryBidIDFlags(cmd) flags.MarkReqBidIDFlags(cmd) }, Func: func(cmd *gcli.Command, args []string) error { clientCtx, err := client.GetClientQueryContext() if err != nil { return err } queryClient := types.NewQueryClient(clientCtx) bidID, err := flags.BidIDFromFlags() if err != nil { return err } res, err := queryClient.Lease(context.Background(), &types.QueryLeaseRequest{ID: types.MakeLeaseID(bidID)}) if err != nil { return err } return clientCtx.PrintProto(res) }, } return cmd }
package test import ( "errors" "github.com/agiledragon/trans-dsl" "github.com/agiledragon/trans-dsl/test/context" "github.com/agiledragon/trans-dsl/test/context/action" . "github.com/smartystreets/goconvey/convey" "testing" ) func newRetryTrans() *transdsl.Transaction { trans := &transdsl.Transaction{ Fragments: []transdsl.Fragment{ &transdsl.Retry{ MaxTimes: 3, TimeLen: 100, Fragment: new(action.StubConnectServer), Errs: []error{errors.New("fatal"), errors.New("panic")}, }, }, } return trans } func TestRetryTrans(t *testing.T) { trans := newRetryTrans() Convey("TestRetryTrans", t, func() { Convey("trans exec succ when fail time is 1", func() { transInfo := &transdsl.TransInfo{ AppInfo: &context.StubInfo{ FailTimes: 1, }, } err := trans.Start(transInfo) So(err, ShouldEqual, nil) }) Convey("trans exec succ when fail time is 2", func() { transInfo := &transdsl.TransInfo{ AppInfo: &context.StubInfo{ FailTimes: 2, }, } err := trans.Start(transInfo) So(err, ShouldEqual, nil) }) Convey("trans exec fail when fail time is 3", func() { transInfo := &transdsl.TransInfo{ AppInfo: &context.StubInfo{ FailTimes: 3, }, } err := trans.Start(transInfo) So(err, ShouldNotEqual, nil) }) Convey("trans exec fail when error string is panic", func() { transInfo := &transdsl.TransInfo{ AppInfo: &context.StubInfo{ FailTimes: 1, Y: -1, }, } err := trans.Start(transInfo) So(err.Error(), ShouldEqual, "panic") }) }) }
//Package reader provides reading and parsing of the .csv files for database fields package reader import ( "bufio" "encoding/csv" "io" "os" "github.com/paulidealiste/ErroneusDilletante/models" ) //Reader implements .csv reading methods and data aggregation type Reader struct { Primbuck models.PrimaryBucket } //FillNames reads in and structures the csv with names func (r *Reader) FillNames(filepath string) error { readread, err := innerReader(filepath) r.Primbuck.Names = readread return err } //FillSurnames reads in and structures the csv with surnames func (r *Reader) FillSurnames(filepath string) error { readread, err := innerReader(filepath) r.Primbuck.Surnames = readread return err } //FillReviews reads in and structures the csv with reviews func (r *Reader) FillReviews(filepath string) error { readread, err := innerReader(filepath) r.Primbuck.Reviews = readread return err } func innerReader(filepath string) ([]string, error) { var readread []string csvFile, err := os.Open(filepath) if err != nil { return readread, err } reader := csv.NewReader(bufio.NewReader(csvFile)) for { line, err := reader.Read() if err == io.EOF { break } else if err != nil { return readread, err } readread = append(readread, line[0]) } return readread, nil }
package types import "encoding/json" type BaseResponse struct { Status string `json:"status"` ResponseData json.RawMessage `json:"responseData"` Exception *Exception `json:"exception"` } type Exception struct { Text string `json:"text"` SQLCode string `json:"sqlCode"` } type AuthResponse struct { SessionID int `json:"sessionId"` ProtocolVersion int `json:"protocolVersion"` ReleaseVersion string `json:"releaseVersion"` DatabaseName string `json:"databaseName"` ProductName string `json:"productName"` MaxDataMessageSize int `json:"maxDataMessageSize"` MaxIdentifierLength int `json:"maxIdentifierLength"` MaxVarcharLength int `json:"maxVarcharLength"` IdentifierQuoteString string `json:"identifierQuoteString"` TimeZone string `json:"timeZone"` TimeZoneBehavior string `json:"timeZoneBehavior"` } type PublicKeyResponse struct { PublicKeyPem string `json:"publicKeyPem"` PublicKeyModulus string `json:"publicKeyModulus"` PublicKeyExponent string `json:"publicKeyExponent"` } type SqlQueriesResponse struct { NumResults int `json:"numResults"` Results []json.RawMessage `json:"results"` } type SqlQueryResponseRowCount struct { ResultType string `json:"resultType"` RowCount int `json:"rowCount"` } type SqlQueryResponseResultSet struct { ResultType string `json:"resultType"` ResultSet SqlQueryResponseResultSetData `json:"resultSet"` } type SqlQueryResponseResultSetData struct { ResultSetHandle int `json:"resultSetHandle"` NumColumns int `json:"numColumns,omitempty"` NumRows int `json:"numRows"` NumRowsInMessage int `json:"numRowsInMessage"` Columns []SqlQueryColumn `json:"columns,omitempty"` Data [][]interface{} `json:"data"` } type SqlQueryColumn struct { Name string `json:"name"` DataType SqlQueryColumnType `json:"dataType"` } type SqlQueryColumnType struct { Type string `json:"type"` Precision *int64 `json:"precision,omitempty"` Scale *int64 `json:"scale,omitempty"` Size *int64 `json:"size,omitempty"` CharacterSet *string `json:"characterSet,omitempty"` WithLocalTimeZone *bool `json:"withLocalTimeZone,omitempty"` Fraction *int `json:"fraction,omitempty"` SRID *int `json:"srid,omitempty"` } type CreatePreparedStatementResponse struct { StatementHandle int `json:"statementHandle"` ParameterData ParameterData `json:"parameterData,omitempty"` } type ParameterData struct { NumColumns int `json:"numColumns"` Columns []SqlQueryColumn `json:"columns"` SqlQueriesResponse }
package sudokuhistory import ( "github.com/jkomoros/sudoku" "github.com/jkomoros/sudoku/sdkconverter" "reflect" "testing" ) func TestReset(t *testing.T) { model := &Model{} grid := sudoku.NewGrid() grid.MutableCell(3, 3).SetNumber(5) grid.LockFilledCells() converter := sdkconverter.Converters["doku"] if converter == nil { t.Fatal("Couldn't find doku converter") } snapshot := converter.DataString(grid) grid.MutableCell(4, 4).SetNumber(6) model.SetGrid(grid) if model.Grid().Cell(4, 4).Number() != 0 { t.Error("Expected grid to be reset after being set, but the unlocked cell remained:", model.Grid().Cell(4, 4).Number()) } if model.snapshot != snapshot { t.Error("Got unexpected snapshot: got", model.snapshot, "expected", snapshot) } } func TestMarkMutator(t *testing.T) { model := &Model{} model.SetGrid(sudoku.NewGrid()) cell := model.grid.MutableCell(0, 0) cell.SetMark(1, true) command := model.newMarkCommand(sudoku.CellRef{0, 0}, map[int]bool{1: true}) if command != nil { t.Error("Got invalid command, expected nil", command) } command = model.newMarkCommand(sudoku.CellRef{0, 0}, map[int]bool{1: false, 2: true, 3: false}) if command.Number() != nil { t.Error("Expected nil for number, got non-nil:", command.Number()) } marks := command.Marks() if marks == nil { t.Error("Got nil from Marks on mark command") } //3:false is a no-op so we expect it to be discarded. if !reflect.DeepEqual(map[int]bool{1: false, 2: true}, marks) { t.Error("Marks back from command was wrong, got", marks) } command.Apply(model) if !cell.Marks().SameContentAs(sudoku.IntSlice{2}) { t.Error("Got wrong marks after mutating:", cell.Marks()) } command.Undo(model) if !cell.Marks().SameContentAs(sudoku.IntSlice{1}) { t.Error("Got wrong marks after undoing:", cell.Marks()) } if !reflect.DeepEqual(command.ModifiedCells(model), sudoku.CellRefSlice{sudoku.CellRef{0, 0}}) { t.Error("Didn't get right Modified Cells") } } func TestNumberMutator(t *testing.T) { model := &Model{} model.SetGrid(sudoku.NewGrid()) cell := model.grid.Cell(0, 0) command := model.newNumberCommand(sudoku.CellRef{0, 0}, 0) if command != nil { t.Error("Got non-nil number command for a no op") } command = model.newNumberCommand(sudoku.CellRef{0, 0}, 1) if command.Marks() != nil { t.Error("Got non-nil from Marks on mark command") } number := command.Number() if number == nil { t.Error("Expected non-nil for number, got nil") } if *number != 1 { t.Error("Number returned from number command was not right. Got:", *number) } command.Apply(model) if cell.Number() != 1 { t.Error("Number mutator didn't add the number") } command.Undo(model) if cell.Number() != 0 { t.Error("Number mutator didn't undo") } if !reflect.DeepEqual(command.ModifiedCells(model), sudoku.CellRefSlice{sudoku.CellRef{0, 0}}) { t.Error("Didn't get right Modified Cells") } } func TestGroups(t *testing.T) { model := &Model{} model.SetGrid(sudoku.NewGrid()) model.SetNumber(sudoku.CellRef{0, 0}, 1) if model.grid.Cell(0, 0).Number() != 1 { t.Fatal("Setting number outside group didn't set number") } model.SetMarks(sudoku.CellRef{0, 1}, map[int]bool{3: true}) if !model.grid.Cell(0, 1).Marks().SameContentAs(sudoku.IntSlice{3}) { t.Fatal("Setting marks outside of group didn't set marks") } state := model.grid.Diagram(true) if model.InGroup() { t.Error("Model reported being in group even though it wasn't") } model.StartGroup("foo") if !model.InGroup() { t.Error("Model didn't report being in a group even though it was") } model.SetNumber(sudoku.CellRef{0, 2}, 1) model.SetMarks(sudoku.CellRef{0, 3}, map[int]bool{3: true}) if model.grid.Diagram(true) != state { t.Error("Within a group setnumber and setmarks mutated the grid") } model.FinishGroupAndExecute() command := model.currentCommand.c subCommands := command.subCommands if len(subCommands) != 2 { t.Fatal("Got wrong sized subcommands for marks", len(subCommands)) } if subCommands[0].Number() == nil { t.Error("Sub command #1 was not number") } if subCommands[1].Marks() == nil { t.Error("Sub command #2 was not marks") } if command.description != "foo" { t.Error("Expected description of 'foo', got:", command.description) } if command.Marks() != nil { t.Error("Got non-nil from Marks on mark command") } if command.Number() != nil { t.Error("Expected nil for number, got non-nil:", command.Number()) } if model.InGroup() { t.Error("After finishing a group model still said it was in group") } if model.grid.Diagram(true) == state { t.Error("Commiting a group didn't mutate grid") } if model.grid.Cell(0, 2).Number() != 1 { t.Error("Commiting a group didn't set the number") } if !model.grid.Cell(0, 3).Marks().SameContentAs(sudoku.IntSlice{3}) { t.Error("Commiting a group didn't set the right marks") } model.Undo() if model.grid.Diagram(true) != state { t.Error("Undoing a group update didn't set the grid back to same state") } model.StartGroup("discardable") model.CancelGroup() if model.InGroup() { t.Error("After canceling a group the model still thought it was in one.") } } func TestUndoRedo(t *testing.T) { model := &Model{} model.SetGrid(sudoku.NewGrid()) if model.Undo() { t.Error("Could undo on a fresh grid") } if model.Redo() { t.Error("Could redo on a fresh grid") } rememberedStates := []string{ model.grid.Diagram(true), } rememberedModfiedCells := []sudoku.CellRefSlice{ nil, } model.SetNumber(sudoku.CellRef{0, 0}, 1) rememberedStates = append(rememberedStates, model.grid.Diagram(true)) rememberedModfiedCells = append(rememberedModfiedCells, sudoku.CellRefSlice{sudoku.CellRef{0, 0}}) model.SetNumber(sudoku.CellRef{0, 1}, 2) rememberedStates = append(rememberedStates, model.grid.Diagram(true)) rememberedModfiedCells = append(rememberedModfiedCells, sudoku.CellRefSlice{sudoku.CellRef{0, 1}}) model.SetNumber(sudoku.CellRef{0, 0}, 3) rememberedStates = append(rememberedStates, model.grid.Diagram(true)) rememberedModfiedCells = append(rememberedModfiedCells, sudoku.CellRefSlice{sudoku.CellRef{0, 0}}) model.SetMarks(sudoku.CellRef{0, 2}, map[int]bool{3: true, 4: true}) rememberedStates = append(rememberedStates, model.grid.Diagram(true)) rememberedModfiedCells = append(rememberedModfiedCells, sudoku.CellRefSlice{sudoku.CellRef{0, 2}}) model.SetMarks(sudoku.CellRef{0, 2}, map[int]bool{1: true, 4: false}) rememberedStates = append(rememberedStates, model.grid.Diagram(true)) rememberedModfiedCells = append(rememberedModfiedCells, sudoku.CellRefSlice{sudoku.CellRef{0, 2}}) if model.Redo() { t.Error("Able to redo even though at end") } for i := len(rememberedStates) - 1; i >= 1; i-- { if model.grid.Diagram(true) != rememberedStates[i] { t.Error("Remembere state wrong for state", i) } if !reflect.DeepEqual(model.LastModifiedCells(), rememberedModfiedCells[i]) { t.Error("Wrong last modified cells", i) } if !model.Undo() { t.Error("Couldn't undo early: ", i) } } //Verify we can't undo at beginning if model.Undo() { t.Error("Could undo even though it was the beginning.") } for i := 0; i < 3; i++ { if model.grid.Diagram(true) != rememberedStates[i] { t.Error("Remembered states wrong for state", i, "when redoing") } if !reflect.DeepEqual(model.LastModifiedCells(), rememberedModfiedCells[i]) { t.Error("Wrong last modified cells", i) } if !model.Redo() { t.Error("Unable to redo") } } model.SetNumber(sudoku.CellRef{2, 0}, 3) if model.Redo() { t.Error("Able to redo even though just spliced in a new move.") } //verify setting a new grid clears history model.SetGrid(sudoku.NewGrid()) if model.Undo() { t.Error("Could undo on a new grid") } if model.Redo() { t.Error("Could undo on an old grid") } }
package main import ( "log" brokerImpl "test/broker-impl" "test/cli" "test/geo" "time" ) func main() { broker := brokerImpl.NewBrokerImpl() broker.Start() geos := make([]*geo.GeoService, 5) for i := 0; i < 5; i++ { geos[i] = geo.NewGeoService() ch, err := broker.Register(geos[i].GetName()) if err != nil { log.Println(err) } else { geos[i].Start(broker, ch) } } cli := cli.NewCliService() ch, err := broker.Register(cli.GetName()) if err != nil { log.Println(err) } else { cli.Start(broker, ch) } time.Sleep(time.Minute) for i := 0; i < 5; i++ { geos[i].Stop() } cli.Stop() broker.Stop() }
package fuzz import ( "bytes" "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "text/template" ) // ErrGoTestFailed indicates that a 'go test' invocation failed, // most likely because the test had a legitimate failure. var ErrGoTestFailed = errors.New("go test failed") // VerifyCorpus runs all of the files in a corpus directory as subtests. // The approach is to create a temp dir, then create a synthetic corpus_test.go // file with a TestCorpus(t *testing.T) func that loads all the files from the corpus, // and passes them to the Fuzz function in a t.Run call. // A standard 'go test .' is then invoked within that temporary directory. // The inputs used are all deterministic (without generating new fuzzing-based inputs). // The names used with t.Run mean a 'fzgo test -run=TestCorpus/<corpus-file-name>' works. // One way to see the file names or otherwise verify execution is to run 'fzgo test -v <pkg>'. func VerifyCorpus(function Func, workDir string, run string, verbose bool) error { corpusDir := filepath.Join(workDir, "corpus") return verifyFiles(function, corpusDir, run, "TestCorpus", verbose) } // VerifyCrashers is similar to VerifyCorpus, but runs the crashers. It // can be useful to pass -v to what is causing a crash, such as 'fzgo test -v -fuzz=. -run=TestCrashers' func VerifyCrashers(function Func, workDir string, run string, verbose bool) error { crashersDir := filepath.Join(workDir, "crashers") return verifyFiles(function, crashersDir, run, "TestCrashers", verbose) } // verifyFiles implements the heart of VerifyCorpus and VerifyCrashers func verifyFiles(function Func, filesDir string, run string, testFunc string, verbose bool) error { report := func(err error) error { if err == ErrGoTestFailed { return err } return fmt.Errorf("verify corpus for %s: %v", function.FuzzName(), err) } if _, err := os.Stat(filesDir); os.IsNotExist(err) { // No corpus to validate. // TODO: a future real 'go test' invocation should be silent in this case, // given the proposed intent is to always check for a corpus for normal 'go test' invocations. // However, maybe fzgo should warn? or warn if -v is passed? or always be silent? // Right now, main.go is making the decision to skip calling VerifyCorpus if workDir is not found. return nil } // Check if we have a regex match for -run regexp for this testFunc // TODO: add test for TestCorpus/fced9f7db3881a5250d7e287ab8c33f2952f0e99-8 // cd fzgo/examples // fzgo test -fuzz=FuzzWithBasicTypes -run=TestCorpus/fced9f7db3881a5250d7e287ab8c33f2952f0e99-8 ./... -v // Doesn't print anything? if run == "" { report(fmt.Errorf("invalid empty run argument")) } runFields := strings.SplitN(run, "/", 2) re1 := runFields[0] ok, err := regexp.MatchString(re1, testFunc) if err != nil { report(fmt.Errorf("invalid regexp %q for -run: %v", run, err)) } if !ok { // Nothing to do. Return now to avoid 'go test' saying nothing to do. return nil } // Do a light test to see if there are any files in the filesDir. // This avoids 'go test' from reporting 'no tests' (and does not need to be perfect check). re2 := "." matchedFile := false if len(runFields) > 1 { re2 = runFields[1] } entries, err := ioutil.ReadDir(filesDir) if err != nil { report(err) } for i := range entries { ok, err := regexp.MatchString(re2, entries[i].Name()) if err != nil { report(fmt.Errorf("invalid regexp %q for -run: %v", run, err)) } if ok { matchedFile = true break } } if !matchedFile { return nil } // check if we have a plain data []byte signature, vs. a rich signature plain, err := IsPlainSig(function.TypesFunc) if err != nil { return report(err) } var target Target if plain { // create our initial target struct using the actual func supplied by the user. target = Target{UserFunc: function} } else { info("detected rich signature for %v.%v", function.PkgName, function.FuncName) // create a wrapper function to handle the rich signature. // if both -v and -run is set (presumaly to some corpus file), // as a convinience also print the deserialized arguments printArgs := verbose && run != "" target, err = CreateRichSigWrapper(function, printArgs) if err != nil { return report(err) } // CreateRichSigWrapper was successful, which means it populated the temp dir with the wrapper func. // By the time we leave our current function, we are done with the temp dir // that CreateRichSigWrapper created, so delete via a defer. // (We can't delete it immediately because we haven't yet run go-fuzz-build on it). defer os.RemoveAll(target.wrapperTempDir) // TODO: consider moving gopath setup into richsig, store on Target // also set up a second entry in GOPATH to include our temporary directory containing the rich sig wrapper. } // create temp dir to work in. // this is where we will create a corpus test wrapper suitable for running a normal 'go test'. tempDir, err := ioutil.TempDir("", "fzgo-verify-corpus") if err != nil { return report(fmt.Errorf("failed to create temp dir: %v", err)) } defer os.RemoveAll(tempDir) // cd to our temp dir to simplify invoking 'go test' oldWd, err := os.Getwd() if err != nil { return err } err = os.Chdir(tempDir) if err != nil { return err } defer func() { os.Chdir(oldWd) }() var pkgPath, funcName string var env []string if target.hasWrapper { pkgPath = target.wrapperFunc.PkgPath funcName = target.wrapperFunc.FuncName env = target.wrapperEnv } else { pkgPath = target.UserFunc.PkgPath funcName = target.UserFunc.FuncName env = nil } // write out temporary corpus_test.go file vals := map[string]string{"pkgPath": pkgPath, "filesDir": filesDir, "testFunc": testFunc, "funcName": funcName} buf := new(bytes.Buffer) if err := corpusTestSrc.Execute(buf, vals); err != nil { report(fmt.Errorf("could not execute template: %v", err)) } // return buf.Bytes() // src := fmt.Sprintf(corpusTestSrc, // pkgPath, // filesDir, // testFunc, // testFunc, // funcName) // err = ioutil.WriteFile(filepath.Join(tempDir, "corpus_test.go"), []byte(src), 0700) err = ioutil.WriteFile(filepath.Join(tempDir, "corpus_test.go"), buf.Bytes(), 0700) if err != nil { return report(fmt.Errorf("failed to create temporary corpus_test.go: %v", err)) } // actually run 'go test .' now! runArgs := []string{ "test", buildTagsArg, ".", } // formerly, we passed through nonPkgArgs here from fzgo flag parsing. // now, we choose which flags explicitly to pass on (currently -run and -v). // we could return to passing through everything, but would need to strip things like -fuzzdir // that 'go test' does not understand. if run != "" { runArgs = append(runArgs, fmt.Sprintf("-run=%s", run)) } if verbose { runArgs = append(runArgs, "-v") } err = ExecGo(runArgs, env) if err != nil { // we will guess for now at least that this was due to a test failure. // the 'go' command should have already printed the details on the failure. // return a sentinel error here so that a caller can exit with non-zero exit code // without printing any additional error beyond what the 'go' command printed. return ErrGoTestFailed } return nil } // corpusTestTemplate provides a test function that runs // all of the files in a corpus directory as subtests. // This template needs three string variables to be supplied: // 1. an import path to the fuzzer, such as: // github.com/dvyukov/go-fuzz-corpus/png // 2. the directory path to the corpus, such as: // /tmp/gopath/src/github.com/dvyukov/go-fuzz-corpus/png/testdata/fuzz/png.Fuzz/corpus/ // 3. the fuzz function name, such as: // Fuzz var corpusTestSrc = template.Must(template.New("CorpusTest").Parse(` package corpustest import ( "io/ioutil" "path/filepath" {{if eq .testFunc "TestCrashers"}} "strings" {{end}} "testing" fuzzer "{{.pkgPath}}" ) var corpusPath = ` + "`{{.filesDir}}`" + ` // %s executes a fuzzing function against each file in a corpus directory // as subtests. func {{.testFunc}}(t *testing.T) { files, err := ioutil.ReadDir(corpusPath) if err != nil { t.Fatal(err) } for _, file := range files { if file.IsDir() { continue } {{if eq .testFunc "TestCrashers"}} // exclude auxillary files that reside in the crashers directory. if strings.HasSuffix(file.Name(), ".output") || strings.HasSuffix(file.Name(), ".quoted") { continue } {{end}} t.Run(file.Name(), func(t *testing.T) { dat, err := ioutil.ReadFile(filepath.Join(corpusPath, file.Name())) if err != nil { t.Error(err) } fuzzer.{{.funcName}}(dat) }) } } `))
package auto import ( "../api/models" ) var users = []models.User{ { Nickname: "Jhon Doe", Email: "jhondoe@email.com", Password: "123456", }, { Nickname: "Chi Thien", Email: "chithien@gmail.com", Password: "123456", }, } var posts = []models.Post{ { Title: "Title post 01", Content: "Post 01 content", }, { Title: "Title post 02", Content: "Post 02 content", }, }
package cdn import ( "fmt" "time" "github.com/empirefox/esecend/config" "qiniupkg.com/api.v7/kodo" ) type Qiniu struct { conf *config.Qiniu Client *kodo.Client } func NewQiniu(c *config.Config) *Qiniu { conf := &c.Qiniu kodoConfig := &kodo.Config{ AccessKey: conf.Ak, SecretKey: conf.Sk, } return &Qiniu{ conf: conf, Client: kodo.New(conf.Zone, kodoConfig), } } func (q *Qiniu) HeadUptoken(userId uint) string { putPolicy := &kodo.PutPolicy{ Scope: fmt.Sprintf("%s:%s%d", q.conf.HeadBucketName, q.conf.HeadPrefix, userId), UpHosts: []string{q.conf.HeadUpHost}, Expires: uint32(time.Now().Unix()) + q.conf.HeadUptokenLifeMinute*60, } return q.Client.MakeUptoken(putPolicy) }
package introspection import ( "encoding/json" "errors" "fmt" "github.com/jclem/graphsh/graphql" "github.com/jclem/graphsh/querybuilder" ) var schema *Schema // GetFields gets the fields for a given query func GetFields(q graphql.Querier, query *querybuilder.Query) ([]Field, error) { typ, ok := schema.GetQueryType() if !ok { return nil, errors.New("No QueryType present in schema") } for _, node := range query.List() { if node.ConcreteType == "" { field, ok := typ.GetField(node.Name) if !ok { return nil, fmt.Errorf("Missing field %q from type %q", node.Name, typ.Name) } typ, ok = schema.GetType(field.GetTypeName()) if !ok { return nil, fmt.Errorf("Missing type %q", field.GetTypeName()) } } else { typ, ok = schema.GetType(node.ConcreteType) if !ok { return nil, fmt.Errorf("Missing type %q", node.ConcreteType) } } } return typ.Fields, nil } // LoadSchema pre-loads the schema struct func LoadSchema(q graphql.Querier) error { if schema != nil { return nil } respBody, err := q.Query(schemaQuery) if err != nil { return err } var introspection introspection if err := json.Unmarshal(respBody, &introspection); err != nil { return err } schema = &introspection.Data.Schema return nil }
package models import ( "encoding/json" "io" "time" //_ "url_shortener/controllers" ) // Direction es la entidad de una direccion a redirigir type Direction struct { ID uint64 `json:"id"` URL string `json:"url"` ShortURL string `json:"short_url"` CreateAt time.Time `-` UpdateAt time.Time `-` DeleteAt time.Time `-` } // ToJSON devuelve una respuesta codificada en json func (d *Direction) ToJSON(w io.Writer) error { encoder := json.NewEncoder(w) return encoder.Encode(d) } // FromJSON obtiene del cliente una respuesta codificada en json func (d *Direction) FromJSON(r io.Reader) error { encoder := json.NewDecoder(r) return encoder.Decode(d) }
package main import ( "bytes" "fmt" "github.com/vidmed/request" "time" "github.com/BurntSushi/toml" ) var configInstance *TomlConfig // TomlConfig represents a config type TomlConfig struct { Main Main } // Main represent a main section of the TomlConfig type Main struct { LogLevel uint8 ListenAddr string ListenPort uint } // GetConfig returns application config func GetConfig() *TomlConfig { return configInstance } // NewConfig creates new application config with given .toml file func NewConfig(file string) (*TomlConfig, error) { configInstance = &TomlConfig{} if _, err := toml.DecodeFile(file, configInstance); err != nil { return nil, err } dump(configInstance) // check required fields // Main if configInstance.Main.ListenAddr == "" { request.GetLogger().Fatalln("Main.ListenAddr must be specified. Check your Config file") } if configInstance.Main.ListenPort == 0 { request.GetLogger().Fatalln("Main.ListenPort must be specified. Check your Config file") } return configInstance, nil } func dump(cfg *TomlConfig) { var buffer bytes.Buffer e := toml.NewEncoder(&buffer) err := e.Encode(cfg) if err != nil { request.GetLogger().Fatal(err) } fmt.Println( time.Now().UTC(), "\n---------------------Sevice started with config:\n", buffer.String(), "\n---------------------") }
package builder import ( "bufio" "encoding/json" "fmt" "io" "os" "path/filepath" "sort" "strings" "syscall" "time" "github.com/Cloud-Foundations/Dominator/imageserver/client" "github.com/Cloud-Foundations/Dominator/lib/configwatch" "github.com/Cloud-Foundations/Dominator/lib/filter" "github.com/Cloud-Foundations/Dominator/lib/format" libjson "github.com/Cloud-Foundations/Dominator/lib/json" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/slavedriver" "github.com/Cloud-Foundations/Dominator/lib/srpc" "github.com/Cloud-Foundations/Dominator/lib/stringutil" "github.com/Cloud-Foundations/Dominator/lib/triggers" "github.com/Cloud-Foundations/Dominator/lib/url/urlutil" ) func getNamespace() (string, error) { pathname := fmt.Sprintf("/proc/%d/ns/mnt", syscall.Gettid()) namespace, err := os.Readlink(pathname) if err != nil { return "", fmt.Errorf("error discovering namespace: %s", err) } return namespace, nil } func imageStreamsDecoder(reader io.Reader) (interface{}, error) { return imageStreamsRealDecoder(reader) } func imageStreamsRealDecoder(reader io.Reader) ( *imageStreamsConfigurationType, error) { var config imageStreamsConfigurationType decoder := json.NewDecoder(bufio.NewReader(reader)) if err := decoder.Decode(&config); err != nil { return nil, err } for _, stream := range config.Streams { stream.builderUsers = stringutil.ConvertListToMap(stream.BuilderUsers, false) } return &config, nil } func load(confUrl, variablesFile, stateDir, imageServerAddress string, imageRebuildInterval time.Duration, slaveDriver *slavedriver.SlaveDriver, logger log.DebugLogger) (*Builder, error) { ctimeResolution, err := getCtimeResolution() if err != nil { return nil, err } logger.Printf("Inode Ctime resolution: %s\n", format.Duration(ctimeResolution)) initialNamespace, err := getNamespace() if err != nil { return nil, err } logger.Printf("Initial namespace: %s\n", initialNamespace) err = syscall.Mount("none", "/", "", syscall.MS_REC|syscall.MS_PRIVATE, "") if err != nil { return nil, fmt.Errorf("error making mounts private: %s", err) } masterConfiguration, err := loadMasterConfiguration(confUrl) if err != nil { return nil, fmt.Errorf("error getting master configuration: %s", err) } if len(masterConfiguration.BootstrapStreams) < 1 { logger.Println( "No bootstrap streams configured: some operations degraded") } imageStreamsToAutoRebuild := make([]string, 0) for name := range masterConfiguration.BootstrapStreams { imageStreamsToAutoRebuild = append(imageStreamsToAutoRebuild, name) } sort.Strings(imageStreamsToAutoRebuild) for _, name := range masterConfiguration.ImageStreamsToAutoRebuild { imageStreamsToAutoRebuild = append(imageStreamsToAutoRebuild, name) } var variables map[string]string if variablesFile != "" { if err := libjson.ReadFromFile(variablesFile, &variables); err != nil { return nil, err } } if variables == nil { variables = make(map[string]string) } generateDependencyTrigger := make(chan struct{}, 0) b := &Builder{ bindMounts: masterConfiguration.BindMounts, generateDependencyTrigger: generateDependencyTrigger, stateDir: stateDir, imageServerAddress: imageServerAddress, logger: logger, imageStreamsUrl: masterConfiguration.ImageStreamsUrl, initialNamespace: initialNamespace, bootstrapStreams: masterConfiguration.BootstrapStreams, imageStreamsToAutoRebuild: imageStreamsToAutoRebuild, slaveDriver: slaveDriver, currentBuildInfos: make(map[string]*currentBuildInfo), lastBuildResults: make(map[string]buildResultType), packagerTypes: masterConfiguration.PackagerTypes, variables: variables, } for name, stream := range b.bootstrapStreams { stream.builder = b stream.name = name } imageStreamsConfigChannel, err := configwatch.WatchWithCache( masterConfiguration.ImageStreamsUrl, time.Second*time.Duration( masterConfiguration.ImageStreamsCheckInterval), imageStreamsDecoder, filepath.Join(stateDir, "image-streams.json"), time.Second*5, logger) if err != nil { return nil, err } go b.dependencyGeneratorLoop(generateDependencyTrigger) go b.watchConfigLoop(imageStreamsConfigChannel) go b.rebuildImages(imageRebuildInterval) return b, nil } func loadImageStreams(url string) (*imageStreamsConfigurationType, error) { if url == "" { return &imageStreamsConfigurationType{}, nil } file, err := urlutil.Open(url) if err != nil { return nil, err } defer file.Close() configuration, err := imageStreamsRealDecoder(file) if err != nil { return nil, fmt.Errorf("error decoding image streams from: %s: %s", url, err) } return configuration, nil } func loadMasterConfiguration(url string) (*masterConfigurationType, error) { file, err := urlutil.Open(url) if err != nil { return nil, err } defer file.Close() var configuration masterConfigurationType decoder := json.NewDecoder(bufio.NewReader(file)) if err := decoder.Decode(&configuration); err != nil { return nil, fmt.Errorf("error reading configuration from: %s: %s", url, err) } for _, stream := range configuration.BootstrapStreams { if _, ok := configuration.PackagerTypes[stream.PackagerType]; !ok { return nil, fmt.Errorf("packager type: \"%s\" unknown", stream.PackagerType) } if stream.Filter != nil { if err := stream.Filter.Compile(); err != nil { return nil, err } } if stream.ImageFilterUrl != "" { filterFile, err := urlutil.Open(stream.ImageFilterUrl) if err != nil { return nil, err } defer filterFile.Close() stream.imageFilter, err = filter.Read(filterFile) if err != nil { return nil, err } } if stream.ImageTriggersUrl != "" { triggersFile, err := urlutil.Open(stream.ImageTriggersUrl) if err != nil { return nil, err } defer triggersFile.Close() stream.imageTriggers, err = triggers.Read(triggersFile) if err != nil { return nil, err } } } return &configuration, nil } func (b *Builder) delayMakeRequiredDirectories(abortNotifier <-chan struct{}) { timer := time.NewTimer(time.Second * 5) select { case <-abortNotifier: if !timer.Stop() { <-timer.C } case <-timer.C: b.makeRequiredDirectories() } } func (b *Builder) makeRequiredDirectories() error { imageServer, err := srpc.DialHTTP("tcp", b.imageServerAddress, 0) if err != nil { b.logger.Printf("%s: %s\n", b.imageServerAddress, err) return nil } defer imageServer.Close() directoryList, err := client.ListDirectories(imageServer) if err != nil { b.logger.Println(err) return nil } directories := make(map[string]struct{}, len(directoryList)) for _, directory := range directoryList { directories[directory.Name] = struct{}{} } streamNames := b.listAllStreamNames() for _, streamName := range streamNames { if _, ok := directories[streamName]; ok { continue } pathComponents := strings.Split(streamName, "/") for index := range pathComponents { partPath := strings.Join(pathComponents[0:index+1], "/") if _, ok := directories[partPath]; ok { continue } if err := client.MakeDirectory(imageServer, partPath); err != nil { return err } b.logger.Printf("Created missing directory: %s\n", partPath) directories[partPath] = struct{}{} } } return nil } func (b *Builder) reloadNormalStreamsConfiguration() error { imageStreamsConfiguration, err := loadImageStreams(b.imageStreamsUrl) if err != nil { return err } b.logger.Println("Reloaded streams streams configuration") return b.updateImageStreams(imageStreamsConfiguration) } func (b *Builder) updateImageStreams( imageStreamsConfiguration *imageStreamsConfigurationType) error { for name, stream := range imageStreamsConfiguration.Streams { stream.builder = b stream.name = name } b.streamsLock.Lock() b.imageStreams = imageStreamsConfiguration.Streams b.streamsLock.Unlock() b.triggerDependencyDataGeneration() return b.makeRequiredDirectories() } func (b *Builder) watchConfigLoop(configChannel <-chan interface{}) { firstLoadNotifier := make(chan struct{}) go b.delayMakeRequiredDirectories(firstLoadNotifier) for rawConfig := range configChannel { imageStreamsConfig, ok := rawConfig.(*imageStreamsConfigurationType) if !ok { b.logger.Printf("received unknown type over config channel") continue } if firstLoadNotifier != nil { firstLoadNotifier <- struct{}{} close(firstLoadNotifier) firstLoadNotifier = nil } b.logger.Println("received new image streams configuration") b.updateImageStreams(imageStreamsConfig) } }
package response type RestartPodResponse struct { Success bool `json:"success"` }
package main import ( "crypto/subtle" "encoding/base64" "encoding/json" "errors" "fmt" "hipeople.api/internal" "io/ioutil" "log" "net/http" "strconv" "strings" ) type Api struct { config *internal.Config imageService *internal.ImageService user string } func NewApi(config *internal.Config, service *internal.ImageService) *Api { return &Api{ config: config, imageService: service, } } func (a *Api) handler() http.Handler { mux := http.NewServeMux() mux.Handle("/images/", a.checkAuth(a.imagesRouter)) mux.Handle("/images/direct/", a.checkAuth(a.direct)) return mux } func (a *Api) run() { server := &http.Server{ Addr: ":8080", Handler: a.handler(), } log.Fatal(server.ListenAndServe()) } func main() { config := internal.NewConfig() // In production app I would use real DB with some cache in front of it. db := make(internal.FakeDB) imageRepository := internal.NewImageRepository(db) imageService := internal.NewImageService(imageRepository) api := NewApi(config, imageService) api.run() } func (a *Api) findUser(splitToken []string) (string, error) { if len(splitToken) != 2 || splitToken[0] != "Bearer" { return "", errors.New("findUser.notFound") } for _, token := range a.config.Tokens { if subtle.ConstantTimeCompare([]byte(splitToken[1]), []byte(token.Token)) == 1 { return token.User, nil } } return "", errors.New("findUser.notFound") } func (a *Api) checkAuth(handler http.HandlerFunc) http.Handler { return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { forbidden := true if len(request.Header["Authorization"]) >= 1 { if user, err := a.findUser(strings.Fields(request.Header["Authorization"][0])); err == nil { a.user = user forbidden = false } } if forbidden { writer.WriteHeader(http.StatusForbidden) return } handler.ServeHTTP(writer, request) }) } func (a *Api) direct(writer http.ResponseWriter, request *http.Request) { log.Printf("direct, url: %v, method: %v", request.URL, request.Method) if request.Method != http.MethodGet { a.notSupported(writer, request, "GET") return } imageId, err := parseImageId(request.URL.Path[strings.LastIndex(request.URL.Path, "/")+1:]) if err != nil { log.Println("getImages.BadRequest,", err) writer.WriteHeader(http.StatusBadRequest) return } image := a.imageService.SelectImage(imageId, a.user) if image == nil { log.Println("direct.NotFound") writer.WriteHeader(http.StatusNotFound) return } writer.Header().Set("Content-Type", image.Mime) dec, _ := base64.URLEncoding.DecodeString(image.Data) writer.Write(dec) } func (a *Api) imagesRouter(writer http.ResponseWriter, request *http.Request) { log.Printf("imagesRouter, url: %v, method: %v, user %v", request.URL, request.Method, a.user) lastPath := request.URL.Path[strings.LastIndex(request.URL.Path, "/")+1:] switch request.Method { case http.MethodGet: a.getImages(writer, request, lastPath) case http.MethodPost: a.postImages(writer, request, lastPath) default: a.notSupported(writer, request, "GET, POST") } } func (a *Api) getImages(writer http.ResponseWriter, _ *http.Request, lastPath string) { imageId, err := parseImageId(lastPath) if err != nil { log.Println("getImages.BadRequest,", err) writer.WriteHeader(http.StatusBadRequest) return } var result interface{} if imageId == 0 { result = a.imageService.SelectImages(a.user) } else { result = a.imageService.SelectImage(imageId, a.user) } if result == nil { log.Println("getImages.NotFound") writer.WriteHeader(http.StatusNotFound) return } resultJson, _ := json.Marshal(result) writer.Header().Set("Content-Type", "application/json") writer.Write(resultJson) } func (a *Api) postImages(writer http.ResponseWriter, request *http.Request, lastPath string) { if lastPath != "" { writer.WriteHeader(http.StatusMethodNotAllowed) log.Println("postImages.StatusMethodNotAllowed") return } body, err := ioutil.ReadAll(request.Body) if err != nil { writer.WriteHeader(http.StatusUnprocessableEntity) log.Println("postImages.UnprocessableEntity,", err) return } image, err := internal.NewImageJson(&body) if err != nil { writer.WriteHeader(http.StatusBadRequest) log.Println("postImages.BadRequest,", err) return } imageId := a.imageService.InsertImage(image, a.user) writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusCreated) writer.Write([]byte(fmt.Sprintf("{\"image_id\": %v}", imageId))) } func (a *Api) notSupported(writer http.ResponseWriter, _ *http.Request, methods string) { writer.Header().Set("Allow", methods) writer.WriteHeader(http.StatusMethodNotAllowed) log.Println("notSupported.MethodNotAllowed") } func parseImageId(lastPath string) (int, error) { if lastPath != "" { if parsedInt, err := strconv.ParseInt(lastPath, 10, 64); err != nil { return 0, err } else { return int(parsedInt), err } } return 0, nil }
package main import ( "fmt" "github.com/fogleman/gg" "image/color" "math" ) type canvas struct { *gg.Context radiusX float64 radiusY float64 top float64 left float64 } func New(width, height int) *canvas { c := &canvas{ Context: gg.NewContext(width, height), radiusX: 100.0, radiusY: 20.0, top: 200.0, } c.left = c.radiusX return c } func (c *canvas) drawSine() { c._drawSine(-math.Pi, 0) c._drawSine(0, math.Pi) } func (c *canvas) _drawSine(angle1, angle2 float64) { c.SetColor(color.Black) c.DrawEllipticalArc(c.left, c.top, c.radiusX, c.radiusY, angle1, angle2) c.left += c.radiusX * 2 c.Stroke() } func (c *canvas) drawline() { c.SetColor(color.RGBA{255, 0, 0, 255}) c.DrawLine(c.left-c.radiusX, c.top, c.left+c.radiusX*3, c.top) c.Stroke() } func printRadiant(angle float64) { fmt.Printf("%02.f° -> %0.2f\n", angle, gg.Radians(angle)) } func main() { printRadiant(0) // 0 printRadiant(90) // math.Pi/2 printRadiant(180) // math.Pi printRadiant(360) // 2 * math.Pi /* gg.NewContext(width, height) ctx := gg.NewContext(800, 800) */ ctx := New(1600, 1600) ctx.radiusY = 10 ctx.SetLineWidth(4) // ctx.SetLineWidth(4) ctx.drawline() ctx.SetLineWidth(2) ctx.drawSine() // ctx.drawline() ctx.drawSine() ctx.drawline() ctx.drawSine() // ctx.DrawEllipticalArc(200, 200, 100, 20, 0, math.Pi) // ctx.Stroke() // ctx.SetColor(color.RGBA{255, 0, 0, 255}) // ctx.SetLineWidth(2) // ctx.SetColor(color.Black) // ctx.SetColor(color.RGBA{255, 0, 0, 255}) // ctx.drawline() // ctx.DrawLine(100, 200, 300, 200) // ctx.Stroke() // ctx.drawline() // ctx.DrawLine(300, 200, 500, 200) // ctx.Stroke() // ctx.DrawEllipticalArc(400, 200, 100, 20, -math.Pi, 0) // ctx.Stroke() // ctx.DrawEllipse(x, y, rx, ry) gg.SavePNG("test.png", ctx.Image()) }
package main import "fmt" func main() { //var a int =0 //fmt.Scanf("%d",&a) for i:=0 ; i<11;i++{ fmt.Println(fib(i)) } //fib(13) } func fib(a int) int{ //var t int if a==0{ //fmt.Println(a) return 0 } else if a==1{ //fmt.Println(a) return 1 } else{ return fib(a-1)+fib(a-2) } }
/* RZFeeser | Alta3 Research Writing out to a YAML file */ package main import ( "fmt" "io/ioutil" "log" "gopkg.in/yaml.v3" ) type Record struct { Item string `yaml:"item"` Col string `yaml:"color"` Size string `yaml:"postage"` } type Config struct { Record Record `yaml:"Settings"` } func main() { config := Config{Record: Record{Item: "window", Col: "blue", Size: "small flat rate box"}} data, err := yaml.Marshal(&config) if err != nil { log.Fatal(err) } err2 := ioutil.WriteFile("config.yaml", data, 0) if err2 != nil { log.Fatal(err2) } fmt.Println("data written") }
// Copyright 2020, Jeff Alder // // 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 nr_yml import ( "github.com/stretchr/testify/assert" "io/ioutil" "os" "testing" ) func withContents(contents string, t *testing.T, test func(filename string, t *testing.T)) { tempFile, err := ioutil.TempFile(os.TempDir(), t.Name()+"*") assert.NoError(t, err) defer os.Remove(tempFile.Name()) _, err = tempFile.WriteString(contents) assert.NoError(t, err) test(tempFile.Name(), t) }
package openinstrument import ( "code.google.com/p/goprotobuf/proto" openinstrument_proto "code.google.com/p/open-instrument/proto" "encoding/binary" "errors" "fmt" "github.com/joaojeronimo/go-crc16" "io" "log" "os" ) var PROTO_MAGIC uint16 = 0xDEAD type ProtoFileReader struct { filename string file *os.File stat os.FileInfo } func ReadProtoFile(filename string) (*ProtoFileReader, error) { reader := new(ProtoFileReader) reader.filename = filename var err error reader.file, err = os.Open(filename) if err != nil { return nil, err } reader.stat, err = reader.file.Stat() if err != nil { reader.file.Close() return nil, err } return reader, nil } func (this *ProtoFileReader) Close() error { return this.file.Close() } func (this *ProtoFileReader) Tell() int64 { pos, _ := this.file.Seek(0, os.SEEK_CUR) return pos } func (this *ProtoFileReader) Seek(pos int64) int64 { npos, _ := this.file.Seek(pos, os.SEEK_SET) return npos } func (this *ProtoFileReader) Stat() (os.FileInfo, error) { return this.file.Stat() } func (this *ProtoFileReader) ReadAt(pos int64, message proto.Message) (int, error) { this.Seek(pos) return this.Read(message) } func (this *ProtoFileReader) ValueStreamReader(chan_size int) chan *openinstrument_proto.ValueStream { c := make(chan *openinstrument_proto.ValueStream, chan_size) go func() { for { value := new(openinstrument_proto.ValueStream) _, err := this.Read(value) if err == io.EOF { break } if err != nil { log.Println(err) break } c <- value } close(c) }() return c } func (this *ProtoFileReader) ValueStreamReaderUntil(max_pos uint64, chan_size int) chan *openinstrument_proto.ValueStream { c := make(chan *openinstrument_proto.ValueStream, chan_size) go func() { for uint64(this.Tell()) < max_pos { value := new(openinstrument_proto.ValueStream) _, err := this.Read(value) if err == io.EOF { break } if err != nil { log.Println(err) break } c <- value } close(c) }() return c } func (this *ProtoFileReader) Read(message proto.Message) (int, error) { for { pos := this.Tell() type header struct { Magic uint16 Length uint32 } var h header err := binary.Read(this.file, binary.LittleEndian, &h) if err != nil { if err == io.EOF { return 0, io.EOF } log.Printf("Error reading record header from recordlog: %s", err) return 0, err } // Read Magic header if h.Magic != PROTO_MAGIC { log.Printf("Protobuf delimeter at %s:%x does not match %#x", this.filename, pos, PROTO_MAGIC) continue } if int64(h.Length) >= this.stat.Size() { log.Printf("Chunk length %d at %s:%x is greater than file size %d", h.Length, this.filename, pos, this.stat.Size()) continue } // Read Proto buf := make([]byte, h.Length) n, err := this.file.Read(buf) if err != nil || uint32(n) != h.Length { log.Printf("Could not read %d bytes from file: %s", h.Length, err) return 0, io.EOF } // Read CRC var crc uint16 err = binary.Read(this.file, binary.LittleEndian, &crc) if err != nil { log.Printf("Error reading CRC from recordlog: %s", err) continue } checkcrc := crc16.Crc16(buf) if checkcrc != crc { //log.Printf("CRC %x does not match %x", crc, checkcrc) } // Decode and add proto if err = proto.Unmarshal(buf, message); err != nil { return 0, errors.New(fmt.Sprintf("Error decoding protobuf at %s:%x: %s", this.filename, pos, err)) } break } return 1, nil } func WriteProtoFile(filename string) (*ProtoFileWriter, error) { reader := new(ProtoFileWriter) reader.filename = filename var err error reader.file, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0664) if err != nil { return nil, err } reader.stat, err = reader.file.Stat() if err != nil { reader.file.Close() return nil, err } reader.file.Seek(0, os.SEEK_END) return reader, nil } type ProtoFileWriter struct { filename string file *os.File stat os.FileInfo } func (this *ProtoFileWriter) Close() error { return this.file.Close() } func (this *ProtoFileWriter) Tell() int64 { pos, _ := this.file.Seek(0, os.SEEK_CUR) return pos } func (this *ProtoFileWriter) Stat() (os.FileInfo, error) { return this.file.Stat() } func (this *ProtoFileWriter) Sync() error { return this.file.Sync() } func (this *ProtoFileWriter) WriteAt(pos int64, message proto.Message) (int, error) { this.file.Seek(pos, os.SEEK_SET) return this.Write(message) } func (this *ProtoFileWriter) Write(message proto.Message) (int, error) { data, err := proto.Marshal(message) if err != nil { return 0, errors.New(fmt.Sprintf("Marshaling error: %s", err)) } var buf = []interface{}{ uint16(PROTO_MAGIC), uint32(len(data)), data, uint16(0), } for _, v := range buf { err = binary.Write(this.file, binary.LittleEndian, v) if err != nil { return 0, errors.New(fmt.Sprintf("Error writing entry to protofile: %s", err)) } } return 1, nil }
package test import ( "database/sql" "encoding/json" "io/ioutil" "log" "net/http" "net/url" "os" "sort" "strings" "testing" _ "github.com/lib/pq" ) var ( baseAPI = "http://localhost:3000/api" ) type testStruct struct { arrayRequestBody url.Values stringRequestBody string expectedResult } type expectedResult struct { Success bool `json:"success"` Friends []string `json:"friends"` Count int `json:"count"` Recipients []string `json:"recipients"` } type user struct { Email string `json:"email"` } type userActions struct { Requestor string `json:"requestor"` Target string `json:"target"` Sender string `json:"sender"` Text string `json:"text"` } func init() { if os.Getenv("GO_ENV") == "test" { baseAPI = "http://localhost:3001/api" } } func TestCreateFriends(t *testing.T) { resetDB() testSamples := []map[string]interface{}{ { "friends": []string{"andy@example.com", "john@example.com"}, "success": true, }, { // duplicate request "friends": []string{"andy@example.com", "john@example.com"}, "success": false, }, { // same user "friends": []string{"andy@example.com", "andy@example.com"}, "success": false, }, { // insufficient user "friends": []string{"andy@example.com"}, "success": false, }, { // invalid user format "friends": []string{"andy", "john"}, "success": false, }, } testCases := []testStruct{} for _, testSample := range testSamples { friends := expectedResult{Friends: testSample["friends"].([]string)} jsonTestUser, err := json.Marshal(friends) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(jsonTestUser), expectedResult: expectedResult{ Success: testSample["success"].(bool), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } } } func TestGetFriendsList(t *testing.T) { resetDB() // add friends addFriends := []map[string]interface{}{ {"friends": []string{"andy@example.com", "john@example.com"}}, {"friends": []string{"andy@example.com", "lisa@example.com"}}, {"friends": []string{"john@example.com", "kate@example.com"}}, } for _, addFriend := range addFriends { // errors are not checked as these are tested in TestCreateFriends test json, _ := json.Marshal(expectedResult{Friends: addFriend["friends"].([]string)}) req, _ := http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(string(json))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") http.DefaultClient.Do(req) } // get friends testCases := []testStruct{} testUsers := []map[string]interface{}{ {"email": "andy@example.com", "friends": []string{"john@example.com", "lisa@example.com"}, "count": 2}, {"email": "john@example.com", "friends": []string{"andy@example.com", "kate@example.com"}, "count": 2}, {"email": "lisa@example.com", "friends": []string{"andy@example.com"}, "count": 1}, {"email": "sean@example.com", "friends": []string{}, "count": 0}, } for _, testUser := range testUsers { user := user{testUser["email"].(string)} jsonTestUser, err := json.Marshal(user) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(jsonTestUser), expectedResult: expectedResult{ Success: testUser["count"].(int) > 0, Friends: testUser["friends"].([]string), Count: testUser["count"].(int), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("GET", baseAPI+"/friends", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } if strings.Join(actualResult.Friends, ",") != strings.Join(testCase.expectedResult.Friends, ",") { t.Errorf("expecting %v but have %v", testCase.expectedResult.Friends, actualResult.Friends) } if actualResult.Count != testCase.expectedResult.Count { t.Errorf("expecting %v but have %v", testCase.expectedResult.Count, actualResult.Count) } } } func TestGetCommonFriendsList(t *testing.T) { resetDB() // add friends addFriends := []map[string]interface{}{ {"friends": []string{"andy@example.com", "john@example.com"}}, {"friends": []string{"andy@example.com", "common@example.com"}}, {"friends": []string{"andy@example.com", "lisa@example.com"}}, {"friends": []string{"andy@example.com", "sean@example.com"}}, {"friends": []string{"john@example.com", "andy@example.com"}}, {"friends": []string{"john@example.com", "common@example.com"}}, {"friends": []string{"john@example.com", "lisa@example.com"}}, {"friends": []string{"lisa@example.com", "sean@example.com"}}, } for _, addFriend := range addFriends { // errors are not checked as these are tested in TestCreateFriends test json, _ := json.Marshal(expectedResult{Friends: addFriend["friends"].([]string)}) req, _ := http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(string(json))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") http.DefaultClient.Do(req) } // get common friends testCases := []testStruct{} testUsers := []map[string]interface{}{ // andy and others { // andy - john common friends "friends": []string{"andy@example.com", "john@example.com"}, "commonFriends": []string{"common@example.com", "lisa@example.com"}, "count": 2, }, { // andy - common common friends "friends": []string{"andy@example.com", "common@example.com"}, "commonFriends": []string{"john@example.com"}, "count": 1, }, { // andy - lisa common friends "friends": []string{"andy@example.com", "lisa@example.com"}, "commonFriends": []string{"john@example.com", "sean@example.com"}, "count": 2, }, { // andy - sean common friends "friends": []string{"andy@example.com", "sean@example.com"}, "commonFriends": []string{"lisa@example.com"}, "count": 1, }, // john and others { // john - andy common friends - should be the same as andy - john "friends": []string{"john@example.com", "andy@example.com"}, "commonFriends": []string{"common@example.com", "lisa@example.com"}, "count": 2, }, { // john - common common friends "friends": []string{"john@example.com", "common@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, { // john - lisa common friends "friends": []string{"john@example.com", "lisa@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, { // john - sean common friends "friends": []string{"john@example.com", "sean@example.com"}, "commonFriends": []string{"lisa@example.com", "andy@example.com"}, "count": 2, }, // common and others { // common - andy common friends - should be the same as andy - common "friends": []string{"common@example.com", "andy@example.com"}, "commonFriends": []string{"john@example.com"}, "count": 1, }, { // common - john common friends - should be the same as john - common "friends": []string{"common@example.com", "john@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, { // common - lisa common friends "friends": []string{"common@example.com", "lisa@example.com"}, "commonFriends": []string{"andy@example.com", "john@example.com"}, "count": 2, }, { // common - sean common friends "friends": []string{"common@example.com", "sean@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, // lisa and others { // lisa - andy common friends - should be the same as andy - lisa "friends": []string{"lisa@example.com", "andy@example.com"}, "commonFriends": []string{"john@example.com", "sean@example.com"}, "count": 2, }, { // lisa - john common friends - should be the same as john - common "friends": []string{"lisa@example.com", "john@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, { // lisa - common common friends - should be the same as common - lisa "friends": []string{"lisa@example.com", "common@example.com"}, "commonFriends": []string{"andy@example.com", "john@example.com"}, "count": 2, }, { // lisa - sean common friends "friends": []string{"lisa@example.com", "sean@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, // sean and others { // sean - andy common friends - should be the same as sean - andy "friends": []string{"sean@example.com", "andy@example.com"}, "commonFriends": []string{"lisa@example.com"}, "count": 1, }, { // sean - john common friends - should be the same as john - sean "friends": []string{"sean@example.com", "john@example.com"}, "commonFriends": []string{"lisa@example.com", "andy@example.com"}, "count": 2, }, { // sean - common common friends - should be the same as common - sean "friends": []string{"common@example.com", "sean@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, { // sean - lisa common friends - should be the same as lisa - sean "friends": []string{"lisa@example.com", "sean@example.com"}, "commonFriends": []string{"andy@example.com"}, "count": 1, }, } for _, testUser := range testUsers { friends := expectedResult{Friends: testUser["friends"].([]string)} jsonTestUser, err := json.Marshal(friends) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(jsonTestUser), expectedResult: expectedResult{ Success: testUser["count"].(int) > 0, Friends: testUser["commonFriends"].([]string), Count: testUser["count"].(int), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("GET", baseAPI+"/friends/common", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } sort.Strings(actualResult.Friends) sort.Strings(testCase.expectedResult.Friends) if strings.Join(actualResult.Friends, ",") != strings.Join(testCase.expectedResult.Friends, ",") { t.Errorf("expecting %v but have %v", testCase.expectedResult.Friends, actualResult.Friends) } if actualResult.Count != testCase.expectedResult.Count { t.Errorf("expecting %v but have %v", testCase.expectedResult.Count, actualResult.Count) } } } func TestSubScribeUpdates(t *testing.T) { resetDB() testSubscribeSamples := []map[string]interface{}{ {"json": userActions{Requestor: "lisa@example.com", Target: "john@example.com"}, "expectedResult": true}, {"json": userActions{Requestor: "lisa@example.com", Target: "john@example.com"}, "expectedResult": false}, {"json": userActions{Requestor: "lisa@example.com"}, "expectedResult": false}, {"json": userActions{Target: "john@example.com"}, "expectedResult": false}, {"json": userActions{}, "expectedResult": false}, } testCases := []testStruct{} for _, testSubscribeSample := range testSubscribeSamples { json, err := json.Marshal(testSubscribeSample["json"]) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(json), expectedResult: expectedResult{ Success: testSubscribeSample["expectedResult"].(bool), }, }) } // subscribe updates for _, testCase := range testCases { req, err := http.NewRequest("POST", baseAPI+"/friends/subscribe", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } } // ensure no friends are created testUsers := []map[string]interface{}{ {"email": "lisa@example.com", "friends": []string{}, "count": 0}, {"email": "john@example.com", "friends": []string{}, "count": 0}, } testCases = []testStruct{} for _, testUser := range testUsers { user := user{testUser["email"].(string)} jsonTestUser, err := json.Marshal(user) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(jsonTestUser), expectedResult: expectedResult{ Success: testUser["count"].(int) > 0, Friends: testUser["friends"].([]string), Count: testUser["count"].(int), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("GET", baseAPI+"/friends", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } if strings.Join(actualResult.Friends, ",") != strings.Join(testCase.expectedResult.Friends, ",") { t.Errorf("expecting %v but have %v", testCase.expectedResult.Friends, actualResult.Friends) } if actualResult.Count != testCase.expectedResult.Count { t.Errorf("expecting %v but have %v", testCase.expectedResult.Count, actualResult.Count) } } } func TestBlockUpdates(t *testing.T) { resetDB() // block not connected users testSubscribeSamples := []map[string]interface{}{ {"json": userActions{Requestor: "andy@example.com", Target: "john@example.com"}, "expectedResult": true}, {"json": userActions{Requestor: "andy@example.com", Target: "john@example.com"}, "expectedResult": false}, {"json": userActions{Requestor: "andy@example.com"}, "expectedResult": false}, {"json": userActions{Target: "john@example.com"}, "expectedResult": false}, {"json": userActions{}, "expectedResult": false}, } testCases := []testStruct{} for _, testSubscribeSample := range testSubscribeSamples { json, err := json.Marshal(testSubscribeSample["json"]) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(json), expectedResult: expectedResult{ Success: testSubscribeSample["expectedResult"].(bool), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("POST", baseAPI+"/friends/block", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } } // ensure new friends conenction cannot be made // errors are skipped as they have been tested in the respecive tests jsonUsers, _ := json.Marshal(expectedResult{Friends: []string{"andy@example.com", "john@example.com"}}) req, _ := http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(string(jsonUsers))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, _ := http.DefaultClient.Do(req) bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != false { t.Errorf("expecting %v but have %v", false, actualResult.Success) } // ensure blocked target cannot subscribe to block requestor // errors are skipped as they have been tested in the respecive tests jsonUsers, _ = json.Marshal(userActions{Requestor: "andy@example.com", Target: "john@example.com"}) req, _ = http.NewRequest("POST", baseAPI+"/friends/subscribe", strings.NewReader(string(jsonUsers))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, _ = http.DefaultClient.Do(req) bodyBytes, _ = ioutil.ReadAll(res.Body) actualResult = expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != false { t.Errorf("expecting %v but have %v", false, actualResult.Success) } // add new friends to test blocking connected users // errors are skipped as they have been tested in the respective test jsonUsers, _ = json.Marshal(expectedResult{Friends: []string{"sean@example.com", "lisa@example.com"}}) req, _ = http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(string(jsonUsers))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, _ = http.DefaultClient.Do(req) // ensure new friends have been added successfully // errors are skipped as they have been tested in the respective test jsonUser, _ := json.Marshal(user{Email: "sean@example.com"}) req, _ = http.NewRequest("GET", baseAPI+"/friends", strings.NewReader(string(jsonUser))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, _ = http.DefaultClient.Do(req) bodyBytes, _ = ioutil.ReadAll(res.Body) actualResult = expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != true { t.Errorf("expecting %v but have %v", true, actualResult.Success) } if strings.Join(actualResult.Friends, ",") != strings.Join([]string{"lisa@example.com"}, ",") { t.Errorf("expecting %v but have %v", []string{"lisa@example.com"}, actualResult.Friends) } if actualResult.Count != 1 { t.Errorf("expecting %v but have %v", 1, actualResult.Count) } // test block connected users jsonUsers, _ = json.Marshal(userActions{Requestor: "sean@example.com", Target: "lisa@example.com"}) req, err := http.NewRequest("POST", baseAPI+"/friends/block", strings.NewReader(string(jsonUsers))) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err = http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ = ioutil.ReadAll(res.Body) actualResult = expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != true { t.Errorf("expecting %v but have %v %v", true, actualResult.Success, string(bodyBytes)) } // ensure blocked target is no longer a friend of the block requestor jsonUser, _ = json.Marshal(user{Email: "lisa@example.com"}) req, err = http.NewRequest("GET", baseAPI+"/friends", strings.NewReader(string(jsonUser))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err = http.DefaultClient.Do(req) bodyBytes, _ = ioutil.ReadAll(res.Body) actualResult = expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != false { t.Errorf("expecting %v but have %v", false, actualResult.Success) } if strings.Join(actualResult.Friends, ",") != strings.Join([]string{}, ",") { t.Errorf("expecting %v but have %v", []string{}, actualResult.Friends) } if actualResult.Count != 0 { t.Errorf("expecting %v but have %v", 0, actualResult.Count) } } func TestGetSubscribersList(t *testing.T) { resetDB() // add connections & subscribers // err and result checks are omitted intentionally newFriends := []map[string]interface{}{ {"friends": []string{"andy@example.com", "john@example.com"}}, {"friends": []string{"lisa@example.com", "john@example.com"}}, } for _, newFriend := range newFriends { json, _ := json.Marshal(expectedResult{Friends: newFriend["friends"].([]string)}) req, _ := http.NewRequest("POST", baseAPI+"/friends", strings.NewReader(string(json))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") http.DefaultClient.Do(req) } newSubscriber := userActions{Requestor: "sean@example.com", Target: "john@example.com"} jsonSubscriber, _ := json.Marshal(newSubscriber) req, _ := http.NewRequest("POST", baseAPI+"/friends/subscribe", strings.NewReader(string(jsonSubscriber))) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") http.DefaultClient.Do(req) testSamples := []map[string]interface{}{ { // with valid data "test": userActions{Sender: "john@example.com", Text: "Hello World! kate@example.com"}, "success": true, "recipients": []string{"andy@example.com", "lisa@example.com", "sean@example.com", "kate@example.com"}, }, { // with empty message "test": userActions{Sender: "john@example.com"}, "success": true, "recipients": []string{"andy@example.com", "lisa@example.com", "sean@example.com"}, }, { // with message without mentions "test": userActions{Sender: "john@example.com", Text: "Hello World!"}, "success": true, "recipients": []string{"andy@example.com", "lisa@example.com", "sean@example.com"}, }, { // with multiple mentions in message "test": userActions{Sender: "john@example.com", Text: "Hello World! kate@example.com, cathy@example.com and someone@example.com"}, "success": true, "recipients": []string{"andy@example.com", "lisa@example.com", "sean@example.com", "kate@example.com", "cathy@example.com", "someone@example.com"}, }, { // with invalid mention in message "test": userActions{Sender: "john@example.com", Text: "Hello World! kate@exam@ple.com"}, "success": true, "recipients": []string{"andy@example.com", "lisa@example.com", "sean@example.com"}, }, { // without subscriber but valid mention in message "test": userActions{Sender: "someone@example.com", Text: "Hello World! kate@example.com"}, "success": true, "recipients": []string{"kate@example.com"}, }, { // without sender "test": userActions{Text: "Hello World! kate@example.com"}, "success": false, "recipients": []string{}, }, { // blank "test": userActions{}, "success": false, "recipients": []string{}, }, } testCases := []testStruct{} for _, testSample := range testSamples { jsonTest, err := json.Marshal(testSample["test"]) if err != nil { t.Error(err) } testCases = append(testCases, testStruct{ stringRequestBody: string(jsonTest), expectedResult: expectedResult{ Success: testSample["success"].(bool), Recipients: testSample["recipients"].([]string), }, }) } for _, testCase := range testCases { req, err := http.NewRequest("GET", baseAPI+"/friends/subscribe", strings.NewReader(testCase.stringRequestBody)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") res, err := http.DefaultClient.Do(req) if err != nil { t.Error(err) } if res.StatusCode != 200 { t.Errorf("expecting status code of 200 but have %v", res.StatusCode) } bodyBytes, _ := ioutil.ReadAll(res.Body) actualResult := expectedResult{} if err := json.Unmarshal(bodyBytes, &actualResult); err != nil { t.Errorf("failed to unmarshal test result %v", err) } if actualResult.Success != testCase.expectedResult.Success { t.Errorf("expecting %v but have %v", testCase.expectedResult.Success, actualResult.Success) } sort.Strings(actualResult.Recipients) sort.Strings(testCase.expectedResult.Recipients) if strings.Join(actualResult.Recipients, ",") != strings.Join(testCase.expectedResult.Recipients, ",") { t.Errorf("expecting %v but have %v", testCase.expectedResult.Recipients, actualResult.Recipients) } } } func resetDB() { conninfo := "user=postgres host=db sslmode=disable dbname=friends_management_test" db, err := sql.Open("postgres", conninfo) if err != nil { log.Fatalf("error in db connection info %+v", err) } if err := db.Ping(); err != nil { log.Fatalf("error in pinging db %v", err) } db.Exec("DELETE FROM relationships") }
package filters import ( "net" ) type CidrFilter struct { cidrFilters []*net.IPNet } func NewCidrFilter(filters []string) (*CidrFilter, error) { cidrFilters := []*net.IPNet{} for _, filter := range filters { _, net, err := net.ParseCIDR(filter) if err != nil { return nil, err } cidrFilters = append(cidrFilters, net) } return &CidrFilter{cidrFilters: cidrFilters}, nil } func (f *CidrFilter) Select(ips []string) (string, bool) { for _, c := range f.cidrFilters { for _, val := range ips { ip := net.ParseIP(val) if ip == nil { continue } if c.Contains(ip) { return val, true } } } return "", false }
package logfmt import ( "io" "io/ioutil" "os" "runtime" "time" "github.com/bingoohuang/golog/pkg/rotate" "github.com/sirupsen/logrus" ) type LogrusEntry struct { *logrus.Entry EntryTraceID string } func (e LogrusEntry) Time() time.Time { return e.Entry.Time } func (e LogrusEntry) Level() string { return e.Entry.Level.String() } func (e LogrusEntry) TraceID() string { return e.EntryTraceID } func (e LogrusEntry) Fields() Fields { return Fields(e.Entry.Data) } func (e LogrusEntry) Message() string { return e.Entry.Message } func (e LogrusEntry) Caller() *runtime.Frame { return e.Entry.Caller } // LogrusOption defines the options to setup logrus logging system. type LogrusOption struct { Level string PrintColor bool PrintCaller bool Stdout bool Simple bool Layout string LogPath string Rotate string MaxSize int64 MaxAge time.Duration GzipAge time.Duration } type DiscardFormatter struct { } func (f DiscardFormatter) Format(_ *logrus.Entry) ([]byte, error) { return nil, nil } type LogrusFormatter struct { Formatter } func (f LogrusFormatter) Format(entry *logrus.Entry) ([]byte, error) { return f.Formatter.Format(&LogrusEntry{ Entry: entry, }), nil } // Setup setup log parameters. func (o LogrusOption) Setup(ll *logrus.Logger) (*Result, error) { l, err := logrus.ParseLevel(o.Level) if err != nil { l = logrus.InfoLevel } if ll == nil { ll = logrus.StandardLogger() } ll.SetLevel(l) var layout *Layout = nil if o.Layout != "" { if layout, err = NewLayout(o.Layout); err != nil { return nil, err } } writers := make([]*WriterFormatter, 0, 2) if o.Stdout { writers = append(writers, &WriterFormatter{ Writer: os.Stdout, Formatter: &LogrusFormatter{ Formatter: Formatter{ PrintColor: o.PrintColor, PrintCaller: o.PrintCaller, Simple: o.Simple, Layout: layout, }, }, }) } g := &Result{ Option: o, } if o.LogPath != "" { r, err := rotate.New(o.LogPath, rotate.WithRotateLayout(o.Rotate), rotate.WithMaxSize(o.MaxSize), rotate.WithMaxAge(o.MaxAge), rotate.WithGzipAge(o.GzipAge), ) if err != nil { panic(err) } g.Rotate = r writers = append(writers, &WriterFormatter{ Writer: r, Formatter: &LogrusFormatter{ Formatter: Formatter{ PrintColor: false, PrintCaller: o.PrintCaller, Simple: o.Simple, Layout: layout, }, }, }) } var ws []io.Writer for _, w := range writers { ws = append(ws, w) } g.Writer = io.MultiWriter(ws...) ll.SetFormatter(&DiscardFormatter{}) ll.AddHook(NewHook(writers)) ll.SetOutput(ioutil.Discard) ll.SetReportCaller(o.PrintCaller) return g, nil }
package lib import ( util "github.com/eagle7410/go_util/libs" "github.com/gorilla/mux" "net/http" ) func GetRouter() *mux.Router { r := mux.NewRouter() //TODO: clear Do somethining ... //r.PathPrefix("/static/").Handler( // staticAccess( // http.StripPrefix( // "/static/", // http.FileServer(http.Dir(path.Join(ENV.WorkDir, "/front/dist")))))) // Tech r.HandleFunc("/ping", util.Ping) r.HandleFunc("/", toIndex) return r } //TODO: clear //func staticAccess(handler http.Handler) http.Handler { // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // //TODO: clear Maybe check access // handler.ServeHTTP(w, r) // // }) //} func toIndex(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/ping", http.StatusSeeOther) }
package multiLanguageString type MultiLanguageString struct { Ja string `json:"ja"` En string `json:"en"` Fr string `json:"fr"` Ru string `json:"ru"` Zh string `json:"zh"` Ko string `json:"ko"` } func NewMultiLanguageString(japanese string) *MultiLanguageString { return &MultiLanguageString{Ja: japanese} }
/* Package create2 is a Golang library implementing serial commands for the iRobot Create2 robot. Basics The iRobot Create2 is a low cost mobile robot based on the Roomba 600 series robot repurposed for education and hacking. iRobot provides a well documented serial interface for controlling the Create2. */ package create2 import ( "fmt" "golang.org/x/sys/unix" "os" "time" "unsafe" ) type Create2 interface { Reset() error Safe() error Full() error SeekDock() error DrivePwn(int, int) error GetSensorData() (SensorData, error) } type Create2exec struct { serial *os.File S *os.File } func Connect(serialConnectionStr string) (*Create2exec, error) { // Set up connection to the serial port f, err := os.OpenFile(serialConnectionStr, unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0666) if err != nil { return &Create2exec{}, err } rate := uint32(unix.B115200) // 115200 is the default Baud rate of the Create 2 arm cflagToUse := unix.CREAD | unix.CLOCAL | rate // We use rational defaults from https://github.com/tarm/serial/blob/master/serial_linux.go cflagToUse |= unix.CS8 // Get Unix file descriptor fd := f.Fd() t := unix.Termios{ Iflag: unix.IGNPAR, Cflag: cflagToUse, Ispeed: rate, Ospeed: rate, } t.Cc[unix.VMIN] = uint8(1) t.Cc[unix.VTIME] = uint8(10) // Default timeout is 1s _, _, errno := unix.Syscall6( unix.SYS_IOCTL, uintptr(fd), uintptr(unix.TCSETS), uintptr(unsafe.Pointer(&t)), 0, 0, 0, ) if errno != 0 { return &Create2exec{}, err } newCreate2 := Create2exec{serial: f, S: f} // Start the create2 var start byte = 128 _, err = newCreate2.serial.Write([]byte{start}) if err != nil { return &newCreate2, err } // Return the Create2 object return &newCreate2, nil } func (create2 *Create2exec) Reset() error { // First we reset the bot var command byte = 7 _, err := create2.serial.Write([]byte{command}) if err != nil { return err } // After we reset, we have to start the interface again var start byte = 128 _, err = create2.serial.Write([]byte{start}) if err != nil { return err } return nil } func (create2 *Create2exec) Safe() error { var command byte = 131 _, err := create2.serial.Write([]byte{command}) if err != nil { return err } // Requires a sleep before commands are issued time.Sleep(1 * time.Second) return nil } func (create2 *Create2exec) Full() error { var command byte = 132 _, err := create2.serial.Write([]byte{command}) if err != nil { return err } // Requires a sleep before commands are issued time.Sleep(1 * time.Second) return nil } func (create2 *Create2exec) SeekDock() error { var command byte = 143 _, err := create2.serial.Write([]byte{command}) if err != nil { return err } return nil } func (create2 *Create2exec) DrivePwm(right, left int) error { // First, check if the values are within tolerable range. if right > 255 || right < -255 { return fmt.Errorf("Right drive values must be between 500 and -500. Got: %d", right) } if left > 255 || left < -255 { return fmt.Errorf("Left drive values must be between 500 and -500. Got: %d", left) } // Append into a command var opcode byte = 146 command := []byte{opcode} var rightInt16 int16 = int16(right) var rightH, rightL uint8 = uint8(rightInt16 >> 8), uint8(rightInt16 & 0xff) command = append(command, rightH) command = append(command, rightL) var lefInt16 int16 = int16(left) var leftH, leftL uint8 = uint8(lefInt16 >> 8), uint8(lefInt16 & 0xff) command = append(command, leftH) command = append(command, leftL) _, err := create2.serial.Write(command) if err != nil { return err } return nil } func (create2 *Create2exec) GetSensors() (SensorData, error) { var command byte = 142 _, err := create2.serial.Write([]byte{command, 100}) if err != nil { return SensorData{}, err } // wait 15ms before update var sensorBytes = make([]byte, 80) time.Sleep(15 * time.Millisecond) _, err = create2.serial.Read(sensorBytes) if err != nil { return SensorData{}, err } sensorData, err := decodeFullPacket(sensorBytes) if err != nil { return sensorData, err } return sensorData, nil }
package factory import ( "database/sql" "fmt" "log" "otoboni.com.br/customer-webservice/model" ) func GetCustomerById(id string) (model.Customer, error) { db := ConnectToDb() var cust model.Customer row := db.QueryRow("SELECT customerid, code, customername, email, address, phone, city, country FROM customer WHERE code = $1", id) defer db.Close() if err := row.Scan(&cust.CustomerId, &cust.Code, &cust.CustomerName, &cust.Email, &cust.Address, &cust.Phone, &cust.City, &cust.Country); err != nil { if err == sql.ErrNoRows { return cust, fmt.Errorf("GetById %s: customer not found", id) } return cust, fmt.Errorf("GetById %s: %s", id, err) } return cust, nil } func GetCustomer() ([]model.Customer, error) { db := ConnectToDb() var customers []model.Customer rows, err := db.Query("SELECT customerid, code, customername, email, address, phone, city, country FROM customer") if err != nil { return nil, fmt.Errorf("%s: %w", "Get", err) } defer rows.Close() defer db.Close() for rows.Next() { var cust model.Customer if err := rows.Scan(&cust.CustomerId, &cust.Code, &cust.CustomerName, &cust.Email, &cust.Address, &cust.Phone, &cust.City, &cust.Country); err != nil { return nil, fmt.Errorf("%s: %w", "Get", err) } customers = append(customers, cust) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("%s: %w", "Get", err) } return customers, nil } func AddCustomer(customer model.Customer) error { var cust model.Customer cust, err := GetCustomerById(customer.Code) if cust.Code != "" { log.Println(err) return fmt.Errorf("%s: %s", "Add: Customer already exists", cust.CustomerName) } db := ConnectToDb() tx, err := db.Begin() if err != nil { return fmt.Errorf("%s: %w", "Add", err) } _, err = tx.Exec("INSERT INTO customer (code, customername, email, address, phone, city, country, createdat) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())", customer.Code, customer.CustomerName, customer.Email, customer.Address, customer.Phone, customer.City, customer.Country) defer db.Close() if err != nil { tx.Rollback() return fmt.Errorf("%s: %w", "Add", err) } tx.Commit() return nil } func UpdateCustomer(customer model.Customer) error { var cust model.Customer cust, err := GetCustomerById(customer.Code) if err != nil { log.Println(cust) return fmt.Errorf("%s: %w", "Update", err) } db := ConnectToDb() _, err = db.Exec("UPDATE customer SET customername = $2, email = $3, address = $4, phone = $5, city = $6, country = $7, modifiedat = NOW() WHERE code = $1", customer.Code, customer.CustomerName, customer.Email, customer.Address, customer.Phone, customer.City, customer.Country) defer db.Close() if err != nil { return fmt.Errorf("%s: %w", "Update", err) } return nil } func DeleteCustomer(id string) error { var cust model.Customer cust, err := GetCustomerById(id) if err != nil { log.Println(cust) return fmt.Errorf("%s: %w", "Delete", err) } db := ConnectToDb() _, err = db.Exec("DELETE FROM customer WHERE code = $1", id) defer db.Close() if err != nil { return fmt.Errorf("%s: %w", "Delete", err) } return nil }
package tests import ( "github.com/unio-framework/go" "testing" ) func TestJsonSearchQuery(t *testing.T) { stringQuery := "{\"filter\":{\"packageName\":{\"in\":[\"com.unio.test\"]}}}" query, _ := unio.Utils.JSONParse(stringQuery) want := unio.JSONObject{ "filter": map[string]interface{}{ "packageName": map[string]interface{}{ "$in": []string{ "com.unio.test", }, }, }, } got := unio.Searchs.SearchFormat(query, nil) result(t, want["filter"] != nil, got["filter"] != nil) } func TestStringSearchQuery(t *testing.T) { stringQuery := "{\"packageName\":{\"in\":[\"com.unio.test\"]}}" query, _ := unio.Utils.JSONParse(stringQuery) js := unio.JSONObject{ "filter": query, } want := unio.JSONObject{ "filter": map[string]interface{}{ "packageName": map[string]interface{}{ "$in": []string{ "com.unio.test", }, }, }, } got := unio.Searchs.SearchFormat(js, nil) result(t, want["filter"] != nil, got["filter"] != nil) }
package main import ( "fmt" . "leetcode" ) func main() { fmt.Println(pairSum(NewListNode(1, 2, 3, 4))) } func pairSum(head *ListNode) int { var reverse func(head *ListNode) *ListNode reverse = func(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } newHead := reverse(head.Next) head.Next.Next = head head.Next = nil return newHead } ln := 0 cur := head for cur != nil { ln++ cur = cur.Next } cur = head for i := 0; i < ln/2-1; i++ { cur = cur.Next } l2 := cur.Next cur.Next = nil l2 = reverse(l2) var ans int for i := 0; i < ln/2; i++ { if d := head.Val + l2.Val; d > ans { ans = d } head = head.Next l2 = l2.Next } return ans } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func pairSum2(head *ListNode) int { ls := make([]int, 0) for head != nil { ls = append(ls, head.Val) head = head.Next } var ans int for l, r := 0, len(ls)-1; l < r; l, r = l+1, r-1 { if d := ls[l] + ls[r]; d > ans { ans = d } } return ans }
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package p2p import ( "bufio" "github.com/reed/errors" "github.com/reed/log" "github.com/reed/p2p/discover" "github.com/sirupsen/logrus" "github.com/tendermint/tmlibs/common" "net" "sync" "time" ) const ( dialTimeout = 3 * time.Second handshakeTimeout = 5 * time.Second peerUpdateInterval = time.Second * 10 connectionSize = 30 ) var ( addPeerFromAcceptErr = errors.New("failed to add peer from accept") dialErr = errors.New("failed to dial") ) type Network struct { common.BaseService pm *PeerMap dialing *PeerDialing table *discover.Table ourNodeInfo *NodeInfo handlerServ Handler acceptCh <-chan net.Conn disConnCh chan string quitCh chan struct{} } func NewNetWork(ourNode *discover.Node, t *discover.Table, acceptCh <-chan net.Conn, handlerServ Handler) (*Network, error) { n := &Network{ pm: NewPeerMap(), dialing: NewPeerDialing(), table: t, ourNodeInfo: NewOurNodeInfo(ourNode.ID, ourNode.IP, ourNode.TCPPort), handlerServ: handlerServ, acceptCh: acceptCh, disConnCh: make(chan string), quitCh: make(chan struct{}), } n.BaseService = *common.NewBaseService(nil, "network", n) return n, nil } func (n *Network) OnStart() error { go n.loop() go n.loopFillPeer() log.Logger.Info("★★p2p.TCP Network Server OnStart") return nil } func (n *Network) OnStop() { close(n.quitCh) for _, v := range n.pm.peers { n.releasePeer(v) } close(n.disConnCh) log.Logger.Info("★★p2p.TCP Network Server OnStop") } func (n *Network) loop() { for { select { case c, ok := <-n.acceptCh: if !ok { return } log.Logger.WithFields(logrus.Fields{"remote addr": c.RemoteAddr().String()}).Info("->accept peer") if err := n.addPeerFromAccept(c); err != nil { log.Logger.Error(err) } case addr := <-n.disConnCh: log.Logger.WithField("peerAddr", addr).Info("remove disconnection peer") peer := n.pm.get(addr) if peer != nil { n.releasePeer(peer) } case <-n.quitCh: log.Logger.Info("[loop] quit") return } } } func (n *Network) loopFillPeer() { timer := time.NewTimer(peerUpdateInterval) for { select { case <-timer.C: n.fillPeer() timer.Reset(peerUpdateInterval) case <-n.quitCh: log.Logger.Info("[loopFillPeer] quit") return } } } func (n *Network) addPeerFromAccept(conn net.Conn) error { if n.pm.peerCount() >= connectionSize { _ = conn.Close() return errors.Wrap(addPeerFromAcceptErr, "enough peers already exist") } return n.connectPeer(conn) } func (n *Network) fillPeer() { log.Logger.Debug("time to fill Peer") nodes := n.table.GetRandNodes(activelyPeerCount, n.pm.IDs()) if len(nodes) == 0 { log.Logger.Debug("no available node to dial") return } var wg sync.WaitGroup var waitForProcess []string for _, node := range nodes { addr := toAddress(node.IP, node.TCPPort) if n.dialing.exist(addr) { log.Logger.WithField("peerAddr", addr).Info("peer is dialing") continue } else { waitForProcess = append(waitForProcess, addr) } } wg.Add(len(waitForProcess)) for _, addr := range waitForProcess { go n.dialPeerAndAdd(addr, &wg) } wg.Wait() } func (n *Network) dialPeerAndAdd(addr string, wg *sync.WaitGroup) { defer func() { n.dialing.remove(addr) wg.Done() }() n.dialing.add(addr) rawConn, err := n.dial(addr) if err != nil { log.Logger.WithField("peerAddr", addr).Errorf("failt to dial peer:%v", err) return } if err = n.connectPeer(rawConn); err != nil { log.Logger.WithField("peerAddr", addr).Errorf("failed to connect peer: %v", err) return } } func (n *Network) connectPeer(rawConn net.Conn) error { nodeInfo, err := n.handshake(rawConn) if err != nil { return err } peer := NewPeer(n.ourNodeInfo, nodeInfo, n.disConnCh, rawConn, n.handlerServ) if err = peer.Start(); err != nil { return err } n.pm.add(peer) log.Logger.WithField("peerAddr", peer.nodeInfo.RemoteAddr).Info("Add a new peer and started.") return nil } func (n *Network) releasePeer(peer *Peer) { if err := peer.Stop(); err != nil { log.Logger.WithField("peerAddr", peer.nodeInfo.RemoteAddr).Error(err) } n.pm.remove(peer.nodeInfo.RemoteAddr) } func (n *Network) dial(address string) (net.Conn, error) { conn, err := net.DialTimeout("tcp", address, dialTimeout) if err != nil { return nil, errors.Wrap(dialErr, err) } return conn, nil } func (n *Network) handshake(conn net.Conn) (*NodeInfo, error) { log.Logger.WithFields(logrus.Fields{"self": n.ourNodeInfo.RemoteAddr, "remote": conn.RemoteAddr()}).Debug("ready to handshake") if err := conn.SetDeadline(time.Now().Add(handshakeTimeout)); err != nil { return nil, err } if err := write(conn, []byte{handshakeCode}); err != nil { return nil, err } input := bufio.NewScanner(conn) for input.Scan() { switch b := input.Bytes(); b[0] { case handshakeCode: log.Logger.WithFields(logrus.Fields{"self": n.ourNodeInfo.RemoteAddr, "remote": conn.RemoteAddr()}).Debug("process [handshakeCode]") if err := writeOurNodeInfo(conn, n.ourNodeInfo); err != nil { log.Logger.Error(err) } case handshakeRespCode: log.Logger.WithFields(logrus.Fields{"self": n.ourNodeInfo.RemoteAddr, "remote": conn.RemoteAddr()}).Debug("process [handshakeRespCode]") return NewNodeInfoFromBytes(b[1:], conn) } } if input.Err() != nil { return nil, input.Err() } return nil, errors.New("handshake error") }
package partyrobot import ( "fmt" ) // Welcome greets a person by name. func Welcome(name string) string { return "Welcome to my party, " + name + "!" } // HappyBirthday wishes happy birthday to the birthday person and stands out their age. func HappyBirthday(name string, age int) string { return fmt.Sprintf("Happy birthday %s! You are now %d years old!", name, age) } // AssignTable assigns a table to each guest. func AssignTable(name string, table int, neighbour, direction string, distance float64) string { m := Welcome(name) m += fmt.Sprintf("\nYou have been assigned to table %X. ", table) m += fmt.Sprintf("Your table is %s, exactly %.1f meters from here.\n", direction, distance) m += fmt.Sprintf("You will be sitting next to %s.", neighbour) return m }
package v1beta8 import ( "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config" ) // Version is the current api version const Version string = "v1beta8" // GetVersion returns the version func (c *Config) GetVersion() string { return Version } // New creates a new config object func New() config.Config { return NewRaw() } // NewRaw creates a new config object func NewRaw() *Config { return &Config{ Version: Version, Dev: &DevConfig{}, Images: map[string]*ImageConfig{}, } } // Config defines the configuration type Config struct { Version string `yaml:"version"` Images map[string]*ImageConfig `yaml:"images,omitempty"` Deployments []*DeploymentConfig `yaml:"deployments,omitempty"` Dev *DevConfig `yaml:"dev,omitempty"` Dependencies []*DependencyConfig `yaml:"dependencies,omitempty"` Hooks []*HookConfig `yaml:"hooks,omitempty"` Commands []*CommandConfig `yaml:"commands,omitempty"` Vars []*Variable `yaml:"vars,omitempty"` Profiles []*ProfileConfig `yaml:"profiles,omitempty"` } // ImageConfig defines the image specification type ImageConfig struct { Image string `yaml:"image"` Tags []string `yaml:"tags,omitempty"` Dockerfile string `yaml:"dockerfile,omitempty"` Context string `yaml:"context,omitempty"` Entrypoint []string `yaml:"entrypoint,omitempty"` Cmd []string `yaml:"cmd,omitempty"` CreatePullSecret *bool `yaml:"createPullSecret,omitempty"` Build *BuildConfig `yaml:"build,omitempty"` } // BuildConfig defines the build process for an image type BuildConfig struct { Docker *DockerConfig `yaml:"docker,omitempty"` Kaniko *KanikoConfig `yaml:"kaniko,omitempty"` Custom *CustomConfig `yaml:"custom,omitempty"` Disabled *bool `yaml:"disabled,omitempty"` } // DockerConfig tells the DevSpace CLI to build with Docker on Minikube or on localhost type DockerConfig struct { PreferMinikube *bool `yaml:"preferMinikube,omitempty"` SkipPush *bool `yaml:"skipPush,omitempty"` DisableFallback *bool `yaml:"disableFallback,omitempty"` UseBuildKit *bool `yaml:"useBuildKit,omitempty"` Args []string `yaml:"args,omitempty"` Options *BuildOptions `yaml:"options,omitempty"` } // KanikoConfig tells the DevSpace CLI to build with Docker on Minikube or on localhost type KanikoConfig struct { // if a cache repository should be used. defaults to true Cache *bool `yaml:"cache,omitempty"` // the snapshot mode kaniko should use. defaults to time SnapshotMode string `yaml:"snapshotMode,omitempty"` // the image name of the kaniko pod to use Image string `yaml:"image,omitempty"` // additional arguments that should be passed to kaniko Args []string `yaml:"args,omitempty"` // the namespace where the kaniko pod should be run Namespace string `yaml:"namespace,omitempty"` // if true pushing to insecure registries is allowed Insecure *bool `yaml:"insecure,omitempty"` // the pull secret to mount by default PullSecret string `yaml:"pullSecret,omitempty"` // additional mounts that will be added to the build pod AdditionalMounts []KanikoAdditionalMount `yaml:"additionalMounts,omitempty"` // other build options that will be passed to the kaniko pod Options *BuildOptions `yaml:"options,omitempty"` } // KanikoAdditionalMount tells devspace how the additional mount of the kaniko pod should look like type KanikoAdditionalMount struct { // The secret that should be mounted Secret *KanikoAdditionalMountSecret `yaml:"secret,omitempty"` // The configMap that should be mounted ConfigMap *KanikoAdditionalMountConfigMap `yaml:"configMap,omitempty"` // Mounted read-only if true, read-write otherwise (false or unspecified). // Defaults to false. // +optional ReadOnly bool `yaml:"readOnly,omitempty"` // Path within the container at which the volume should be mounted. Must // not contain ':'. MountPath string `yaml:"mountPath,omitempty"` // Path within the volume from which the container's volume should be mounted. // Defaults to "" (volume's root). // +optional SubPath string `yaml:"subPath,omitempty"` } type KanikoAdditionalMountConfigMap struct { // Name of the configmap // +optional Name string `yaml:"name,omitempty"` // If unspecified, each key-value pair in the Data field of the referenced // ConfigMap will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be // projected into the specified paths, and unlisted keys will not be // present. If a key is specified which is not present in the ConfigMap, // the volume setup will error unless it is marked optional. Paths must be // relative and may not contain the '..' path or start with '..'. // +optional Items []KanikoAdditionalMountKeyToPath `yaml:"items,omitempty"` // Optional: mode bits to use on created files by default. Must be a // value between 0 and 0777. Defaults to 0644. // Directories within the path are not affected by this setting. // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. // +optional DefaultMode *int32 `yaml:"defaultMode,omitempty"` } type KanikoAdditionalMountSecret struct { // Name of the secret in the pod's namespace to use. // More info: https://kubernetes.io/docs/concepts/storage/volumes#secret // +optional Name string `yaml:"name"` // If unspecified, each key-value pair in the Data field of the referenced // Secret will be projected into the volume as a file whose name is the // key and content is the value. If specified, the listed keys will be // projected into the specified paths, and unlisted keys will not be // present. If a key is specified which is not present in the Secret, // the volume setup will error unless it is marked optional. Paths must be // relative and may not contain the '..' path or start with '..'. // +optional Items []KanikoAdditionalMountKeyToPath `yaml:"items,omitempty"` // Optional: mode bits to use on created files by default. Must be a // value between 0 and 0777. Defaults to 0644. // Directories within the path are not affected by this setting. // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. // +optional DefaultMode *int32 `yaml:"defaultMode,omitempty"` } type KanikoAdditionalMountKeyToPath struct { // The key to project. Key string `yaml:"key"` // The relative path of the file to map the key to. // May not be an absolute path. // May not contain the path element '..'. // May not start with the string '..'. Path string `yaml:"path"` // Optional: mode bits to use on this file, must be a value between 0 // and 0777. If not specified, the volume defaultMode will be used. // This might be in conflict with other options that affect the file // mode, like fsGroup, and the result can be other mode bits set. // +optional Mode *int32 `yaml:"mode,omitempty"` } // CustomConfig tells the DevSpace CLI to build with a custom build script type CustomConfig struct { Command string `yaml:"command,omitempty"` AppendArgs []string `yaml:"appendArgs,omitempty"` Args []string `yaml:"args,omitempty"` ImageFlag string `yaml:"imageFlag,omitempty"` OnChange []string `yaml:"onChange,omitempty"` } // BuildOptions defines options for building Docker images type BuildOptions struct { Target string `yaml:"target,omitempty"` Network string `yaml:"network,omitempty"` BuildArgs map[string]*string `yaml:"buildArgs,omitempty"` } // DeploymentConfig defines the configuration how the devspace should be deployed type DeploymentConfig struct { Name string `yaml:"name"` Namespace string `yaml:"namespace,omitempty"` Helm *HelmConfig `yaml:"helm,omitempty"` Kubectl *KubectlConfig `yaml:"kubectl,omitempty"` } // ComponentConfig holds the component information type ComponentConfig struct { InitContainers []*ContainerConfig `yaml:"initContainers,omitempty"` Containers []*ContainerConfig `yaml:"containers,omitempty"` Labels map[string]string `yaml:"labels,omitempty"` Annotations map[string]string `yaml:"annotations,omitempty"` Volumes []*VolumeConfig `yaml:"volumes,omitempty"` Service *ServiceConfig `yaml:"service,omitempty"` ServiceName string `yaml:"serviceName,omitempty"` Ingress *IngressConfig `yaml:"ingress,omitempty"` Replicas *int `yaml:"replicas,omitempty"` Autoscaling *AutoScalingConfig `yaml:"autoScaling,omitempty"` RollingUpdate *RollingUpdateConfig `yaml:"rollingUpdate,omitempty"` PullSecrets []*string `yaml:"pullSecrets,omitempty"` PodManagementPolicy string `yaml:"podManagementPolicy,omitempty"` } // ContainerConfig holds the configurations of a container type ContainerConfig struct { Name string `yaml:"name,omitempty"` Image string `yaml:"image,omitempty"` Command []string `yaml:"command,omitempty"` Args []string `yaml:"args,omitempty"` Stdin bool `yaml:"stdin,omitempty"` TTY bool `yaml:"tty,omitempty"` Env []map[interface{}]interface{} `yaml:"env,omitempty"` VolumeMounts []*VolumeMountConfig `yaml:"volumeMounts,omitempty"` Resources map[interface{}]interface{} `yaml:"resources,omitempty"` LivenessProbe map[interface{}]interface{} `yaml:"livenessProbe,omitempty"` ReadinessProbe map[interface{}]interface{} `yaml:"readinessProbe,omitempty"` } // VolumeMountConfig holds the configuration for a specific mount path type VolumeMountConfig struct { ContainerPath string `yaml:"containerPath,omitempty"` Volume *VolumeMountVolumeConfig `yaml:"volume,omitempty"` } // VolumeMountVolumeConfig holds the configuration for a specfic mount path volume type VolumeMountVolumeConfig struct { Name string `yaml:"name,omitempty"` SubPath string `yaml:"subPath,omitempty"` ReadOnly *bool `yaml:"readOnly,omitempty"` } // VolumeConfig holds the configuration for a specific volume type VolumeConfig struct { Name string `yaml:"name,omitempty"` Labels map[string]string `yaml:"labels,omitempty"` Annotations map[string]string `yaml:"annotations,omitempty"` Size string `yaml:"size,omitempty"` ConfigMap map[interface{}]interface{} `yaml:"configMap,omitempty"` Secret map[interface{}]interface{} `yaml:"secret,omitempty"` } // ServiceConfig holds the configuration of a component service type ServiceConfig struct { Name string `yaml:"name,omitempty"` Labels map[string]string `yaml:"labels,omitempty"` Annotations map[string]string `yaml:"annotations,omitempty"` Type string `yaml:"type,omitempty"` Ports []*ServicePortConfig `yaml:"ports,omitempty"` ExternalIPs []string `yaml:"externalIPs,omitempty"` } // ServicePortConfig holds the port configuration of a component service type ServicePortConfig struct { Port *int `yaml:"port,omitempty"` ContainerPort *int `yaml:"containerPort,omitempty"` Protocol string `yaml:"protocol,omitempty"` } // IngressConfig holds the configuration of a component ingress type IngressConfig struct { Name string `yaml:"name,omitempty"` Labels map[string]string `yaml:"labels,omitempty"` Annotations map[string]string `yaml:"annotations,omitempty"` TLS string `yaml:"tls,omitempty"` TLSClusterIssuer string `yaml:"tlsClusterIssuer,omitempty"` IngressClass string `yaml:"ingressClass,omitempty"` Rules []*IngressRuleConfig `yaml:"rules,omitempty"` } // IngressRuleConfig holds the port configuration of a component service type IngressRuleConfig struct { Host string `yaml:"host,omitempty"` TLS string `yaml:"tls,omitempty"` // DEPRECATED Path string `yaml:"path,omitempty"` ServicePort *int `yaml:"servicePort,omitempty"` ServiceName string `yaml:"serviceName,omitempty"` } // AutoScalingConfig holds the autoscaling config of a component type AutoScalingConfig struct { Horizontal *AutoScalingHorizontalConfig `yaml:"horizontal,omitempty"` } // AutoScalingHorizontalConfig holds the horizontal autoscaling config of a component type AutoScalingHorizontalConfig struct { MaxReplicas *int `yaml:"maxReplicas,omitempty"` AverageCPU string `yaml:"averageCPU,omitempty"` AverageRelativeCPU string `yaml:"averageRelativeCPU,omitempty"` AverageMemory string `yaml:"averageMemory,omitempty"` AverageRelativeMemory string `yaml:"averageRelativeMemory,omitempty"` } // RollingUpdateConfig holds the configuration for rolling updates type RollingUpdateConfig struct { Enabled *bool `yaml:"enabled,omitempty"` MaxSurge string `yaml:"maxSurge,omitempty"` MaxUnavailable string `yaml:"maxUnavailable,omitempty"` Partition *int `yaml:"partition,omitempty"` } // HelmConfig defines the specific helm options used during deployment type HelmConfig struct { Chart *ChartConfig `yaml:"chart,omitempty"` ComponentChart *bool `yaml:"componentChart,omitempty"` Values map[interface{}]interface{} `yaml:"values,omitempty"` ValuesFiles []string `yaml:"valuesFiles,omitempty"` ReplaceImageTags *bool `yaml:"replaceImageTags,omitempty"` Wait bool `yaml:"wait,omitempty"` Timeout *int64 `yaml:"timeout,omitempty"` Force bool `yaml:"force,omitempty"` Atomic bool `yaml:"atomic,omitempty"` CleanupOnFail bool `yaml:"cleanupOnFail,omitempty"` Recreate bool `yaml:"recreate,omitempty"` DisableHooks bool `yaml:"disableHooks,omitempty"` Driver string `yaml:"driver,omitempty"` Path string `yaml:"path,omitempty"` V2 bool `yaml:"v2,omitempty"` TillerNamespace string `yaml:"tillerNamespace,omitempty"` } // ChartConfig defines the helm chart options type ChartConfig struct { Name string `yaml:"name,omitempty"` Version string `yaml:"version,omitempty"` RepoURL string `yaml:"repo,omitempty"` Username string `yaml:"username,omitempty"` Password string `yaml:"password,omitempty"` } // KubectlConfig defines the specific kubectl options used during deployment type KubectlConfig struct { Manifests []string `yaml:"manifests,omitempty"` Kustomize *bool `yaml:"kustomize,omitempty"` KustomizeArgs []string `yaml:"kustomizeArgs,omitempty"` ReplaceImageTags *bool `yaml:"replaceImageTags,omitempty"` DeleteArgs []string `yaml:"deleteArgs,omitempty"` CreateArgs []string `yaml:"createArgs,omitempty"` ApplyArgs []string `yaml:"applyArgs,omitempty"` CmdPath string `yaml:"cmdPath,omitempty"` } // DevConfig defines the devspace deployment type DevConfig struct { Ports []*PortForwardingConfig `yaml:"ports,omitempty"` Open []*OpenConfig `yaml:"open,omitempty"` Sync []*SyncConfig `yaml:"sync,omitempty"` Logs *LogsConfig `yaml:"logs,omitempty"` AutoReload *AutoReloadConfig `yaml:"autoReload,omitempty"` Interactive *InteractiveConfig `yaml:"interactive,omitempty"` } // PortForwardingConfig defines the ports for a port forwarding to a DevSpace type PortForwardingConfig struct { ImageName string `yaml:"imageName,omitempty"` LabelSelector map[string]string `yaml:"labelSelector,omitempty"` Namespace string `yaml:"namespace,omitempty"` PortMappings []*PortMapping `yaml:"forward,omitempty"` } // PortMapping defines the ports for a PortMapping type PortMapping struct { LocalPort *int `yaml:"port"` RemotePort *int `yaml:"remotePort,omitempty"` BindAddress string `yaml:"bindAddress,omitempty"` } // OpenConfig defines what to open after services have been started type OpenConfig struct { URL string `yaml:"url,omitempty"` } // SyncConfig defines the paths for a SyncFolder type SyncConfig struct { ImageName string `yaml:"imageName,omitempty"` LabelSelector map[string]string `yaml:"labelSelector,omitempty"` ContainerName string `yaml:"containerName,omitempty"` Namespace string `yaml:"namespace,omitempty"` LocalSubPath string `yaml:"localSubPath,omitempty"` ContainerPath string `yaml:"containerPath,omitempty"` ExcludePaths []string `yaml:"excludePaths,omitempty"` DownloadExcludePaths []string `yaml:"downloadExcludePaths,omitempty"` UploadExcludePaths []string `yaml:"uploadExcludePaths,omitempty"` InitialSync InitialSyncStrategy `yaml:"initialSync,omitempty"` DisableDownload *bool `yaml:"disableDownload,omitempty"` DisableUpload *bool `yaml:"disableUpload,omitempty"` WaitInitialSync *bool `yaml:"waitInitialSync,omitempty"` BandwidthLimits *BandwidthLimits `yaml:"bandwidthLimits,omitempty"` OnUpload *SyncOnUpload `yaml:"onUpload,omitempty"` OnDownload *SyncOnDownload `yaml:"onDownload,omitempty"` } // SyncOnUpload defines the struct for the command that should be executed when files / folders are uploaded type SyncOnUpload struct { ExecRemote *SyncExecCommand `yaml:"execRemote,omitempty"` } // SyncOnDownload defines the struct for the command that should be executed when files / folders are downloaded type SyncOnDownload struct { ExecLocal *SyncExecCommand `yaml:"execLocal,omitempty"` } // SyncExecCommand holds the configuration of commands that should be executed when files / folders are change type SyncExecCommand struct { Command string `yaml:"command,omitempty"` Args []string `yaml:"args,omitempty"` OnFileChange *SyncCommand `yaml:"onFileChange,omitempty"` OnDirCreate *SyncCommand `yaml:"onDirCreate,omitempty"` } // SyncCommand holds a command definition type SyncCommand struct { Command string `yaml:"command,omitempty"` Args []string `yaml:"args,omitempty"` } // InitialSyncStrategy is the type of a initial sync strategy type InitialSyncStrategy string // List of values that source can take const ( InitialSyncStrategyMirrorLocal InitialSyncStrategy = "mirrorLocal" InitialSyncStrategyMirrorRemote InitialSyncStrategy = "mirrorRemote" InitialSyncStrategyPreferLocal InitialSyncStrategy = "preferLocal" InitialSyncStrategyPreferRemote InitialSyncStrategy = "preferRemote" InitialSyncStrategyPreferNewest InitialSyncStrategy = "preferNewest" InitialSyncStrategyKeepAll InitialSyncStrategy = "keepAll" ) // BandwidthLimits defines the struct for specifying the sync bandwidth limits type BandwidthLimits struct { Download *int64 `yaml:"download,omitempty"` Upload *int64 `yaml:"upload,omitempty"` } // LogsConfig specifies the logs options for devspace dev type LogsConfig struct { Disabled *bool `yaml:"disabled,omitempty"` ShowLast *int `yaml:"showLast,omitempty"` Images []string `yaml:"images,omitempty"` } // AutoReloadConfig defines the struct for auto reloading devspace with additional paths type AutoReloadConfig struct { Paths []string `yaml:"paths,omitempty"` Deployments []string `yaml:"deployments,omitempty"` Images []string `yaml:"images,omitempty"` } // InteractiveConfig defines the default interactive config type InteractiveConfig struct { DefaultEnabled *bool `yaml:"defaultEnabled,omitempty"` Images []*InteractiveImageConfig `yaml:"images,omitempty"` Terminal *TerminalConfig `yaml:"terminal,omitempty"` } // InteractiveImageConfig describes the interactive mode options for an image type InteractiveImageConfig struct { Name string `yaml:"name,omitempty"` Entrypoint []string `yaml:"entrypoint,omitempty"` Cmd []string `yaml:"cmd,omitempty"` } // TerminalConfig describes the terminal options type TerminalConfig struct { ImageName string `yaml:"imageName,omitempty"` LabelSelector map[string]string `yaml:"labelSelector,omitempty"` ContainerName string `yaml:"containerName,omitempty"` Namespace string `yaml:"namespace,omitempty"` Command []string `yaml:"command,omitempty"` } // DependencyConfig defines the devspace dependency type DependencyConfig struct { Name string `yaml:"name"` Source *SourceConfig `yaml:"source"` Profile string `yaml:"profile,omitempty"` SkipBuild *bool `yaml:"skipBuild,omitempty"` IgnoreDependencies *bool `yaml:"ignoreDependencies,omitempty"` Namespace string `yaml:"namespace,omitempty"` } // SourceConfig defines the dependency source type SourceConfig struct { Git string `yaml:"git,omitempty"` CloneArgs []string `yaml:"cloneArgs,omitempty"` DisableShallow bool `yaml:"disableShallow,omitempty"` SubPath string `yaml:"subPath,omitempty"` Branch string `yaml:"branch,omitempty"` Tag string `yaml:"tag,omitempty"` Revision string `yaml:"revision,omitempty"` Path string `yaml:"path,omitempty"` } // HookConfig defines a hook type HookConfig struct { Command string `yaml:"command"` Args []string `yaml:"args,omitempty"` When *HookWhenConfig `yaml:"when,omitempty"` } // HookWhenConfig defines when the hook should be executed type HookWhenConfig struct { Before *HookWhenAtConfig `yaml:"before,omitempty"` After *HookWhenAtConfig `yaml:"after,omitempty"` } // HookWhenAtConfig defines at which stage the hook should be executed type HookWhenAtConfig struct { Images string `yaml:"images,omitempty"` Deployments string `yaml:"deployments,omitempty"` } // CommandConfig defines the command specification type CommandConfig struct { Name string `yaml:"name"` Command string `yaml:"command"` } // Variable describes the var definition type Variable struct { Name string `yaml:"name"` Question string `yaml:"question,omitempty"` Options []string `yaml:"options,omitempty"` Password bool `yaml:"password,omitempty"` ValidationPattern string `yaml:"validationPattern,omitempty"` ValidationMessage string `yaml:"validationMessage,omitempty"` Default string `yaml:"default,omitempty"` Source *VariableSource `yaml:"source,omitempty"` } // VariableSource is type of a variable source type VariableSource string // List of values that source can take const ( VariableSourceAll VariableSource = "all" VariableSourceEnv VariableSource = "env" VariableSourceInput VariableSource = "input" VariableSourceNone VariableSource = "none" ) // ProfileConfig defines a profile config type ProfileConfig struct { Name string `yaml:"name"` Parent string `yaml:"parent,omitempty"` Patches []*PatchConfig `yaml:"patches,omitempty"` Replace *ReplaceConfig `yaml:"replace,omitempty"` } // PatchConfig describes a config patch and how it should be applied type PatchConfig struct { Operation string `yaml:"op"` Path string `yaml:"path"` Value interface{} `yaml:"value,omitempty"` From string `yaml:"from,omitempty"` } // ReplaceConfig defines a replace config that can override certain parts of the config completely type ReplaceConfig struct { Images map[string]*ImageConfig `yaml:"images,omitempty"` Deployments []*DeploymentConfig `yaml:"deployments,omitempty"` Dev *DevConfig `yaml:"dev,omitempty"` Dependencies []*DependencyConfig `yaml:"dependencies,omitempty"` Hooks []*HookConfig `yaml:"hooks,omitempty"` }
//go:build !(linux || windows) // +build !linux,!windows package main // This file is a stub for unsupported platforms to make IDEs happy. // unhandledArgHandler is a handler for unsupported arguments. func unhandledArgHandler(arg string) (string, []cleanupFunc, error) { panic("Platform is unsupported") } // argHandlers is the table of argument handlers. var argHandlers = argHandlersType{ volumeArgHandler: unhandledArgHandler, filePathArgHandler: unhandledArgHandler, outputPathArgHandler: unhandledArgHandler, mountArgHandler: unhandledArgHandler, builderCacheArgHandler: unhandledArgHandler, } func spawn(opts spawnOptions) error { panic("Platform is unsupported") } // function prepareParseArgs should be called before argument parsing to set up // the system for arg parsing. func prepareParseArgs() error { panic("Platform is unsupported") } // function cleanupParseArgs should be called after the command finishes // (regardless of whether it succeeded) to clean up any resources. func cleanupParseArgs() error { panic("Platform is unsupported") }
//go:build !windows && !freebsd // +build !windows,!freebsd package osutil import ( "fmt" "syscall" ) // RaiseOpenFileLimit tries to maximize the limit of open file descriptors, limited by max or the OS's hard limit func RaiseOpenFileLimit(max uint64) error { var limit syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { return fmt.Errorf("could not get current limit: %w", err) } if limit.Cur >= limit.Max || limit.Cur >= max { return nil } limit.Cur = limit.Max if limit.Cur > max { limit.Cur = max } return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit) }
// Copyright © 2019 IBM Corporation and others. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path/filepath" "time" "github.com/gosuri/uitable" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) type RepoIndex struct { APIVersion string `yaml:"apiVersion"` Generated time.Time `yaml:"generated"` Projects map[string]ProjectVersions `yaml:"projects"` } type ProjectVersions []*ProjectVersion type ProjectVersion struct { APIVersion string `yaml:"apiVersion"` Created time.Time `yaml:"created"` Name string `yaml:"name"` Home string `yaml:"home"` Version string `yaml:"version"` Description string `yaml:"description"` Keywords []string `yaml:"keywords"` Maintainers []string `yaml:"maintainers"` Icon string `yaml:"icon"` Digest string `yaml:"digest"` URLs []string `yaml:"urls"` } type RepositoryFile struct { APIVersion string `yaml:"apiVersion"` Generated time.Time `yaml:"generated"` Repositories []*RepositoryEntry `yaml:"repositories"` } type RepositoryEntry struct { Name string `yaml:"name"` URL string `yaml:"url"` } var ( appsodyHubURL = "https://raw.githubusercontent.com/appsody/stacks/master/index.yaml" ) // repoCmd represents the repo command var repoCmd = &cobra.Command{ Use: "repo", Short: "Manage your Appsody repositories", Long: ``, } func getHome() string { return cliConfig.GetString("home") } func getRepoDir() string { return filepath.Join(getHome(), "repository") } func getRepoFileLocation() string { return filepath.Join(getRepoDir(), "repository.yaml") } func init() { rootCmd.AddCommand(repoCmd) } // Locate or create config structure in $APPSODY_HOME func ensureConfig() { directories := []string{ getHome(), getRepoDir(), } for _, p := range directories { if fi, err := os.Stat(p); err != nil { if dryrun { Info.log("Dry Run - Skipping create of directory ", p) } else { Debug.log("Creating ", p) if err := os.MkdirAll(p, 0755); err != nil { Error.logf("Could not create %s: %s", p, err) os.Exit(1) } } } else if !fi.IsDir() { Error.logf("%s must be a directory", p) os.Exit(1) } } // Repositories file var repoFileLocation = getRepoFileLocation() if file, err := os.Stat(repoFileLocation); err != nil { if dryrun { Info.log("Dry Run - Skipping creation of appsodyhub repo: ", appsodyHubURL) } else { repo := NewRepoFile() repo.Add(&RepositoryEntry{ Name: "appsodyhub", URL: appsodyHubURL, }) Debug.log("Creating ", repoFileLocation) if err := repo.WriteFile(repoFileLocation); err != nil { Error.logf("Error writing %s file: %s ", repoFileLocation, err) os.Exit(1) } } } else if file.IsDir() { Error.logf("%s must be a file, not a directory ", repoFileLocation) os.Exit(1) } defaultConfigFile := getDefaultConfigFile() if _, err := os.Stat(defaultConfigFile); err != nil { if dryrun { Info.log("Dry Run - Skip creation of default config file ", defaultConfigFile) } else { Debug.log("Creating ", defaultConfigFile) if err := ioutil.WriteFile(defaultConfigFile, []byte{}, 0644); err != nil { Error.logf("Error creating default config file %s", err) os.Exit(1) } } } if dryrun { Info.log("Dry Run - Skip writing config file ", defaultConfigFile) } else { Debug.log("Writing config file ", defaultConfigFile) if err := cliConfig.WriteConfig(); err != nil { Error.logf("Writing default config file %s", err) os.Exit(1) } } } func downloadIndex(href string) (*bytes.Buffer, error) { buf := bytes.NewBuffer(nil) // allow file:// scheme t := &http.Transport{} t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/"))) httpClient := &http.Client{Transport: t} Debug.log("Downloading appsody repository index from ", href) req, err := http.NewRequest("GET", href, nil) if err != nil { return buf, err } resp, err := httpClient.Do(req) if err != nil { return buf, err } if resp.StatusCode != 200 { return buf, fmt.Errorf("Failed to fetch %s : %s", href, resp.Status) } _, err = io.Copy(buf, resp.Body) resp.Body.Close() return buf, err } func (index *RepoIndex) getIndex() *RepoIndex { var repos RepositoryFile repos.getRepos() var masterIndex *RepoIndex for _, value := range repos.Repositories { indexBuffer, err := downloadIndex(value.URL) if err != nil { log.Printf("yamlFile.Get err #%v ", err) } yamlFile, err := ioutil.ReadAll(indexBuffer) if err != nil { log.Printf("yamlFile.Get err #%v ", err) } err = yaml.Unmarshal(yamlFile, index) if err != nil { log.Fatalf("Unmarshal: %v", err) } if masterIndex == nil { masterIndex = index } else { for name, project := range index.Projects { masterIndex.Projects[name] = project } } } return masterIndex } func (index *RepoIndex) listProjects() string { table := uitable.New() table.MaxColWidth = 60 table.AddRow("NAME", "VERSION", "DESCRIPTION") for _, value := range index.Projects { table.AddRow(value[0].Name, value[0].Version, value[0].Description) } return table.String() } func (r *RepositoryFile) getRepos() *RepositoryFile { var repoFileLocation = getRepoFileLocation() repoReader, err := ioutil.ReadFile(repoFileLocation) if err != nil { if os.IsNotExist(err) { Error.logf("Repository file does not exist %s. Check to make sure appsody init has been run. ", repoFileLocation) os.Exit(1) } else { Error.log("Failed reading repository file ", repoFileLocation) os.Exit(1) } } err = yaml.Unmarshal(repoReader, r) if err != nil { Error.log("Failed to parse repository file ", err) os.Exit(1) } return r } func (r *RepositoryFile) listRepos() string { table := uitable.New() table.MaxColWidth = 120 table.AddRow("NAME", "URL") for _, value := range r.Repositories { table.AddRow(value.Name, value.URL) } return table.String() } func NewRepoFile() *RepositoryFile { return &RepositoryFile{ APIVersion: APIVersionV1, Generated: time.Now(), Repositories: []*RepositoryEntry{}, } } func (r *RepositoryFile) Add(re ...*RepositoryEntry) { r.Repositories = append(r.Repositories, re...) } func (r *RepositoryFile) Has(name string) bool { for _, rf := range r.Repositories { if rf.Name == name { return true } } return false } func (r *RepositoryFile) Remove(name string) { for index, rf := range r.Repositories { if rf.Name == name { r.Repositories[index] = r.Repositories[0] r.Repositories = r.Repositories[1:] return } } } func (r *RepositoryFile) WriteFile(path string) error { data, err := yaml.Marshal(r) if err != nil { return err } return ioutil.WriteFile(path, data, 0644) }
package types import ( "flag" "testing" "time" ) const errMsg = "Expected `%v`, got `%v`." func TestSetString(t *testing.T) { for _, v := range []struct { v flag.Value fn func(v flag.Value) exp string }{ { &Strings{Value: []string{"a", "b", "c"}}, func(v flag.Value) { v.Set("x") v.Set("y") v.Set("z") }, "[x; y; z]", }, { &Ints{Value: []int{1, 2, 3}}, func(v flag.Value) { v.Set("4") v.Set("5") v.Set("6") }, "[4; 5; 6]", }, { &Int64s{Value: []int64{1, 2, 3}}, func(v flag.Value) { v.Set("4") v.Set("5") v.Set("6") }, "[4; 5; 6]", }, { &Uints{Value: []uint{1, 2, 3}}, func(v flag.Value) { v.Set("4") v.Set("5") v.Set("6") }, "[4; 5; 6]", }, { &Uint64s{Value: []uint64{1, 2, 3}}, func(v flag.Value) { v.Set("4") v.Set("5") v.Set("6") }, "[4; 5; 6]", }, { &Float64s{Value: []float64{1, 2, 3}}, func(v flag.Value) { v.Set("4.0") v.Set("5.0") v.Set("6.0") }, "[4; 5; 6]", }, { &Bools{Value: []bool{true, false, true}}, func(v flag.Value) { v.Set("0") v.Set("false") v.Set("1") }, "[false; false; true]", }, { &Durations{Value: []time.Duration{}}, func(v flag.Value) { v.Set("1ms") v.Set("1m") v.Set("8h") }, "[1ms; 1m0s; 8h0m0s]", }, } { v.fn(v.v) if res := v.v.String(); res != v.exp { t.Errorf(errMsg, v.exp, res) } } } func TestAdd_IncorrectInput(t *testing.T) { for inp, obj := range map[string]slice{ "incorrect_int": &Ints{}, "incorrect_int64": &Int64s{}, "incorrect_uint": &Uints{}, "incorrect_uint64": &Uint64s{}, "incorrect_float64": &Float64s{}, "incorrect_bool": &Bools{}, "incorrect_duration": &Durations{}, } { if err := obj.add(inp); err == nil { t.Errorf(`"%s": Error expected, got nil.`, inp) } } }
package main import ( "fmt" "github.com/wagoodman/jotframe/pkg/frame" "io" "math/rand" "time" ) func renderLine(idx int, line *frame.Line) { minMs := 10 maxMs := 50 message := fmt.Sprintf("%s %s INITIALIZED", line, time.Now()) io.WriteString(line, message) for idx := 100; idx > 0; idx-- { // sleep for a bit... randomInterval := rand.Intn(maxMs-minMs) + minMs time.Sleep(time.Duration(randomInterval) * time.Millisecond) // write a message to this line... message := fmt.Sprintf("%s CountDown:%d", line, idx) io.WriteString(line, message) } // write a final message message = fmt.Sprintf("%s %s", line, "Closed!") io.WriteString(line, message) line.Close() } func main() { rand.Seed(time.Now().Unix()) config := frame.Config{ Lines: 5, PositionPolicy: frame.FloatTop, HasHeader: true, HasFooter: true, TrailOnRemove: true, } fr := frame.New(config) // add a header and footer fr.Header().WriteString("This is the best header ever!") fr.Header().Close() fr.Footer().WriteString("...Followed by the best footer ever...") fr.Footer().Close() // concurrently write to each line for idx := 0; idx < config.Lines; idx++ { go renderLine(idx, fr.Lines()[idx]) } // close the frame fr.Wait() fr.Close() frame.Close() }
//+build linux,arm package bus import ( "errors" "os" "runtime" "syscall" "unsafe" "github.com/zyxar/berry/sys" ) var ( errInvalidBaud = errors.New("invalid baud") ) type serial struct { fd uintptr } func OpenSerial(device string, baud uint) (s *serial, err error) { myBaud := getBaud(baud) if myBaud == 0 { err = errInvalidBaud return } fd, err := syscall.Open( device, os.O_RDWR|syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NDELAY|syscall.O_NONBLOCK, 0666) if err != nil { return } defer func() { if err != nil { syscall.Close(fd) } }() term := syscall.Termios{} if err = sys.Ioctl(uintptr(fd), syscall.TCGETS, uintptr(unsafe.Pointer(&term))); err != nil { return } term.Ispeed = myBaud term.Ospeed = myBaud term.Cflag |= (syscall.CLOCAL | syscall.CREAD) term.Cflag = uint32(int32(term.Cflag) & ^syscall.PARENB & ^syscall.CSTOPB & ^syscall.CSIZE) term.Cflag |= syscall.CS8 term.Lflag = uint32(int32(term.Lflag) & ^(syscall.ICANON | syscall.ECHO | syscall.ECHOE | syscall.ISIG)) term.Oflag = uint32(int32(term.Oflag) & ^syscall.OPOST) term.Cc[syscall.VMIN] = 0 term.Cc[syscall.VTIME] = 100 if err = sys.Ioctl(uintptr(fd), syscall.TCSETS, uintptr(unsafe.Pointer(&term))); err != nil { return } status := 0 if err = sys.Ioctl(uintptr(fd), syscall.TIOCMGET, uintptr(unsafe.Pointer(&status))); err != nil { return } status |= syscall.TIOCM_DTR | syscall.TIOCM_RTS if err = sys.Ioctl(uintptr(fd), syscall.TIOCMSET, uintptr(unsafe.Pointer(&status))); err != nil { return } s = &serial{uintptr(fd)} runtime.SetFinalizer(s, func(this *serial) { this.Close() }) return } func (this *serial) Close() error { return syscall.Close(int(this.fd)) } func (this *serial) Flush() error { return sys.Ioctl(this.fd, syscall.TCIOFLUSH, 0) } func (this *serial) Write(p []byte) (n int, err error) { n, err = syscall.Write(int(this.fd), p) return } func (this *serial) Read(p []byte) (n int, err error) { n, err = syscall.Read(int(this.fd), p) return } func (this *serial) Available() (n int, err error) { err = sys.Ioctl(this.fd, syscall.TIOCINQ, uintptr(unsafe.Pointer(&n))) return } func getBaud(b uint) uint32 { switch b { case 50: return syscall.B50 case 75: return syscall.B75 case 110: return syscall.B110 case 134: return syscall.B134 case 150: return syscall.B150 case 200: return syscall.B200 case 300: return syscall.B300 case 600: return syscall.B600 case 1200: return syscall.B1200 case 1800: return syscall.B1800 case 2400: return syscall.B2400 case 4800: return syscall.B4800 case 9600: return syscall.B9600 case 19200: return syscall.B19200 case 38400: return syscall.B38400 case 57600: return syscall.B57600 case 115200: return syscall.B115200 case 230400: return syscall.B230400 default: } return 0 }
package main import ( "log" "web/lib" ) func main() { log.Println("Weclome to Avalon") lib.LogInit(true) lib.Web() }
package main import "fmt" func main() { funcExe(multiplication); funcExe(addition); } func funcExe(handle func()){ handle(); } func addition(){ for i:=1; i<=9 ;i++ { for j:=1;j<=i ;j++ { fmt.Print(i,"+",j,"=",i+j," "); } fmt.Println(""); } } func multiplication(){ for i:=1; i<=9 ;i++ { for j:=1;j<=i ;j++ { fmt.Print(i,"*",j,"=",i*j," "); } fmt.Println(""); } }
package mock import ( "net/http" ) // Handler is a mock http.Handler. type Handler struct { serveHTTP func(writer http.ResponseWriter, request *http.Request) } // NewHandler creates a new mock handler. func NewHandler(serveHTTP func(writer http.ResponseWriter, request *http.Request)) *Handler { return &Handler{ serveHTTP: serveHTTP, } } func (handler *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { handler.serveHTTP(writer, request) }
package main import ( "testing" // "context" "fmt" "time" ) func TestFuncs(t *testing.T){ //firebase testing // ctx := context.Background() // firebase, err := newFirebase(&ctx) // if err!=nil{ // logger.Printf(err.Error()) // return // } // start := time.Now() // resToken, err := firebase.getToken.fromTokenStr("") // if err!=nil { // //토큰이 valid하지 않을 경우 / 자체적인 err인 경우 // logger.Printf(err.Error()) // return // } // UID := firebase.getStr.UIDFromToken(resToken) // fmt.Printf("UID := %v\n",UID) // timeTrack(start, "varifyLoginToken") //mysql testing // mysql, err := newMysql() // if err!=nil{ // return // } // paymentID, err = mysql.getStr.paymentIDFromUID("uidStr") // if (err!=nil || paymentID == ""){ // return // } //paypal testing paypal, err := newPaypal() if err!=nil{ fmt.Printf("err := %v\n",err.Error()) return } accessToken, err := paypal.getStr.accessToken() if err!=nil{ fmt.Printf("err := %v\n",err.Error()) return } subscriptionVarifyBool, err := paypal.getBool.varifyPaymentFromPaymentID("I-WG9BCLFJAPGK",accessToken) if err!=nil{ fmt.Printf("err := %v\n",err.Error()) return } fmt.Printf("%v\n",subscriptionVarifyBool) // fmt.Printf(accessToken) } func TestMain(t *testing.T){ } func timeTrack(start time.Time, name string) { elapsed := time.Since(start) fmt.Printf("%s took %s\n", name, elapsed) }
// TOML Parser. package toml import ( "fmt" "reflect" "strconv" "strings" "time" ) type parser struct { flow chan token tree *TomlTree tokensBuffer []token currentGroup []string seenGroupKeys []string } type parserStateFn func(*parser) parserStateFn func (p *parser) run() { for state := parseStart; state != nil; { state = state(p) } } func (p *parser) peek() *token { if len(p.tokensBuffer) != 0 { return &(p.tokensBuffer[0]) } tok, ok := <-p.flow if !ok { return nil } p.tokensBuffer = append(p.tokensBuffer, tok) return &tok } func (p *parser) assume(typ tokenType) { tok := p.getToken() if tok == nil { panic(fmt.Sprintf("was expecting token %s, but token stream is empty", typ)) } if tok.typ != typ { panic(fmt.Sprintf("was expecting token %s, but got %s", typ, tok.typ)) } } func (p *parser) getToken() *token { if len(p.tokensBuffer) != 0 { tok := p.tokensBuffer[0] p.tokensBuffer = p.tokensBuffer[1:] return &tok } tok, ok := <-p.flow if !ok { return nil } return &tok } func parseStart(p *parser) parserStateFn { tok := p.peek() // end of stream, parsing is finished if tok == nil { return nil } switch tok.typ { case tokenDoubleLeftBracket: return parseGroupArray case tokenLeftBracket: return parseGroup case tokenKey: return parseAssign case tokenEOF: return nil default: panic("unexpected token") } return nil } func parseGroupArray(p *parser) parserStateFn { p.getToken() // discard the [[ key := p.getToken() if key.typ != tokenKeyGroupArray { panic(fmt.Sprintf("unexpected token %s, was expecting a key group array", key)) } // get or create group array element at the indicated part in the path p.currentGroup = strings.Split(key.val, ".") dest_tree := p.tree.GetPath(p.currentGroup) var array []*TomlTree if dest_tree == nil { array = make([]*TomlTree, 0) } else if dest_tree.([]*TomlTree) != nil { array = dest_tree.([]*TomlTree) } else { panic(fmt.Sprintf("key %s is already assigned and not of type group array", key)) } // add a new tree to the end of the group array new_tree := make(TomlTree) array = append(array, &new_tree) p.tree.SetPath(p.currentGroup, array) // keep this key name from use by other kinds of assignments p.seenGroupKeys = append(p.seenGroupKeys, key.val) // move to next parser state p.assume(tokenDoubleRightBracket) return parseStart(p) } func parseGroup(p *parser) parserStateFn { p.getToken() // discard the [ key := p.getToken() if key.typ != tokenKeyGroup { panic(fmt.Sprintf("unexpected token %s, was expecting a key group", key)) } for _, item := range p.seenGroupKeys { if item == key.val { panic("duplicated tables") } } p.seenGroupKeys = append(p.seenGroupKeys, key.val) p.tree.createSubTree(key.val) p.assume(tokenRightBracket) p.currentGroup = strings.Split(key.val, ".") return parseStart(p) } func parseAssign(p *parser) parserStateFn { key := p.getToken() p.assume(tokenEqual) value := parseRvalue(p) var group_key []string if len(p.currentGroup) > 0 { group_key = p.currentGroup } else { group_key = make([]string, 0) } // find the group to assign, looking out for arrays of groups var target_node *TomlTree switch node := p.tree.GetPath(group_key).(type) { case []*TomlTree: target_node = node[len(node)-1] case *TomlTree: target_node = node default: panic(fmt.Sprintf("Unknown group type for path %v", group_key)) } // assign value to the found group local_key := []string{key.val} final_key := append(group_key, key.val) if target_node.GetPath(local_key) != nil { panic(fmt.Sprintf("the following key was defined twice: %s", strings.Join(final_key, "."))) } target_node.SetPath(local_key, value) return parseStart(p) } func parseRvalue(p *parser) interface{} { tok := p.getToken() if tok == nil || tok.typ == tokenEOF { panic("expecting a value") } switch tok.typ { case tokenString: return tok.val case tokenTrue: return true case tokenFalse: return false case tokenInteger: val, err := strconv.ParseInt(tok.val, 10, 64) if err != nil { panic(err) } return val case tokenFloat: val, err := strconv.ParseFloat(tok.val, 64) if err != nil { panic(err) } return val case tokenDate: val, err := time.Parse(time.RFC3339, tok.val) if err != nil { panic(err) } return val case tokenLeftBracket: return parseArray(p) case tokenError: panic(tok.val) } panic("never reached") return nil } func parseArray(p *parser) []interface{} { array := make([]interface{}, 0) arrayType := reflect.TypeOf(nil) for { follow := p.peek() if follow == nil || follow.typ == tokenEOF { panic("unterminated array") } if follow.typ == tokenRightBracket { p.getToken() return array } val := parseRvalue(p) if arrayType == nil { arrayType = reflect.TypeOf(val) } if reflect.TypeOf(val) != arrayType { panic("mixed types in array") } array = append(array, val) follow = p.peek() if follow == nil { panic("unterminated array") } if follow.typ != tokenRightBracket && follow.typ != tokenComma { panic("missing comma") } if follow.typ == tokenComma { p.getToken() } } return array } func parse(flow chan token) *TomlTree { result := make(TomlTree) parser := &parser{ flow: flow, tree: &result, tokensBuffer: make([]token, 0), currentGroup: make([]string, 0), seenGroupKeys: make([]string, 0), } parser.run() return parser.tree }
package main import ( "fmt" "math/rand" "ms/sun/shared/helper" "ms/sun_old/base" //"ms/sun/shared/x" "ms/sun/shared/x" "time" ) var write = 0 var read = 0 func main() { base.DefultConnectToMysql() fn := func() { x, err := x.NewHomeFanout_Selector().ForUserId_Eq(rand.Intn(10000)).GetRows(base.DB) read++ if read%100 == 0 { fmt.Println("read ", read, len(x), err) } /*//witr=e arr := make([]x.HomeFanout, 0, 5000) for i := 0; i < 1000; i++ { p := x.HomeFanout{ OrderId: helper.NextRowsSeqId(), ForUserId: rand.Intn(10000)+1, PostId: helper.NextRowsSeqId(), } write++ arr = append(arr, p) } if write%1 == 0{ fmt.Println("write: ", write) } x.MassReplace_HomeFanout(arr, base.DB)*/ } // //go f4() //go f4() //go f4() // //go f5() //go f5() //go f5() for i := 0; i < 6; i++ { go fn() } time.Sleep(time.Hour) } func all() { x, err := x.NewHomeFanout_Selector().ForUserId_Eq(rand.Intn(10000)).GetRows(base.DB) read++ if read%100 == 0 { fmt.Println("read ", read, len(x), err) } //witr=e arr := make([]x.HomeFanout, 0, 5000) for i := 0; i < 1000; i++ { p := x.HomeFanout{ OrderId: helper.NextRowsSeqId(), ForUserId: rand.Intn(10000) + 1, PostId: helper.NextRowsSeqId(), } write++ arr = append(arr, p) } if write%1 == 0 { fmt.Println("write: ", write) } x.MassReplace_HomeFanout(arr, base.DB) } func f5() { for { x, err := x.NewHomeFanout_Selector().ForUserId_Eq(rand.Intn(10000)).GetRows(base.DB) read++ if read%100 == 0 { fmt.Println("read ", read, len(x), err) } time.Sleep(time.Millisecond * 10) } } func f4() { for { arr := make([]x.HomeFanout, 0, 5000) for i := 0; i < 1000; i++ { p := x.HomeFanout{ OrderId: helper.NextRowsSeqId(), ForUserId: rand.Intn(10000) + 1, PostId: helper.NextRowsSeqId(), } write++ arr = append(arr, p) } if write%1 == 0 { fmt.Println("write: ", write) } x.MassReplace_HomeFanout(arr, base.DB) time.Sleep(time.Millisecond * 10) } }
package main import ( "log" "os" "github.com/urfave/cli/v2" ) func main() { app := &cli.App{ Name: "AppStore Review Dumper", Usage: "Dumps recent AppStore reviews of given app", Commands: []*cli.Command{ { Name: "dump", Aliases: []string{"d"}, Usage: "dump dump dumper", Action: func(c *cli.Context) error { dumpReviews(c.Args().Get(0)) return nil }, }, { Name: "list", Aliases: []string{"l"}, Usage: "List all saved reviews from given URL", Action: func(c *cli.Context) error { listReviews(c.Args().Get(0)) return nil }, }, }, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } }
package main import ( "fmt" ) type Node struct { preNodeName string name string weight int } func BellmanFord(relation map[string][]Node, startName string, searchName string) (int, []string) { searchQueue := make([]string, 0) searchQueue = append(searchQueue, startName) searchedMap := make(map[string]Node) for len(searchQueue) != 0 { currentName := searchQueue[0] //fmt.Println("Debug current node", currentName) for _, node := range relation[currentName] { if existNode, ok := searchedMap[node.name]; ok { if searchedMap[node.name].weight > node.weight+searchedMap[currentName].weight { existNode.weight = node.weight + searchedMap[currentName].weight existNode.preNodeName = currentName searchedMap[node.name] = existNode //fmt.Println("Debug update exist node:", node.name, searchedMap[node.name]) } } else { searchedMap[node.name] = Node{currentName, node.name, node.weight + searchedMap[currentName].weight} fmt.Println("Debug add new node:", node.name, searchedMap[node.name]) searchQueue = append(searchQueue, node.name) } } searchQueue = searchQueue[1:] } fmt.Println("Debug searched record:", searchedMap) path := []string{} pathName := searchName for pathName != startName { if pathNode, ok := searchedMap[pathName]; ok { path = append([]string{pathName}, path...) pathName = pathNode.preNodeName } } path = append([]string{pathName}, path...) return searchedMap[searchName].weight, path } func main() { fmt.Println("Welcome to the playground!") releationMap := make(map[string][]Node) releationMap["name A"] = []Node{Node{"name A", "name B", 5}, Node{"name A", "name E", 0}} releationMap["name B"] = []Node{Node{"name B", "name C", 15}, Node{"name B", "name F", 20}} releationMap["name C"] = []Node{Node{"name C", "name D", 20}} releationMap["name D"] = nil releationMap["name E"] = []Node{Node{"name E", "name C", 30}, Node{"name E", "name F", 35}} releationMap["name F"] = []Node{Node{"name F", "name D", 10}} distance, path := BellmanFord(releationMap, "name A", "name D") fmt.Println("BellmanFord search name D start from name A:", distance, "with path:", path) } // Welcome to the playground! // Debug add new node: name B {name A name B 5} // Debug add new node: name E {name A name E 0} // Debug add new node: name C {name B name C 20} // Debug add new node: name F {name B name F 25} // Debug add new node: name D {name C name D 40} // Debug searched record: map[name B:{name A name B 5} name C:{name B name C 20} name D:{name F name D 35} name E:{name A name E 0} name F:{name B name F 25}] // BellmanFord search name D start from name A: 35 with path: [name A name B name F name D]
package api import ( "net/http" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "github.com/rs/cors" ) type Rest struct { router *mux.Router bind string } func CreateAPI(bind string) *Rest { return &Rest{ router: mux.NewRouter(), bind: bind, } } func (a *Rest) Start() error { handler := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"}, AllowCredentials: true, AllowedHeaders: []string{"Authorization", "Content-Type"}, Debug: false, }).Handler(a.router) log.Infof("API listening on %s", a.bind); return http.ListenAndServe(a.bind, handler) } // == GET ===================================================================== func (a *Rest) RegisterGet(path string, h func(w http.ResponseWriter, r *http.Request)) *mux.Route { log.WithFields(log.Fields{ "method": "GET", "secured": false, }).Info(path) return a.router. Path(path). Methods("GET"). Handler(http.HandlerFunc(h)) } // == POST ==================================================================== func (a *Rest) RegisterPost(path string, h func(w http.ResponseWriter, r *http.Request)) *mux.Route { log.WithFields(log.Fields{ "method": "POST", "secured": false, }).Info(path) return a.router. Path(path). Methods("POST"). Handler(http.HandlerFunc(h)) } // == PUT ===================================================================== func (a *Rest) RegisterPut(path string, h func(w http.ResponseWriter, r *http.Request)) *mux.Route { log.WithFields(log.Fields{ "method": "PUT", "secured": false, }).Info(path) return a.router. Path(path). Methods("PUT"). Handler(http.HandlerFunc(h)) } // == DELETE ================================================================== func (a *Rest) RegisterDelete(path string, h func(w http.ResponseWriter, r *http.Request)) *mux.Route { log.WithFields(log.Fields{ "method": "DELETE", "secured": false, }).Info(path) return a.router. Path(path). Methods("DELETE"). Handler(http.HandlerFunc(h)) }
package models import ( "awesome_gin/pkg/setting" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "log" "time" ) type Model struct { ID int `gorm:"primary_key" json:"id"` Created int `json:"created" gorm:"column:created"` Updated int `json:"updated" gorm:"column:updated"` } var db *gorm.DB func Setup() { var err error db, err = gorm.Open(setting.DBSetting.DBType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", setting.DBSetting.User, setting.DBSetting.Password, setting.DBSetting.Host, setting.DBSetting.DbName)) if err != nil{ log.Fatalf("models.setup err:%v", err) } gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string { return defaultTableName } db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback) db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback) db.SingularTable(true) db.DB().SetMaxIdleConns(10) db.DB().SetMaxOpenConns(100) } func updateTimeStampForCreateCallback(scope *gorm.Scope) { if !scope.HasError() { nowTime := time.Now().Unix() if createTimeField, ok := scope.FieldByName("Created"); ok { if createTimeField.IsBlank { createTimeField.Set(nowTime) } } if modifyTimeField, ok := scope.FieldByName("Updated"); ok { if modifyTimeField.IsBlank { modifyTimeField.Set(nowTime) } } } } func updateTimeStampForUpdateCallback(scope *gorm.Scope) { if _, ok := scope.Get("gorm:update_column"); !ok { scope.SetColumn("Updated", time.Now().Unix()) } } func CloseDB() { if err := db.Close(); err != nil{ log.Fatalf("models.close err:%v", err) } }
package sqlc import ( // "bytes" // "compress/gzip" "fmt" // "io" "io/ioutil" "strings" ) func bindata_read(data []byte, name string) ([]byte, error) { b, err := ioutil.ReadFile(name) if err != nil { return nil, fmt.Errorf("Read: %q: %v", name, err) } return b, nil // gz, err := gzip.NewReader(bytes.NewBuffer(data)) // if err != nil { // return nil, fmt.Errorf("Read %q: %v", name, err) // } // var buf bytes.Buffer // _, err = io.Copy(&buf, gz) // gz.Close() // if err != nil { // return nil, fmt.Errorf("Read %q: %v", name, err) // } // return buf.Bytes(), nil } func sqlc_tmpl_fields_tmpl() ([]byte, error) { return bindata_read([]byte{ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x00, 0xff, 0xc4, 0x57, 0x51, 0x6f, 0xdb, 0x36, 0x10, 0x7e, 0x96, 0x7e, 0xc5, 0xc1, 0x08, 0x02, 0x2b, 0x50, 0x94, 0x77, 0x03, 0x79, 0x70, 0x5b, 0x65, 0xf5, 0xe0, 0x3a, 0x81, 0xed, 0x2e, 0xd8, 0xd3, 0xa0, 0xca, 0x94, 0xcb, 0x4d, 0xa1, 0x35, 0x89, 0xce, 0x5a, 0x08, 0xfa, 0xef, 0xbb, 0x23, 0x29, 0x95, 0xb2, 0x29, 0xd7, 0xc6, 0xb0, 0xd6, 0x0f, 0x89, 0x79, 0x24, 0xef, 0xbe, 0xfb, 0xee, 0x3b, 0x92, 0xbe, 0xbb, 0x83, 0xf5, 0xfb, 0xd9, 0x0a, 0x1e, 0x66, 0xf3, 0x18, 0x9e, 0xa7, 0x2b, 0x98, 0x7e, 0x5c, 0x3f, 0xfe, 0x12, 0x2f, 0xe2, 0xe5, 0x74, 0x1d, 0xbf, 0x83, 0x5b, 0x98, 0x2e, 0x7e, 0x87, 0xf8, 0xdd, 0x6c, 0xbd, 0x82, 0xf5, 0xa3, 0x5e, 0xfa, 0x3c, 0x9b, 0xcf, 0xe1, 0x4d, 0x0c, 0xf3, 0xc7, 0xd5, 0x1a, 0x9e, 0xdf, 0xc7, 0x0b, 0x98, 0xad, 0x01, 0xed, 0xcb, 0xb8, 0xdb, 0xe7, 0xfb, 0x75, 0x0d, 0x57, 0x45, 0xc9, 0x36, 0x15, 0x4c, 0xee, 0x21, 0xa2, 0x6f, 0x3c, 0x4d, 0x24, 0xab, 0xa0, 0x69, 0xd4, 0x5c, 0xb6, 0x17, 0xa9, 0x9e, 0xa3, 0x6f, 0x92, 0xef, 0x84, 0x9a, 0xf2, 0x8b, 0x24, 0xfd, 0x2b, 0xd9, 0x32, 0xa8, 0xfe, 0xce, 0x53, 0xdf, 0xe7, 0x2f, 0xc5, 0xae, 0x94, 0x30, 0xf6, 0xbd, 0x91, 0xe4, 0x2f, 0x6c, 0xe4, 0x07, 0xbe, 0x2f, 0xbf, 0x16, 0x0c, 0x66, 0xa2, 0x62, 0xa5, 0x5c, 0x31, 0xb9, 0x92, 0xac, 0x00, 0x2e, 0x24, 0x2b, 0xb3, 0x24, 0x65, 0x50, 0xfb, 0x1e, 0x7a, 0x2f, 0x13, 0x81, 0x2e, 0xae, 0xfe, 0x08, 0xe1, 0x4a, 0xaa, 0x18, 0xb4, 0x47, 0xf9, 0x07, 0x0f, 0xf7, 0x50, 0x7c, 0x19, 0x3d, 0x95, 0x2c, 0xe3, 0x5f, 0xd0, 0x38, 0x3e, 0x18, 0x3f, 0x70, 0x96, 0x6f, 0x42, 0xd0, 0xd6, 0x39, 0x47, 0xd7, 0x49, 0x8e, 0xe6, 0xe0, 0x5b, 0xd0, 0x0f, 0xbb, 0x92, 0x51, 0x60, 0x74, 0x87, 0xab, 0x98, 0xd8, 0x90, 0xeb, 0xc6, 0x40, 0xfb, 0x58, 0x6c, 0x30, 0xd1, 0x1f, 0x0c, 0xad, 0x0b, 0x3a, 0x04, 0xed, 0x64, 0x68, 0x2a, 0x01, 0x8c, 0x39, 0xdc, 0x70, 0x95, 0x61, 0x00, 0x0e, 0x24, 0x19, 0xb8, 0xb1, 0xbc, 0x9e, 0x43, 0x14, 0x25, 0x5f, 0x32, 0xb9, 0x2f, 0x05, 0xf0, 0xa8, 0x62, 0x72, 0x9c, 0x85, 0xaf, 0x81, 0xaf, 0x94, 0x60, 0x20, 0x9e, 0x03, 0x70, 0x0f, 0x37, 0x7b, 0x95, 0xe7, 0x7f, 0x06, 0x78, 0x44, 0x97, 0x05, 0x70, 0x3f, 0x00, 0xf0, 0x8e, 0x3e, 0xa6, 0xc6, 0x4b, 0x96, 0xe5, 0x2c, 0x95, 0xc9, 0xa7, 0x9c, 0xf5, 0x2a, 0x7c, 0x32, 0x09, 0xcf, 0x85, 0x6f, 0x2c, 0x92, 0x17, 0x54, 0xbb, 0x2c, 0xb9, 0xd8, 0x06, 0xce, 0x0c, 0xfc, 0x63, 0x89, 0x3d, 0x98, 0x96, 0xc1, 0x6c, 0x86, 0xa3, 0x67, 0x14, 0xdd, 0xf4, 0x59, 0x1b, 0x3d, 0x8b, 0x16, 0x14, 0x4e, 0x0b, 0xab, 0xe2, 0x5b, 0xc1, 0x33, 0xce, 0x4a, 0x5a, 0x4b, 0xac, 0x38, 0xc2, 0x9d, 0x51, 0x95, 0x0a, 0x6e, 0x2a, 0x46, 0x6c, 0x20, 0x20, 0x77, 0x06, 0xdf, 0xcf, 0xd1, 0xa2, 0xff, 0x1a, 0xe7, 0xe5, 0x6e, 0xbe, 0xfb, 0x87, 0x70, 0x1d, 0xae, 0xab, 0xc9, 0xd3, 0x04, 0xe8, 0x2f, 0xc1, 0xd3, 0x00, 0x24, 0xa8, 0x42, 0xfc, 0xc0, 0xd8, 0x21, 0x74, 0x19, 0x4f, 0x40, 0x36, 0x4e, 0x9d, 0x9c, 0x64, 0x4e, 0x97, 0xf1, 0x54, 0x34, 0x82, 0xbc, 0x4f, 0x25, 0x81, 0xb3, 0x32, 0xf0, 0xbd, 0x2e, 0x30, 0xb6, 0x40, 0x2b, 0x41, 0xdf, 0x4b, 0x72, 0x9e, 0x54, 0xdd, 0x1a, 0xa4, 0x45, 0xd7, 0xb2, 0xd5, 0x89, 0x6f, 0x45, 0x3c, 0x8e, 0xd4, 0x3b, 0xa2, 0xd6, 0xe4, 0x50, 0x0b, 0xe1, 0xe0, 0xb8, 0x2a, 0x94, 0x9e, 0xf4, 0x99, 0xde, 0xea, 0xa9, 0x88, 0x7a, 0x71, 0x48, 0x58, 0xaf, 0x49, 0xbe, 0x67, 0x8e, 0x96, 0x7b, 0xbb, 0x13, 0x1b, 0xae, 0xc0, 0x98, 0x9d, 0xbf, 0xee, 0xb8, 0x18, 0xda, 0xd8, 0x47, 0x18, 0x00, 0xad, 0xed, 0x3b, 0xf8, 0x26, 0x51, 0x2d, 0x82, 0x14, 0x6e, 0x4e, 0xd1, 0x19, 0x74, 0x3d, 0x33, 0x0e, 0xfa, 0xdc, 0x58, 0xe5, 0xef, 0xd9, 0xd1, 0xec, 0x2d, 0x54, 0xc5, 0x21, 0xa5, 0x3b, 0x4a, 0x75, 0x4e, 0x88, 0xc6, 0xf8, 0x4b, 0x51, 0x76, 0x46, 0x1a, 0x90, 0x71, 0x5a, 0x6e, 0xab, 0xce, 0x48, 0x03, 0x32, 0xbe, 0xfd, 0xcc, 0xf3, 0xcd, 0xc4, 0x18, 0xd5, 0x00, 0xad, 0x97, 0x60, 0xce, 0x52, 0x3c, 0x88, 0xf6, 0x22, 0x04, 0x86, 0x61, 0x4c, 0x79, 0x43, 0x48, 0xd0, 0x3d, 0x44, 0x51, 0xd4, 0xd5, 0xad, 0x6e, 0x7b, 0x97, 0x72, 0xe1, 0x19, 0x5c, 0xab, 0x88, 0x70, 0x7f, 0x0f, 0x82, 0xe7, 0x64, 0x3b, 0x4f, 0xdf, 0xb8, 0xce, 0xd3, 0x1a, 0x57, 0x9f, 0x34, 0x12, 0x26, 0x63, 0xcf, 0x52, 0x7b, 0x1a, 0x75, 0x03, 0x35, 0x85, 0x81, 0xcc, 0xfa, 0x03, 0xfa, 0x14, 0x77, 0x0a, 0xbc, 0x22, 0x8c, 0x32, 0x08, 0x41, 0xd3, 0x44, 0x09, 0x34, 0xb4, 0x1b, 0x55, 0xd4, 0x00, 0xcb, 0x2b, 0xf6, 0xb3, 0x40, 0xd2, 0x64, 0x5b, 0x65, 0xc2, 0xaa, 0xc6, 0xa6, 0xc0, 0x1a, 0xb1, 0xb2, 0x98, 0xea, 0x26, 0xa6, 0xae, 0x5d, 0x65, 0xaf, 0x1d, 0xde, 0xdc, 0xa2, 0xf1, 0x06, 0x74, 0xe3, 0x0d, 0x48, 0xc7, 0x1b, 0x50, 0x0f, 0x7e, 0x14, 0x73, 0x5e, 0xc7, 0xdf, 0x05, 0x72, 0x9a, 0x56, 0x63, 0xfb, 0xa0, 0xb0, 0x44, 0x73, 0x2e, 0xf5, 0x9a, 0x79, 0x43, 0x3a, 0x71, 0x33, 0x4c, 0xba, 0x8a, 0x84, 0xb5, 0xa6, 0x7f, 0x34, 0x56, 0x35, 0x38, 0xe6, 0xcb, 0xcd, 0x96, 0x9b, 0x2b, 0x37, 0x53, 0x6e, 0x9e, 0x9a, 0x0b, 0x5b, 0x6d, 0x4a, 0x38, 0xf1, 0x6c, 0xd0, 0xd4, 0x58, 0x9c, 0xa4, 0x91, 0x4a, 0xe1, 0x02, 0x57, 0x1f, 0x92, 0xaf, 0x9f, 0xd8, 0xb1, 0x3f, 0x6c, 0x4c, 0xe3, 0x8b, 0x3a, 0x73, 0x34, 0xb2, 0x35, 0xaf, 0x19, 0x75, 0x75, 0x43, 0x1b, 0xfe, 0xa2, 0x64, 0x88, 0x47, 0x77, 0x2e, 0x2a, 0xcc, 0xf9, 0x8e, 0x9e, 0x92, 0x92, 0x09, 0x39, 0x0e, 0xac, 0xcb, 0xa6, 0xe7, 0xae, 0xab, 0xb8, 0xaf, 0x2e, 0x3e, 0xb8, 0xbd, 0x3d, 0xbc, 0xf8, 0x0e, 0x6e, 0x8d, 0x73, 0x03, 0x0f, 0x5c, 0x2e, 0xe4, 0xe7, 0xd4, 0xdd, 0x62, 0x81, 0xeb, 0x6c, 0xf5, 0x1b, 0x8e, 0xdf, 0xc4, 0xd6, 0xa8, 0xcf, 0x8c, 0xea, 0xdf, 0xe8, 0xba, 0x99, 0x00, 0x79, 0x0c, 0xf5, 0x0c, 0x6a, 0xa8, 0x09, 0xe1, 0xa9, 0xfd, 0xa9, 0x32, 0x31, 0x20, 0x3a, 0x03, 0x86, 0xba, 0xa4, 0x08, 0xee, 0x5b, 0xce, 0xca, 0xe0, 0xe4, 0x25, 0x67, 0x65, 0xd2, 0xb3, 0xd7, 0xf3, 0xcf, 0xd8, 0x03, 0x69, 0x08, 0x4b, 0xfa, 0xaf, 0xd1, 0x7f, 0x1f, 0x72, 0xef, 0x79, 0xa2, 0xaa, 0xa4, 0x92, 0x38, 0x7c, 0x42, 0x57, 0x56, 0x9d, 0x43, 0xf8, 0xdf, 0x5f, 0x4e, 0x55, 0xe3, 0xb7, 0xef, 0xa5, 0xa3, 0x07, 0xd3, 0xc1, 0xeb, 0xf5, 0x02, 0xce, 0xcf, 0x78, 0xe3, 0x42, 0xed, 0x59, 0x22, 0xa6, 0x5b, 0x76, 0xd4, 0xdb, 0x39, 0x0a, 0xc1, 0x18, 0xe8, 0xec, 0x21, 0x03, 0x8e, 0xb8, 0xf8, 0x93, 0x80, 0x5b, 0xce, 0x8e, 0x7e, 0xc0, 0x98, 0xaf, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0xb4, 0xaa, 0xc3, 0xea, 0x54, 0x0f, 0x00, 0x00, }, "sqlc/tmpl/fields.tmpl", ) } func sqlc_tmpl_schema_tmpl() ([]byte, error) { return bindata_read([]byte{ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x00, 0xff, 0x9c, 0x54, 0x61, 0x6f, 0xda, 0x30, 0x10, 0xfd, 0x4c, 0x7e, 0xc5, 0x29, 0xaa, 0xa6, 0x64, 0xea, 0xc2, 0x77, 0x24, 0x3e, 0x64, 0x6a, 0xda, 0x46, 0x62, 0x61, 0x22, 0xa6, 0x68, 0x9a, 0x26, 0x64, 0x52, 0x87, 0x45, 0x0b, 0x49, 0x66, 0x9b, 0x6e, 0x08, 0xf1, 0xdf, 0x77, 0xb6, 0x49, 0x49, 0xc1, 0x14, 0x34, 0x84, 0x90, 0x39, 0xbf, 0x7b, 0xf7, 0xee, 0xf9, 0xec, 0x7e, 0x1f, 0xc8, 0x63, 0x9c, 0xc2, 0x7d, 0x3c, 0x8a, 0x60, 0x16, 0xa6, 0x10, 0x4e, 0xc9, 0xf8, 0x21, 0x4a, 0xa2, 0x49, 0x48, 0xa2, 0x3b, 0xf8, 0x04, 0x61, 0xf2, 0x0d, 0xa2, 0xbb, 0x98, 0xa4, 0x40, 0xc6, 0x06, 0x3a, 0x8b, 0x47, 0x23, 0xf8, 0x1c, 0xc1, 0x68, 0x9c, 0x12, 0x98, 0x3d, 0x46, 0x09, 0xc4, 0x04, 0x30, 0x3e, 0x89, 0x5e, 0xf3, 0x1c, 0xa4, 0x0d, 0x09, 0x6c, 0xb7, 0x10, 0x7c, 0xe5, 0xf5, 0x0b, 0xab, 0x68, 0x95, 0xb1, 0x80, 0x14, 0x2b, 0x26, 0x24, 0x5d, 0x35, 0xb0, 0xdb, 0xc1, 0x34, 0x8d, 0x93, 0x07, 0x10, 0xbf, 0xcb, 0x0c, 0x9e, 0xa2, 0x49, 0x1a, 0x8f, 0x93, 0x63, 0xf8, 0x13, 0xe3, 0xa2, 0xa8, 0x2b, 0x04, 0x3b, 0x0e, 0x6e, 0xdd, 0xc8, 0x4d, 0xc3, 0x04, 0x0c, 0x86, 0x10, 0x10, 0xbd, 0x52, 0xf1, 0x86, 0x66, 0xbf, 0xe8, 0x92, 0x99, 0xd4, 0xfd, 0x5a, 0xc5, 0x8b, 0x55, 0x53, 0x73, 0x09, 0x9e, 0xd3, 0x73, 0x97, 0x85, 0xfc, 0xb9, 0x5e, 0x04, 0x59, 0xbd, 0xea, 0x73, 0x56, 0xd6, 0x8d, 0xe8, 0xab, 0xa2, 0xfa, 0xc7, 0xc5, 0x6d, 0x21, 0x79, 0x51, 0x2d, 0x85, 0xeb, 0xf8, 0xba, 0x0a, 0xa7, 0x15, 0x52, 0xdc, 0xcc, 0x6f, 0xb1, 0x9e, 0xa9, 0x45, 0x17, 0xe5, 0xbe, 0x98, 0x12, 0xa0, 0x2a, 0xc9, 0x7a, 0x54, 0xff, 0x61, 0x1c, 0x11, 0x41, 0x42, 0x57, 0xaa, 0x20, 0x20, 0xcb, 0x3a, 0x93, 0xb0, 0x75, 0x7a, 0x6f, 0x39, 0x72, 0xc5, 0x81, 0xb8, 0xfb, 0x82, 0x95, 0xcf, 0x9a, 0xa5, 0xa7, 0x09, 0xa6, 0x4d, 0xa3, 0x08, 0xf2, 0x03, 0x01, 0xca, 0x09, 0x54, 0x97, 0xb9, 0xee, 0x0e, 0x43, 0x3a, 0x45, 0xc3, 0x59, 0xf5, 0xac, 0x33, 0x69, 0x59, 0x50, 0x01, 0x46, 0xb0, 0x83, 0x7a, 0xf2, 0x75, 0x95, 0x81, 0x27, 0xe1, 0xa3, 0x55, 0x93, 0x0f, 0xb1, 0x48, 0x59, 0xc9, 0x32, 0xa9, 0x3a, 0xf0, 0x7c, 0xd8, 0x5e, 0x91, 0xa2, 0x16, 0x08, 0x35, 0x35, 0x54, 0x3b, 0x9c, 0xc9, 0x35, 0xaf, 0xc0, 0xb5, 0xe2, 0xdd, 0x6b, 0x54, 0x84, 0xc2, 0xa3, 0x7b, 0x42, 0xdf, 0xb4, 0x79, 0x50, 0xd5, 0xa9, 0xf0, 0xc1, 0x9a, 0x8e, 0xfb, 0x97, 0x1d, 0xb5, 0x5b, 0x3a, 0x00, 0x19, 0x58, 0x37, 0x6e, 0x4d, 0x46, 0xeb, 0xaa, 0xb1, 0x75, 0x40, 0x31, 0xbc, 0xbb, 0xaa, 0x1f, 0x05, 0xb7, 0x79, 0x24, 0x03, 0xcd, 0x74, 0x0d, 0xc7, 0x17, 0xba, 0x59, 0xb0, 0x53, 0xa2, 0x22, 0x6f, 0x49, 0x60, 0x38, 0x04, 0xd7, 0x55, 0xb1, 0x4b, 0x27, 0xd0, 0xdb, 0x01, 0x2b, 0x05, 0xeb, 0x42, 0x5b, 0x21, 0xa6, 0x9f, 0xbe, 0xfa, 0x9c, 0xcc, 0xf6, 0xc6, 0xd8, 0xd8, 0x5e, 0xa4, 0x4b, 0x82, 0xcd, 0xfd, 0xc3, 0xdb, 0xc9, 0xf2, 0xe2, 0x6f, 0x3b, 0x9c, 0x5e, 0xa5, 0xb6, 0xdf, 0x1c, 0xad, 0x15, 0xd7, 0xf1, 0xc8, 0x0a, 0xf2, 0xba, 0xc7, 0xf4, 0x5a, 0xf4, 0x76, 0xcf, 0x2c, 0x02, 0x62, 0xf6, 0x74, 0x39, 0xdf, 0xc7, 0x9e, 0x0e, 0xa7, 0xd7, 0x76, 0x77, 0x49, 0xbf, 0x99, 0x16, 0x34, 0xfb, 0xfb, 0x0f, 0x2d, 0xe1, 0x58, 0x57, 0x37, 0x7c, 0xdd, 0xcc, 0x9d, 0x5e, 0xd8, 0x73, 0x6d, 0xb8, 0xd6, 0x29, 0x74, 0xfd, 0xa3, 0x39, 0xd4, 0x87, 0xd5, 0xe9, 0xec, 0xfd, 0xc7, 0xe8, 0x85, 0x72, 0x98, 0xcf, 0xed, 0x8f, 0xd1, 0xf0, 0xdc, 0x65, 0x32, 0x69, 0x56, 0x99, 0x67, 0x93, 0x94, 0x49, 0xce, 0xff, 0x3d, 0x6a, 0x03, 0xcb, 0xab, 0xe6, 0x9d, 0x11, 0xfd, 0x9e, 0x4d, 0x1d, 0x53, 0xf0, 0x7b, 0xf8, 0xfb, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x77, 0x30, 0x93, 0x44, 0xbc, 0x06, 0x00, 0x00, }, "sqlc/tmpl/schema.tmpl", ) } // Asset loads and returns the asset for the given name. // It returns an error if the asset could not be found or // could not be loaded. func Asset(name string) ([]byte, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { return f() } return nil, fmt.Errorf("Asset %s not found", name) } // AssetNames returns the names of the assets. func AssetNames() []string { names := make([]string, 0, len(_bindata)) for name := range _bindata { names = append(names, name) } return names } // _bindata is a table, holding each asset generator, mapped to its name. var _bindata = map[string]func() ([]byte, error){ "sqlc/tmpl/fields.tmpl": sqlc_tmpl_fields_tmpl, "sqlc/tmpl/schema.tmpl": sqlc_tmpl_schema_tmpl, } // AssetDir returns the file names below a certain // directory embedded in the file by go-bindata. // For example if you run go-bindata on data/... and data contains the // following hierarchy: // data/ // foo.txt // img/ // a.png // b.png // then AssetDir("data") would return []string{"foo.txt", "img"} // AssetDir("data/img") would return []string{"a.png", "b.png"} // AssetDir("foo.txt") and AssetDir("notexist") would return an error // AssetDir("") will return []string{"data"}. func AssetDir(name string) ([]string, error) { node := _bintree if len(name) != 0 { cannonicalName := strings.Replace(name, "\\", "/", -1) pathList := strings.Split(cannonicalName, "/") for _, p := range pathList { node = node.Children[p] if node == nil { return nil, fmt.Errorf("Asset %s not found", name) } } } if node.Func != nil { return nil, fmt.Errorf("Asset %s not found", name) } rv := make([]string, 0, len(node.Children)) for name := range node.Children { rv = append(rv, name) } return rv, nil } type _bintree_t struct { Func func() ([]byte, error) Children map[string]*_bintree_t } var _bintree = &_bintree_t{nil, map[string]*_bintree_t{ "sqlc": &_bintree_t{nil, map[string]*_bintree_t{ "tmpl": &_bintree_t{nil, map[string]*_bintree_t{ "schema.tmpl": &_bintree_t{sqlc_tmpl_schema_tmpl, map[string]*_bintree_t{ }}, "fields.tmpl": &_bintree_t{sqlc_tmpl_fields_tmpl, map[string]*_bintree_t{ }}, }}, }}, }}
package g import ( "fmt" //引入 mysql 驱动 _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" //引入 sqlite 驱动 _ "github.com/mattn/go-sqlite3" ) var dbp *gorm.DB //Conn 给其他模块调用的连接池获取方法 func ConnectDB() *gorm.DB { return dbp } //InitDB 初始化数据库连接池 func InitDB(loggerlevel bool) error { if Config().DB.Sqlite != "" { db, err := gorm.Open("sqlite3", Config().DB.Sqlite) if err != nil { return fmt.Errorf("connect to db: %s", err.Error()) } db.LogMode(loggerlevel) db.SingularTable(true) dbp = db return nil } db, err := gorm.Open("mysql", Config().DB.Mysql) if err != nil { return fmt.Errorf("connect to db: %s", err.Error()) } db.LogMode(loggerlevel) db.SingularTable(true) dbp = db return nil } //CloseDB 关闭数据库连接池 func CloseDB() (err error) { err = dbp.Close() return }
package rest_test import ( "net/http" "path/filepath" "testing" "github.com/iris-contrib/httpexpect" r "github.com/jinmukeji/jiujiantang-services/api-v2/rest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // AnalysisMonthlyReportTestSuite 是AnalysisMonthlyReport的单元测试的 Test Suite type AnalysisMonthlyReportTestSuite struct { suite.Suite Account *Account Expect *httpexpect.Expect } // SetupSuite 设置测试环境 func (suite *AnalysisMonthlyReportTestSuite) SetupSuite() { t := suite.T() envFilepath := filepath.Join("testdata", "local.api-v2.env") suite.Account = newTestingAccountFromEnvFile(envFilepath) app := r.NewApp("v2-api", "jinmuhealth") suite.Expect = httpexpect.WithConfig(httpexpect.Config{ Client: &http.Client{ Transport: httpexpect.NewBinder(app), Jar: httpexpect.NewJar(), }, Reporter: httpexpect.NewAssertReporter(t), Printers: []httpexpect.Printer{ httpexpect.NewCurlPrinter(t), httpexpect.NewDebugPrinter(t, true), }, }) } // TestGetMonthlyReport 测试月报 func (suite *AnalysisMonthlyReportTestSuite) TestGetMonthlyReport() { t := suite.T() e := suite.Expect auth, errGetAuthorization := getAuthorization(e) assert.NoError(t, errGetAuthorization) token, errGetAccessToken := getAccessToken(e) assert.NoError(t, errGetAccessToken) headers := make(map[string]string) headers["Authorization"] = auth headers["X-Access-Token"] = token e.POST("/v2-api/owner/measurements/v2/monthly_report"). WithHeaders(headers). WithJSON(&r.AnalysisMonthlyReportRequestBody{ C0: int32(1), C1: int32(2), C2: int32(3), C3: int32(4), C4: int32(-2), C5: int32(-3), C6: int32(1), C7: int32(1), UserID: int32(suite.Account.UserID), Language: r.LanguageSimpleChinese, PhysicalDialectics: []string{"T0001", "T0002"}, }). Expect().Body().Contains("content").Contains("monthly_report") } func TestAnalysisMonthlyReportTestSuite(t *testing.T) { suite.Run(t, new(AnalysisMonthlyReportTestSuite)) }
package main import ("fmt" "os" "bufio" "time" ) func main() { var myname string now := time.Now() str1 := "Please enter your WVNCC username:" fmt.Println(str1) fmt.Scanf("%s", &myname) //user enters username fmt.Println("User clock-in: ", myname) fmt.Println("Clock in: ",now.Format(time.ANSIC)) //current time stamp fileHandle, _ := os.OpenFile(myname +".txt", os.O_CREATE|os.O_APPEND, 0755) //creates and appends txt file writer := bufio.NewWriter(fileHandle) defer fileHandle.Close() fmt.Fprintln(writer, myname, ":", now.Format(time.ANSIC), "\r\n") //appends txt file with username and timestamp writer.Flush() }
// +build js,wasm package main import ( "app/server" wasmhttp "github.com/nlepage/go-wasm-http-server" ) func main() { e := server.New() wasmhttp.Serve(e.Server.Handler) select {} }
package main import ( "fmt" "os" "sort" ) func main() { // Get Number N of horses var N int fmt.Scan(&N) // Collect all strenght of horses strengthsOfHorses := make([]int, N) for i := 0; i < N; i++ { var Pi int fmt.Scan(&Pi) strengthsOfHorses[i] = Pi } // Debug str of horeses fmt.Fprintln(os.Stderr, "DEBUG: All horses:", N) fmt.Fprintln(os.Stderr, "DEBUG: STR of horses:", strengthsOfHorses) // Find diff srt of horses // Sort array of int in asc order, to easier compare forces sort.Ints(strengthsOfHorses) // Create zero point for compare all forces diffOfPower := closestToZero(strengthsOfHorses[0], strengthsOfHorses[1]) // Debug diff value fmt.Fprintln(os.Stderr, "DEBUG: First diff of 2 near: ", diffOfPower) // Find in loop, near force of two horses for i := 1; i < N; i++ { tmpDiff := closestToZero(strengthsOfHorses[i-1], strengthsOfHorses[i]) // Debug diff value fmt.Fprintln(os.Stderr, "DEBUG: Diff: ", diffOfPower, " > ", tmpDiff) if diffOfPower > tmpDiff { diffOfPower = tmpDiff } } fmt.Println(diffOfPower) // Write answer to stdout } // Find diffrence of 2 STR of horses func closestToZero(num int, num2 int) int { diff := num - num2 if diff < 0 { diff = diff * -1 } return diff }
package e2e import ( "testing" . "github.com/onsi/gomega" ) func TestSimplePublish(t *testing.T) { RegisterTestingT(t) target := getRegistry() + "/publish/simple" Expect(spectrum("build", "-b", "adoptopenjdk/openjdk8:slim", "-t", target, "--push-insecure="+getRegistryInsecure(), "./files/01-simple:/app")).To(BeNil()) assertDataMatch(t, target, isRegistryInsecure(), "/app", "./files/01-simple") } func TestDirectOverride(t *testing.T) { RegisterTestingT(t) target := getRegistry() + "/publish/override" Expect(spectrum("build", "-b", "adoptopenjdk/openjdk8:slim", "-t", target, "--push-insecure="+getRegistryInsecure(), "./files/01-simple:/app", "./files/02-override:/app")).To(BeNil()) assertDataMatch(t, target, isRegistryInsecure(), "/app", "./files/03-merge") } func TestLayerComposition(t *testing.T) { RegisterTestingT(t) target1 := getRegistry() + "/publish/layer1" Expect(spectrum("build", "-b", "adoptopenjdk/openjdk8:slim", "-t", target1, "--push-insecure="+getRegistryInsecure(), "./files/01-simple:/app")).To(BeNil()) target2 := getRegistry() + "/publish/layer2" Expect(spectrum("build", "-b", getRegistry()+"/publish/layer1", "--pull-insecure="+getRegistryInsecure(), "-t", target2, "--push-insecure="+getRegistryInsecure(), "./files/02-override:/app")).To(BeNil()) assertDataMatch(t, target2, isRegistryInsecure(), "/app", "./files/03-merge") }
package schema_test import ( "path/filepath" "runtime" ) func getPath() string { _, filename, _, _ := runtime.Caller(0) return filepath.Dir(filename) }
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // MIT License http://opensource.org/licenses/MIT // Generic stuff useful for scraping radio broadcast station program // websites. // // Most important are the two interfaces 'Scraper' and 'Broadcaster'. // // import "purl.mro.name/recorder/radio/scrape" package scrape import ( "compress/gzip" "fmt" "io" "net/http" "net/url" "os" ) func contains(haystack []string, needle string) bool { for _, s := range haystack { if needle == s { return true } } return false } /// One to fetch them all (except dlf with it's POST requests). func HttpGetBody(url url.URL) (io.Reader, *CountingReader, error) { client := &http.Client{} req, _ := http.NewRequest("GET", url.String(), nil) req.Header.Set("Accept-Encoding", "gzip, deflate") resp, err := client.Do(req) if nil == resp { return nil, nil, err } encs := resp.Header["Content-Encoding"] switch { case contains(encs, "gzip"), contains(encs, "deflate"): cr := NewCountingReader(resp.Body) ret, err := gzip.NewReader(cr) return ret, cr, err case 0 == len(encs): // NOP default: fmt.Fprintf(os.Stderr, "Strange compression: %s\n", encs) } cr := NewCountingReader(resp.Body) return cr, cr, err } /// Sadly doesn't make things really simpler func GenericParseBroadcastFromURL(url url.URL, callback func(io.Reader, *CountingReader) ([]Broadcast, error)) (bc []Broadcast, err error) { bo, cr, err := HttpGetBody(url) if nil == bo { return nil, err } return callback(bo, cr) }
package main import ( "fmt" "github.com/slowteetoe/algorithms/unionfind" "log" "math/rand" "time" ) type grid struct { n int uf unionfind.UnionFind backwash unionfind.UnionFind cells []byte top, bot int } func (g *grid) Display() { for i, val := range g.cells { if i%g.n == 0 && i != 0 { fmt.Println("") } if val == 0 { fmt.Print("*") } else { fmt.Print(".") } } fmt.Printf("\nPercolates? : %v\n\n", g.Percolates()) } func (g *grid) IsOpen(p int) bool { return g.cells[p] == 1 } func (g *grid) IsFull(p int) bool { return g.backwash.Connected(g.top, p) } func (g *grid) Open(p int) { g.cells[p] = 1 // check to see if any adjacent sites need to be joined // see if we need to join to top virtual site if p < g.n { g.uf.Union(p, g.top) g.backwash.Union(p, g.top) } if p-1 >= 0 && g.IsOpen(p-1) { g.uf.Union(p, p-1) } if p+1 < g.n*g.n && g.IsOpen(p+1) { g.uf.Union(p, p+1) } if p-g.n >= 0 && g.IsOpen(p-g.n) { g.uf.Union(p, p-g.n) } if p+g.n < g.n*g.n && g.IsOpen(p+g.n) { g.uf.Union(p, p+g.n) } // see if we need to join to bot virtual site, backwash does not have a bot virtual site if p > len(g.cells)-g.n { g.uf.Union(p, g.bot) } } func (g *grid) Percolates() bool { return g.uf.Connected(g.top, g.bot) } func NewGrid(initialSize int) grid { numCells := initialSize * initialSize // we have two "virtual sites" to reduce the number of connected() calls we need to make grid := grid{n: initialSize, uf: unionfind.NewWeightedQuickUnion(numCells + 2), backwash: unionfind.NewWeightedQuickUnion(numCells + 1), top: numCells, bot: numCells + 1} grid.cells = make([]byte, numCells) return grid } // Run percolation, returning the percentage of open sites it took to percolate func MonteCarlo(n int) (grid, int) { r := rand.New(rand.NewSource(time.Now().UnixNano())) g := NewGrid(n) cells := r.Perm(n * n) for i, cell := range cells { g.Open(cell) if g.Percolates() { log.Printf("Percolated after %v cells were opened.\n", i) return g, i } } panic("Never percolated") } func main() { for _, n := range []int{200, 400, 800, 1600, 3200} { start := time.Now() _, i := MonteCarlo(n) elapsed := time.Since(start) percentage := float64(i) / float64(n*n) fmt.Printf("(%v) %vx%v grid percolated after %v cells were opened: %f\n", elapsed, n, n, i, percentage) } }
package models import ( "time" ) type Header struct { Vendor string `json:"vendor"` Product string `json:"product"` Type string `json:"type"` Subtype string `json:"subtype"` Version string `json:"template_version"` Date string `json:"template_date"` } type Event struct { DbUser string `json:"db-user"` EventID string `json:"event-id"` EventType string `json:"event-type"` UserGroup string `json:"user-group"` UserAuthenticated string `json:"user-authenticated"` ApplicationUser string `json:"application-user"` SourceApplication string `json:"source-application"` OsUser string `json:"os-user"` OsUserChain string `json:"os-user-chain"` RawQuery string `json:"raw-query"` ParsedQuery string `json:"parsed-query"` BindVariables string `json:"bind-variables"` SqlError string `json:"sql-error"` AffectedRows int `json:"affected-rows"` ServiceType string `json:"service-type"` MxIp string `json:"mx-ip"` GwIp string `json:"gw-ip"` AgentName string `json:"agent-name"` DbSchemaPair string `json:"db-schema-pair"` DbSchemaName string `json:"db-schema-name"` StoredProcedure string `json:"stored-procedure"` OperationName string `json:"operation-name"` DatabaseName string `json:"database-name"` TableGroupName string `json:"table-group-name"` IsSensitive string `json:"is-sensitive"` IsPrivileged string `json:"is-privileged"` ObjectType string `json:"object-type"` ObjectsList string `json:"objects-list"` ResponseSize int `json:"response-size"` ResponseTime int `json:"response-time"` ExceptionOccured string `json:"exception-occurred"` ExceptionMessage string `json:"exception-message"` QueryGroup string `json:"query-group"` } type Message struct { Header Header `json:"header"` EventTime string `json:"event-time"` DayOfWeek string `json:"day-of-week"` HourOfDay string `json:"hour-of-day"` Version string `json:"SecureSphere-Version"` MxIp string `json:"mx-ip"` GwIp string `json:"gw-ip"` DestIp string `json:"dest-ip"` DestPort string `json:"dest-port"` HostName string `json:"host-name"` SourceIp string `json:"source-ip"` SourcePort string `json:"source-port"` Protocol string `json:"protocol"` Policy string `json:"policy"` ServerGroup string `json:"server-group"` ServerName string `json:"service-name"` ApplicationName string `json:"application-name"` Event Event `json:"event"` Timestamp time.Time `json:"@timestamp"` }
package spellcorrect import ( "fmt" "strings" "testing" "github.com/eskriett/spell" ) func getSpellCorrector() *SpellCorrector { tokenizer := NewSimpleTokenizer() freq := NewFrequencies(0, 0) sc := NewSpellCorrector(tokenizer, freq, []float64{100, 15, 5}) return sc } func TestTrain(t *testing.T) { trainwords := "golang 100\ngoland 1" traindata := `golang python C erlang golang java java golang goland` r := strings.NewReader(traindata) r1 := strings.NewReader(trainwords) sc := getSpellCorrector() if err := sc.Train(r, r1); err != nil { t.Errorf(err.Error()) return } if prob := sc.frequencies.Get([]string{"golang"}); prob > 0.34 && prob < 0.33 { t.Errorf("invalid prob %f", prob) return } suggestions, _ := sc.spell.Lookup("gola", spell.SuggestionLevel(spell.LevelAll)) if len(suggestions) != 2 { t.Errorf("calculated wrong suggestions") return } expected := map[string]bool{ "golang": true, "goland": true, } for i := range suggestions { if !expected[suggestions[i].Word] { t.Errorf("missing suggestion") return } } } func BenchmarkProduct(b *testing.B) { left := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"} right := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"} b.ResetTimer() for i := 0; i < b.N; i++ { product(left, right) } } func BenchmarkCombos(b *testing.B) { tokens := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"} var in [][]string for i := range tokens { var sug []string if i != 0 && i < len(tokens)/2 { for k := 1; k <= i; k++ { sug = append(sug, strings.Repeat(fmt.Sprintf("%d", i), k)) } } if len(sug) == 0 { sug = append(sug, tokens[i]) } in = append(in, sug) } b.ResetTimer() for i := 0; i < b.N; i++ { _ = combos(in) } } func TestSpellCorrect(t *testing.T) { trainwords := "golang 100\ngoland 1" traindata := `golang python C erlang golang java java golang goland` r := strings.NewReader(traindata) r1 := strings.NewReader(trainwords) sc := getSpellCorrector() if err := sc.Train(r, r1); err != nil { t.Errorf(err.Error()) return } s1 := "restaurant in Bonn" suggestions := sc.SpellCorrect(s1) if len(suggestions) != 1 { t.Errorf("error getting suggestion for not existant") return } if suggestions[0].score != 0 { t.Errorf("error getting suggestion for not existant (different)") return } } func TestGetSuggestionCandidates(t *testing.T) { tokens := []string{"1", "2", "3"} sugMap := map[int]spell.SuggestionList{ 0: spell.SuggestionList{ spell.Suggestion{Distance: 1, Entry: spell.Entry{Word: "a"}}, spell.Suggestion{Distance: 2, Entry: spell.Entry{Word: "aa"}}, }, 1: spell.SuggestionList{ spell.Suggestion{Distance: 1, Entry: spell.Entry{Word: "b"}}, }, 2: spell.SuggestionList{}, } var allSuggestions [][]string for i := range tokens { allSuggestions = append(allSuggestions, nil) allSuggestions[i] = append(allSuggestions[i], tokens[i]) suggestions, _ := sugMap[i] for j := 0; j < len(suggestions) && j < 10; j++ { allSuggestions[i] = append(allSuggestions[i], suggestions[j].Word) } } expected := [][]string{ []string{"1", "2", "3"}, []string{"a", "2", "3"}, []string{"aa", "2", "3"}, []string{"1", "b", "3"}, []string{"a", "b", "3"}, []string{"aa", "b", "3"}, } sc := getSpellCorrector() candidates := sc.getSuggestionCandidates(allSuggestions) if len(candidates) != len(expected) { t.Errorf("invalid length") return } expect := make(map[uint64]bool) for i := range expected { expect[hashTokens(expected[i])] = true } for i := range candidates { if !expect[hashTokens(candidates[i].Tokens)] { t.Errorf("%v not in expected", candidates[i].Tokens) return } } }
package main import "fmt" //import "sort" func main() { strings := []string{"syf", "syf", "oxerkx", "oxerkx", "syf", "xgwatff", "pmnfaw", "t", "ajyvgwd", "xmhb", "ajg", "syf", "syf", "wjddgkopae", "fgrpstxd", "t", "i", "psw", "wjddgkopae", "wjddgkopae", "oxerkx", "zf", "jvdtdxbefr", "rbmphtrmo", "syf", "yssdddhyn", "syf", "jvdtdxbefr", "funnd", "syf", "syf", "wd", "syf", "vnntavj", "wjddgkopae", "yssdddhyn", "wcvk", "wjddgkopae", "fh", "zf", "gpkdcwf", "qkbw", "zf", "teppnr", "jvdtdxbefr", "fmn", "i", "hzmihfrmq", "wjddgkopae", "syf", "vnntavj", "dung", "kn", "qkxo", "ajyvgwd", "fs", "kanixyaepl", "syf", "tl", "yzhaa", "dung", "wa", "syf", "jtucivim", "tl", "kanixyaepl", "oxerkx", "wjddgkopae", "ey", "ai", "zf", "di", "oxerkx", "dung", "i", "oxerkx", "wmtqpwzgh", "t", "beascd", "me", "akklwhtpi", "nxl", "cnq", "bighexy", "ddhditvzdu", "funnd", "wmt", "dgx", "fs", "xmhb", "qtcxvdcl", "thbmn", "pkrisgmr", "mkcfscyb", "x", "oxerkx", "funnd", "iesr", "funnd", "t", } patterns := []string{"enrylabgky", "enrylabgky", "dqlqaihd", "dqlqaihd", "enrylabgky", "ramsnzhyr", "tkibsntkbr", "l", "bgtws", "xwuaep", "o", "enrylabgky", "enrylabgky", "e", "auljuhtj", "l", "d", "jfzokgt", "e", "e", "dqlqaihd", "fgglhiedk", "nj", "quhv", "enrylabgky", "oadats", "enrylabgky", "nj", "zwupro", "enrylabgky", "enrylabgky", "pyw", "enrylabgky", "bedpuycdp", "e", "oadats", "i", "e", "fobyfznrxm", "fgglhiedk", "irxtd", "oyvf", "fgglhiedk", "ebpp", "nj", "p", "d", "cufxylz", "e", "enrylabgky", "bedpuycdp", "mitzb", "shsnw", "papmvh", "bgtws", "chtp", "pze", "enrylabgky", "klp", "wpx", "mitzb", "fo", "enrylabgky", "bvcigrirhe", "klp", "pze", "dqlqaihd", "e", "iufunacwjo", "bubgww", "fgglhiedk", "og", "dqlqaihd", "mitzb", "d", "dqlqaihd", "mysidv", "l", "naj", "clftmrwl", "fjb", "zjjnrffb", "sh", "gcn", "ouispza", "zwupro", "c", "rdank", "chtp", "xwuaep", "jufhm", "iyntbgm", "sufs", "mkivpe", "bxdd", "dqlqaihd", "zwupro", "vzxbbculgv", "zwupro", "l", } stringsMap := make(map[string]int) patternsMap := make(map[string]int) for _, x := range strings { stringsMap[x]++ } for _, x := range patterns { patternsMap[x]++ } if len(patternsMap) != len(stringsMap) { fmt.Println("false") return false } var stringArry []int var patternsArry []int for _, i := range stringsMap { stringArry = append(stringArry, i) } for _, i := range patternsMap { patternsArry = append(patternsArry, i) } sum1 := 0 sum2 := 0 for _, x := range stringArry { sum1 += x } for _, x := range patternsArry { sum2 += x } if sum1 == sum2 { return true } for i := 0; i < len(strings); i++ { if patternsMap[strings[i]] != stringsMap[patterns[i]] { fmt.Println("false", "arrays are not equal") return false } } fmt.Println("true") return true }
// // main.go // Copyright (C) 2019 Grigorii Sokolik <g.sokol99@g-sokol.info> // // Distributed under terms of the MIT license. // package main import ( "log" "net/http" _ "net/http/pprof" "os" "os/signal" configUtil "github.com/GSokol/go-aviasales-task/internal/config/util" "github.com/GSokol/go-aviasales-task/internal/server" "github.com/GSokol/go-aviasales-task/internal/storage" httpClient "github.com/GSokol/go-aviasales-task/pkg/aviasales/places/client" "github.com/buaazp/fasthttprouter" "github.com/kelseyhightower/envconfig" "github.com/panjf2000/ants" "github.com/valyala/fasthttp" "go.uber.org/zap" ) func main() { cfgPath := os.Getenv("AV_CONFIG_PATH") cfg, err := configUtil.Parse(cfgPath) if err != nil { log.Fatal(err) } if err := envconfig.Process("config", &cfg); err != nil { log.Fatal(err) } logger, err := cfg.Logger.Build() if err != nil { log.Fatalf("failed to init logger: %s", err) } pool, err := ants.NewTimingPool(cfg.Pool.Size, cfg.Pool.ExpiritySec) if err != nil { logger.Fatal("failed to init pool", zap.Error(err)) } client := httpClient.NewClient( httpClient.Host(cfg.Client.Host), httpClient.TimeoutMs(cfg.Client.TimeoutMs), ) cache, err := configUtil.NewCache(cfg.Cache) if err != nil { logger.Fatal("failed to init cache", zap.Error(err)) } srv := server.NewServer( storage.NewClient(client), storage.NewCached(cache), pool, logger, cfg.Client.TimeoutMs, cfg.Server.TimeoutMs, ) router := fasthttprouter.New() router.GET("/search", srv.RequestHandler()) router.GET("/healthz", server.HealthCheckHandler) httpServer := fasthttp.Server{Handler: router.Handler} idleConnsClosed := make(chan struct{}) go func() { sigint := make(chan os.Signal, 1) signal.Notify(sigint, os.Interrupt) <-sigint if err := httpServer.Shutdown(); err != nil { logger.Error("Failed to shutdowm", zap.Error(err)) logger.Sync() } close(idleConnsClosed) }() go func() { if err := http.ListenAndServe(":18080", nil); err != nil { logger.Error("Failed to start pprof server", zap.Error(err)) logger.Sync() } }() if err := httpServer.ListenAndServe(":8080"); err != nil { logger.Error("Failed to shutdowm", zap.Error(err)) logger.Sync() } <-idleConnsClosed }