text
stringlengths 11
4.05M
|
|---|
package smallNet
type NetworkConfig struct {
Network string // tcp4(ipv4 only), tcp6(ipv6 only), tcp(ipv4, ipv6)
BindAddress string // 만약 IP와 포트번호 결합이면 localhost:19999
MaxSessionCount int // 최대 클라이언트 세션 수. 넉넉하게 많이 해도 괜찮다
MaxPacketSize int // 최대 패킷 크기
RecvPacketRingBufferMaxSize int
MaxNetMsgChanBufferCount int // 네트워크 이벤트 메시지 채널 버퍼의 최대 크기
// golang은 기본은 nagle's 알고리즘은 off 시킨다. https://golang.org/pkg/net/#TCPConn.SetNoDelay
IsNoDelay bool
SockReadbuf int // 소켓 버퍼 크기-받기
SockWritebuf int // 소켓 버퍼 크기-보내기
}
|
package main
import (
"fmt"
"os"
"github.com/Cloud-Foundations/Dominator/lib/filesystem"
"github.com/Cloud-Foundations/Dominator/lib/filter"
"github.com/Cloud-Foundations/Dominator/lib/log"
)
func showImageInodeSubcommand(args []string, logger log.DebugLogger) error {
if err := showImageInode(args[0], args[1]); err != nil {
return fmt.Errorf("error showing image inode: %s", err)
}
return nil
}
func listInode(inode filesystem.GenericInode, inodePath string,
numLinks int) error {
filt, err := filter.New([]string{".*"})
if err != nil {
return err
}
return inode.List(os.Stdout, inodePath, nil, numLinks, listSelector, filt)
}
func showImageInode(image, inodePath string) error {
fs, _, err := getTypedImage(image)
if err != nil {
return err
}
filenameToInodeTable := fs.FilenameToInodeTable()
if inum, ok := filenameToInodeTable[inodePath]; !ok {
return fmt.Errorf("path: \"%s\" not present in image", inodePath)
} else if inode, ok := fs.InodeTable[inum]; !ok {
return fmt.Errorf("inode: %d not present in image", inum)
} else {
numLinksTable := fs.BuildNumLinksTable()
return listInode(inode, inodePath, numLinksTable[inum])
}
}
|
package receiver
import (
"github.com/btcsuite/btcd/chaincfg"
)
type policy struct {
SoftTimeout int
FundingMinConf int
}
var policies = map[string]policy{
"mainnet": policy{
SoftTimeout: 144,
FundingMinConf: 3,
},
"testnet3": policy{
SoftTimeout: 32,
FundingMinConf: 1,
},
}
func getPolicy(net *chaincfg.Params) policy {
p, ok := policies[net.Name]
if ok {
return p
} else {
return policies["mainnet"]
}
}
|
/*
Go Language Raspberry Pi Interface
(c) Copyright David Thorpe 2016-2018
All Rights Reserved
Documentation http://djthorpe.github.io/gopi/
For Licensing and Usage information, please see LICENSE.md
*/
// Interacts with the BME280 sensor
package main
import (
"errors"
"fmt"
"os"
// Frameworks
"github.com/djthorpe/gopi"
"github.com/djthorpe/sensors"
"github.com/olekukonko/tablewriter"
// Modules
_ "github.com/djthorpe/gopi/sys/logger"
_ "github.com/djthorpe/sensors/sys/bme280"
)
const (
COMMAND_MEASURE = iota
COMMAND_RESET
COMMAND_STATUS
COMMAND_HELP
)
////////////////////////////////////////////////////////////////////////////////
func GetModeFromString(mode string) (sensors.BME280Mode, error) {
switch mode {
case "normal":
return sensors.BME280_MODE_NORMAL, nil
case "forced":
return sensors.BME280_MODE_FORCED, nil
case "sleep":
return sensors.BME280_MODE_SLEEP, nil
default:
return sensors.BME280_MODE_NORMAL, fmt.Errorf("Invalid mode: %v", mode)
}
}
func GetOversampleFromUint(value uint) (sensors.BME280Oversample, error) {
switch value {
case 0:
return sensors.BME280_OVERSAMPLE_SKIP, nil
case 1:
return sensors.BME280_OVERSAMPLE_1, nil
case 2:
return sensors.BME280_OVERSAMPLE_2, nil
case 4:
return sensors.BME280_OVERSAMPLE_4, nil
case 8:
return sensors.BME280_OVERSAMPLE_8, nil
case 16:
return sensors.BME280_OVERSAMPLE_16, nil
default:
return sensors.BME280_OVERSAMPLE_SKIP, fmt.Errorf("Invalid oversample value: %v", value)
}
}
func GetFilterFromUint(value uint) (sensors.BME280Filter, error) {
switch value {
case 0:
return sensors.BME280_FILTER_OFF, nil
case 2:
return sensors.BME280_FILTER_2, nil
case 4:
return sensors.BME280_FILTER_4, nil
case 8:
return sensors.BME280_FILTER_8, nil
case 16:
return sensors.BME280_FILTER_16, nil
default:
return sensors.BME280_FILTER_OFF, fmt.Errorf("Invalid filter value: %v", value)
}
}
func GetStandbyFromFloat(value float64) (sensors.BME280Standby, error) {
switch value {
case 0.5:
return sensors.BME280_STANDBY_0P5MS, nil
case 62.5:
return sensors.BME280_STANDBY_62P5MS, nil
case 125:
return sensors.BME280_STANDBY_125MS, nil
case 250:
return sensors.BME280_STANDBY_250MS, nil
case 500:
return sensors.BME280_STANDBY_500MS, nil
case 1000:
return sensors.BME280_STANDBY_1000MS, nil
case 10:
return sensors.BME280_STANDBY_10MS, nil
case 20:
return sensors.BME280_STANDBY_20MS, nil
default:
return sensors.BME280_STANDBY_MAX, fmt.Errorf("Invalid standby value: %v", value)
}
}
////////////////////////////////////////////////////////////////////////////////
func status(device sensors.BME280) error {
// Output register information
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Register", "Value"})
chip_id, chip_version := device.ChipIDVersion()
table.Append([]string{"chip_id", fmt.Sprintf("0x%02X", chip_id)})
table.Append([]string{"chip_version", fmt.Sprintf("0x%02X", chip_version)})
table.Append([]string{"mode", fmt.Sprint(device.Mode())})
table.Append([]string{"filter", fmt.Sprint(device.Filter())})
table.Append([]string{"standby", fmt.Sprint(device.Standby())})
table.Append([]string{"duty cycle", fmt.Sprint(device.DutyCycle())})
t, p, h := device.Oversample()
table.Append([]string{"oversample temperature", fmt.Sprint(t)})
table.Append([]string{"oversample pressure", fmt.Sprint(p)})
table.Append([]string{"oversample humidity", fmt.Sprint(h)})
if measuring, updating, err := device.Status(); err != nil {
return err
} else {
table.Append([]string{"measuring", fmt.Sprint(measuring)})
table.Append([]string{"updating", fmt.Sprint(updating)})
}
table.Render()
return nil
}
func measure(device sensors.BME280, sealevel_hpa float64) error {
// If oversample temperature is in skip mode, then set to 1 to ensure
// we have at least one thing to measure!
if t_os, p_os, h_os := device.Oversample(); t_os == sensors.BME280_OVERSAMPLE_SKIP {
if err := device.SetOversample(sensors.BME280_OVERSAMPLE_1, p_os, h_os); err != nil {
return err
}
}
// If sensor is in sleep mode then change to forced mode,
// which will return it to sleep mode once the sample
// has been read
if device.Mode() == sensors.BME280_MODE_SLEEP {
if err := device.SetMode(sensors.BME280_MODE_FORCED); err != nil {
return err
}
}
if t, p, h, err := device.ReadSample(); err != nil {
return err
} else {
a := device.AltitudeForPressure(p, sealevel_hpa*100)
table := tablewriter.NewWriter(os.Stdout)
table.SetAlignment(tablewriter.ALIGN_RIGHT)
table.SetHeader([]string{"Measurement", "Value"})
if t > 0 {
table.Append([]string{"temperature", fmt.Sprintf("%.2f \u00B0C", t)})
}
if p > 0.0 {
table.Append([]string{"pressure", fmt.Sprintf("%.2f hPa", p/100.0)})
table.Append([]string{"altitude", fmt.Sprintf("%.2f m", a)})
}
if h > 0 {
table.Append([]string{"humidity", fmt.Sprintf("%.2f %%RH", h)})
}
table.Render()
}
return nil
}
func reset(device sensors.BME280) error {
if err := device.SoftReset(); err != nil {
return err
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// SET
func set_mode(device sensors.BME280, mode string) error {
if mode_value, err := GetModeFromString(mode); err != nil {
return err
} else if err := device.SetMode(mode_value); err != nil {
return err
} else {
return nil
}
}
func set_filter(device sensors.BME280, filter uint) error {
if filter_value, err := GetFilterFromUint(filter); err != nil {
return err
} else if err := device.SetFilter(filter_value); err != nil {
return err
} else {
return nil
}
}
func set_oversample(device sensors.BME280, oversample uint) error {
if oversample_value, err := GetOversampleFromUint(oversample); err != nil {
return err
} else if err := device.SetOversample(oversample_value, oversample_value, oversample_value); err != nil {
return err
} else {
return nil
}
}
func set_standby(device sensors.BME280, standby float64) error {
if standby_value, err := GetStandbyFromFloat(standby); err != nil {
return err
} else if err := device.SetStandby(standby_value); err != nil {
return err
} else {
return nil
}
}
func set(app *gopi.AppInstance, device sensors.BME280) error {
if mode, exists := app.AppFlags.GetString("mode"); exists {
if err := set_mode(device, mode); err != nil {
return err
}
}
if filter, exists := app.AppFlags.GetUint("filter"); exists {
if err := set_filter(device, filter); err != nil {
return err
}
}
if oversample, exists := app.AppFlags.GetUint("oversample"); exists {
if err := set_oversample(device, oversample); err != nil {
return err
}
}
if standby, exists := app.AppFlags.GetFloat64("standby"); exists {
if err := set_standby(device, standby); err != nil {
return err
}
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// MAIN FUNCTION
func MainLoop(app *gopi.AppInstance, done chan<- struct{}) error {
// Determine the command to run
command := COMMAND_HELP
if args := app.AppFlags.Args(); len(args) == 1 && args[0] == "reset" {
command = COMMAND_RESET
} else if len(args) == 1 && args[0] == "status" {
command = COMMAND_STATUS
} else if len(args) == 0 || len(args) == 1 && args[0] == "measure" {
command = COMMAND_MEASURE
}
// Get sealevel pressure value
sealevel, _ := app.AppFlags.GetFloat64("sealevel")
// Run the command
if device := app.ModuleInstance(MODULE_NAME).(sensors.BME280); device == nil {
return errors.New("BME280 module not found")
} else {
switch command {
case COMMAND_MEASURE:
if err := set(app, device); err != nil {
return err
}
if err := measure(device, sealevel); err != nil {
return err
}
case COMMAND_RESET:
if err := reset(device); err != nil {
return err
}
if err := set(app, device); err != nil {
return err
}
if err := status(device); err != nil {
return err
}
case COMMAND_STATUS:
if err := set(app, device); err != nil {
return err
}
if err := status(device); err != nil {
return err
}
default:
return gopi.ErrHelp
}
}
// Exit
done <- gopi.DONE
return nil
}
////////////////////////////////////////////////////////////////////////////////
func main() {
// Create the configuration
config := gopi.NewAppConfig(MODULE_NAME)
config.AppFlags.SetUsageFunc(func(flags *gopi.Flags) {
fmt.Fprintf(os.Stderr, "Usage: %v <flags> (reset|status|measure)\n\n", flags.Name())
fmt.Fprintf(os.Stderr, "Flags:\n")
flags.PrintDefaults()
})
// Parameters
config.AppFlags.FlagString("mode", "", "Sensor mode (normal,forced,sleep)")
config.AppFlags.FlagUint("filter", 0, "Filter co-efficient (0,2,4,8,16)")
config.AppFlags.FlagUint("oversample", 0, "Oversampling (0,1,2,4,8,16)")
config.AppFlags.FlagFloat64("sealevel", sensors.BME280_PRESSURE_SEALEVEL/100.0, "Sealevel atmospheric pressure in hPa")
config.AppFlags.FlagFloat64("standby", 0, "Standby time, ms (0.5,10,20,62.5,125,250,500,1000)")
// Run the command line tool
os.Exit(gopi.CommandLineTool(config, MainLoop))
}
|
package goSolution
import "testing"
func TestSolveNQueens(t *testing.T) {
answer := [][]string{{".Q..","...Q","Q...","..Q."},{"..Q.","Q...","...Q",".Q.."}}
AssertEqual(t, answer, solveNQueens(4))
}
|
/*
* @lc app=leetcode.cn id=134 lang=golang
*
* [134] 加油站
*/
// @lc code=start
package main
import "fmt"
import "math"
func main() {
var gas, cost []int
gas = []int{1,2,3,4,5}
cost = []int{3,4,5,1,2}
fmt.Println(canCompleteCircuit(gas, cost))
gas = []int{2,3,4}
cost = []int{3,4,3}
fmt.Println(canCompleteCircuit(gas, cost))
gas = []int{5,8,2,8}
cost = []int{6,5,6,6}
fmt.Println(canCompleteCircuit(gas, cost))
}
func canCompleteCircuit2(gas []int, cost []int) int {
tmp := make([]int, len(gas))
for i := 0 ; i < len(gas) ; i++ {
tmp[i] = gas[i] - cost[i]
}
index := findBigger(tmp)
newTmp := tmp[index:len(tmp)]
newTmp = append(newTmp, tmp[0:index]...)
sum := 0
for i := 0 ; i < len(newTmp) ; i++ {
sum += newTmp[i]
if sum < 0 {
return -1
}
}
return index
}
func findBigger(a []int) int {
maxV := math.MinInt32
var maxI int
for i := 0 ; i < len(a) ; i ++ {
if a[i] > maxV {
maxV = a[i]
maxI = i
}
}
return maxI
}
// @lc code=end
func canCompleteCircuit(gas []int, cost []int) int {
n := len(gas)
for i := 0 ; i < n ; {
count := 0
sumOfGas := 0
sumOfCost := 0
for count < n {
j := (i + count ) % n
sumOfGas += gas[j]
sumOfCost += cost[j]
if sumOfGas < sumOfCost {
break
}
count++
}
if count == n {
return i
} else {
i += count + 1
}
}
return -1
}
|
package flash
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestNew(t *testing.T) {
Convey("Given new flash", t, func() {
f := New()
Convey("Flash should not be nil", func() {
So(f, ShouldNotBeNil)
})
Convey("Flash data should be empty", func() {
So(f.v, ShouldBeEmpty)
})
Convey("Flash count should be empty", func() {
So(f.Count(), ShouldEqual, 0)
})
Convey("Flash should not in changed state", func() {
So(f.Changed(), ShouldBeFalse)
})
Convey("Flash should be able to encode", func() {
b, err := f.Encode()
Convey("Without error", func() {
So(err, ShouldBeNil)
})
Convey("Encoded result should not be nil", func() {
So(b, ShouldNotBeNil)
})
Convey("Encoded bytes should be empty", func() {
So(b, ShouldBeEmpty)
})
Convey("Flash still unchanged", func() {
So(f.Changed(), ShouldBeFalse)
})
})
Convey("When add a data to flash", func() {
f.Add("a", 1)
Convey("Flash should be in changed state", func() {
So(f.Changed(), ShouldBeTrue)
})
Convey("Count should changed", func() {
So(f.Count(), ShouldEqual, 1)
})
})
})
}
func TestClear(t *testing.T) {
Convey("Given empty flash", t, func() {
f := New()
Convey("When clear", func() {
f.Clear()
Convey("Should not be in changed state", func() {
So(f.Changed(), ShouldBeFalse)
})
})
})
Convey("Given not empty flash", t, func() {
f := New()
f.Add("a", 1)
Convey("When clear", func() {
f.Clear()
Convey("Flash data should be empty", func() {
So(f.v, ShouldBeEmpty)
})
Convey("Count should be zero", func() {
So(f.Count(), ShouldBeZeroValue)
})
Convey("Should be in changed state", func() {
So(f.Changed(), ShouldBeTrue)
})
Convey("When clear again", func() {
Convey("Should still be in changed state", func() {
So(f.Changed(), ShouldBeTrue)
})
})
})
})
}
func TestEncodeDecode(t *testing.T) {
Convey("Given not empty flash", t, func() {
f := New()
f.Add("a", 1)
Convey("Should be able to encode", func() {
b, err := f.Encode()
Convey("Without error", func() {
So(err, ShouldBeNil)
})
Convey("Encoded result should not be nil", func() {
So(b, ShouldNotBeNil)
})
Convey("Encoded bytes should not be empty", func() {
So(b, ShouldNotBeEmpty)
})
Convey("Flash should still be changed state", func() {
So(f.Changed(), ShouldBeTrue)
})
Convey("Encoded data should be able to decode", func() {
f, err := Decode(b)
Convey("Without error", func() {
So(err, ShouldBeNil)
})
Convey("Decoded flash should not be nil", func() {
So(f, ShouldNotBeNil)
})
Convey("With same count", func() {
So(f.Count(), ShouldEqual, 1)
})
Convey("With same data", func() {
So(f.v["a"], ShouldNotBeEmpty)
So(f.v["a"][0], ShouldEqual, 1)
})
})
})
})
Convey("Given flash with invalid data", t, func() {
f := New()
f.Set("key", &struct{}{})
Convey("When encode", func() {
b, err := f.Encode()
Convey("Should error", func() {
So(err, ShouldNotBeNil)
})
Convey("Encoded bytes should be empty", func() {
So(b, ShouldBeEmpty)
})
})
})
Convey("Given empty bytes", t, func() {
b := []byte{}
Convey("Bytes should be able to decode", func() {
f, err := Decode(b)
Convey("Without error", func() {
So(err, ShouldBeNil)
})
Convey("Flash should not be nil", func() {
So(f, ShouldNotBeNil)
})
Convey("Flash data should be empty", func() {
So(f.v, ShouldBeEmpty)
})
Convey("Flash count should be zero", func() {
So(f.Count(), ShouldBeZeroValue)
})
Convey("Flash should not in changed state", func() {
So(f.Changed(), ShouldBeFalse)
})
})
})
Convey("Given invalid encoded flash bytes", t, func() {
b := []byte("invalid data")
Convey("When decode", func() {
f, err := Decode(b)
Convey("Should error", func() {
So(err, ShouldNotBeNil)
})
Convey("Returns flash should be nil", func() {
So(f, ShouldBeNil)
})
})
})
}
func TestDel(t *testing.T) {
Convey("Given not empty flash", t, func() {
f := New()
f.Add("a", 1)
Convey("When delete all keys", func() {
f.Del("a")
Convey("Should still be in changed state", func() {
So(f.Changed(), ShouldBeTrue)
})
})
})
}
func TestValues(t *testing.T) {
Convey("Given empty flash", t, func() {
f := New()
Convey("When retrieve values from not exists key", func() {
v := f.Values("a")
Convey("Should return non-nil values", func() {
So(v, ShouldNotBeNil)
})
Convey("Should return empty data", func() {
So(v, ShouldBeEmpty)
})
})
Convey("When add 3 values same key", func() {
f.Add("a", 1)
f.Add("a", 2)
f.Add("a", 3)
Convey("When retrieve values for that key", func() {
v := f.Values("a")
Convey("Should resemble added values", func() {
So(v, ShouldResemble, []interface{}{1, 2, 3})
})
Convey("Should not disapper in flash", func() {
So(f.Has("a"), ShouldBeFalse)
})
})
})
})
}
func TestGet(t *testing.T) {
Convey("Given empty flash", t, func() {
f := New()
Convey("When get not exists key", func() {
v := f.Get("a")
Convey("Should return nil", func() {
So(v, ShouldBeNil)
})
Convey("Should still be unchanged state", func() {
So(f.Changed(), ShouldBeFalse)
})
})
Convey("When set a value", func() {
f.Set("a", 1)
Convey("Should has that key", func() {
So(f.Has("a"), ShouldBeTrue)
})
Convey("When get that key", func() {
v := f.Get("a")
Convey("Should return same value", func() {
So(v, ShouldEqual, 1)
})
Convey("Key should disappear", func() {
So(f.Has("a"), ShouldBeFalse)
})
})
})
Convey("When set a string value", func() {
f.Set("a", "hello")
Convey("When get string from that key", func() {
v := f.GetString("a")
Convey("Should return same value", func() {
So(v, ShouldEqual, "hello")
})
})
Convey("When get int from that key", func() {
v := f.GetInt("a")
Convey("Should return zero value", func() {
So(v, ShouldBeZeroValue)
})
})
Convey("When get int64 from that key", func() {
v := f.GetInt64("a")
Convey("Should return zero value", func() {
So(v, ShouldBeZeroValue)
})
})
Convey("When get float32 from that key", func() {
v := f.GetFloat32("a")
Convey("Should return zero value", func() {
So(v, ShouldBeZeroValue)
})
})
Convey("When get float64 from that key", func() {
v := f.GetFloat64("a")
Convey("Should return zero value", func() {
So(v, ShouldBeZeroValue)
})
})
Convey("When get bool from that key", func() {
v := f.GetBool("a")
Convey("Should return zero value", func() {
So(v, ShouldBeZeroValue)
})
})
})
})
}
func TestClone(t *testing.T) {
Convey("Given not empty flash", t, func() {
f := New()
f.Add("a", "1")
f.Add("a", "2")
f.Add("b", "3")
Convey("When clone", func() {
p := f.Clone()
Convey("Should not point to original", func() {
So(p, ShouldNotPointTo, f)
})
Convey("Data should have same count", func() {
So(p.Count(), ShouldEqual, f.Count())
})
Convey("Data should have same values", func() {
So(p.v, ShouldResemble, f.v)
})
Convey("When clear original flash", func() {
f.Clear()
Convey("Clone data should not resemble original data", func() {
So(p.v, ShouldNotResemble, f.v)
})
})
})
})
}
func TestCount(t *testing.T) {
Convey("Given empty flash", t, func() {
f := New()
Convey("Should have 0 count", func() {
So(f.Count(), ShouldEqual, 0)
})
Convey("When set a value", func() {
f.Set("a", true)
Convey("Should have 1 count", func() {
So(f.Count(), ShouldEqual, 1)
})
Convey("When get that value", func() {
f.Get("a")
Convey("Should back to 0 count", func() {
So(f.Count(), ShouldEqual, 0)
})
})
})
Convey("When set 2 values", func() {
f.Set("a", 1)
f.Set("b", 2)
Convey("Should have 2 count", func() {
So(f.Count(), ShouldEqual, 2)
})
})
})
}
|
package main
import (
"bytes"
"crypto/tls"
b64 "encoding/base64"
"fmt"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gerald1248/timeline"
"github.com/kabukky/httpscerts"
"io/ioutil"
"log"
"net/http"
"time"
)
type PostStruct struct {
Buffer string
}
func serve(certificate, key, hostname string, port int) {
virtual_fs := &assetfs.AssetFS{
Asset: timeline.Asset,
AssetDir: timeline.AssetDir,
AssetInfo: timeline.AssetInfo}
//set up custom mux
mux := http.NewServeMux()
mux.Handle("/static/", http.FileServer(virtual_fs))
mux.HandleFunc("/timeline/compose", guiHandler)
mux.HandleFunc("/timeline", handler)
err := httpscerts.Check(certificate, key)
if err != nil {
cert, key, err := httpscerts.GenerateArrays(fmt.Sprintf("%s:%d", hostname, port))
if err != nil {
log.Fatal("Can't create https certs")
}
keyPair, err := tls.X509KeyPair(cert, key)
if err != nil {
log.Fatal("Can't create key pair")
}
var certificates []tls.Certificate
certificates = append(certificates, keyPair)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
Certificates: certificates,
}
s := &http.Server{
Addr: fmt.Sprintf("%s:%d", hostname, port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
TLSConfig: cfg,
}
fmt.Print(listening(hostname, port, true))
log.Fatal(s.ListenAndServeTLS("", ""))
}
fmt.Print(listening(hostname, port, false))
log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", hostname, port), certificate, key, mux))
}
func listening(hostname string, port int, selfCert bool) string {
var selfCertMsg string
if selfCert {
selfCertMsg = " (self-certified)"
}
return fmt.Sprintf("Listening on port %d%s\n"+
"POST JSON sources to https://%s:%d/timeline\n"+
"Generate report at https://%s:%d/timeline/compose\n", port, selfCertMsg, hostname, port, hostname, port)
}
/*
func serve(certificate, key, hostname string, port int) {
virtual_fs := &assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
AssetInfo: AssetInfo}
err := httpscerts.Check(certificate, key)
if err != nil {
err = httpscerts.Generate(certificate, key, fmt.Sprintf("%s:%d", hostname, port))
if err != nil {
log.Fatal("Can't create https certs")
}
fmt.Printf("Created %s and %s\n", certificate, key)
}
http.Handle("/static/", http.FileServer(virtual_fs))
http.HandleFunc("/timeline/compose", guiHandler)
http.HandleFunc("/timeline", handler)
fmt.Printf("Listening on port %d\n"+
"POST JSON sources to https://%s:%d/timeline\n"+
"Compose timelines at https://%s:%d/timeline/compose\n", port, hostname, port, hostname, port)
log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", hostname, port), certificate, key, nil))
}
*/
func guiHandler(w http.ResponseWriter, r *http.Request) {
bytes, _ := timeline.Asset("static/index.html")
fmt.Fprintf(w, "%s\n", string(bytes))
}
func handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
handlePost(&w, r)
case "GET":
handleGet(&w, r)
}
}
func handleGet(w *http.ResponseWriter, r *http.Request) {
fmt.Fprintf(*w, "GET request\nRequest struct = %v\n", r)
}
func handlePost(w *http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(*w, "Can't read POST request body: %s\n", err)
return
}
result := timeline.ProcessBytes(body)
if result.Code > 0 {
fmt.Fprintf(*w, "<p>%s</p>", result.Message)
return
}
//now display using base64 data
buf := new(bytes.Buffer)
err = result.Context.EncodePNG(buf)
if err != nil {
fmt.Fprintf(*w, "<p>Can't encode resulting image: %v</p>", err)
return
}
//TBD: option to return bytestream
s := b64.StdEncoding.EncodeToString(buf.Bytes())
fmt.Fprintf(*w, "<img class=\"img-responsive\" alt=\"Timeline\" src=\"data:image/png;base64,%s\"/>", s)
}
|
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package middleware
import (
"net/http"
"strings"
"github.com/clivern/walrus/core/driver"
"github.com/clivern/walrus/core/model"
"github.com/clivern/walrus/core/util"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// Auth middleware
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
method := c.Request.Method
reqAPIKey := c.GetHeader("x-api-key")
clientID := c.GetHeader("x-client-id")
clientEmail := c.GetHeader("x-user-email")
apiKey := ""
if viper.GetString("role") == "tower" {
apiKey = viper.GetString("tower.api.key")
} else if viper.GetString("role") == "agent" {
apiKey = viper.GetString("agent.api.key")
}
// Skip if endpoint not protected API
if !strings.Contains(path, "/api/") {
return
}
// Validate API Call
if clientID != "dashboard" {
if apiKey != "" && apiKey != reqAPIKey {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"http_method": method,
"http_path": path,
"request_api_key": reqAPIKey,
}).Info(`Unauthorized access`)
c.AbortWithStatus(http.StatusUnauthorized)
}
return
}
// Validate Logged User Request
if !util.IsEmailValid(clientEmail) || util.IsEmpty(reqAPIKey) {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"http_method": method,
"http_path": path,
"api_key": reqAPIKey,
"client_email": clientEmail,
}).Info(`Unauthorized access`)
c.AbortWithStatus(http.StatusUnauthorized)
}
db := driver.NewEtcdDriver()
err := db.Connect()
if err != nil {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"error": err.Error(),
}).Error("Internal server error")
c.JSON(http.StatusInternalServerError, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Internal server error",
})
return
}
defer db.Close()
userStore := model.NewUserStore(db)
user, err := userStore.GetUserByEmail(clientEmail)
if err != nil || user.APIKey != reqAPIKey {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"http_method": method,
"http_path": path,
"api_key": reqAPIKey,
"client_email": clientEmail,
}).Info(`Unauthorized access`)
c.AbortWithStatus(http.StatusUnauthorized)
}
}
}
|
package leetcode
/*We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/uncommon-words-from-two-sentences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
import "strings"
func uncommonFromSentences(A string, B string) []string {
strMap := make(map[string]int)
res := make([]string, 0)
subA := strings.Split(A, " ")
subB := strings.Split(B, " ")
for _, str := range subA {
v, ok := strMap[str]
if !ok {
strMap[str] = 1
} else {
strMap[str] = v + 1
}
}
for _, str := range subB {
v, ok := strMap[str]
if !ok {
strMap[str] = 1
} else {
strMap[str] = v + 1
}
}
for k, v := range strMap {
if v == 1 {
res = append(res, k)
}
}
return res
}
|
package virtual_security
import (
"errors"
"log"
"reflect"
"testing"
"time"
)
type testStockService struct {
iStockService
newOrderCode1 []string
newOrderCodeCount int
confirmContract1 error
confirmContractCount int
getStockOrders1 []*stockOrder
getStockOrderByCode1 *stockOrder
getStockOrderByCode2 error
getStockOrderByCodeHistory []string
removeStockOrderByCodeHistory []string
getStockPositions1 []*stockPosition
removeStockPositionByCodeHistory []string
addStockOrder1 error
addStockOrderHistory []*stockOrder
toStockOrder1 *stockOrder
holdSellOrderPositions1 error
validation1 error
cancelAndRelease1 error
cancelAndReleaseCount int
}
func (t *testStockService) saveStockOrder(order *stockOrder) {
t.addStockOrderHistory = append(t.addStockOrderHistory, order)
}
func (t *testStockService) newOrderCode() string {
defer func() { t.newOrderCodeCount++ }()
return t.newOrderCode1[t.newOrderCodeCount%len(t.newOrderCode1)]
}
func (t *testStockService) confirmContract(*stockOrder, *symbolPrice, time.Time) error {
t.confirmContractCount++
return t.confirmContract1
}
func (t *testStockService) getStockOrders() []*stockOrder {
return t.getStockOrders1
}
func (t *testStockService) getStockOrderByCode(orderCode string) (*stockOrder, error) {
t.getStockOrderByCodeHistory = append(t.getStockOrderByCodeHistory, orderCode)
return t.getStockOrderByCode1, t.getStockOrderByCode2
}
func (t *testStockService) removeStockOrderByCode(orderCode string) {
t.removeStockOrderByCodeHistory = append(t.removeStockOrderByCodeHistory, orderCode)
}
func (t *testStockService) getStockPositions() []*stockPosition {
return t.getStockPositions1
}
func (t *testStockService) removeStockPositionByCode(positionCode string) {
t.removeStockPositionByCodeHistory = append(t.removeStockPositionByCodeHistory, positionCode)
}
func (t *testStockService) toStockOrder(*StockOrderRequest, time.Time) *stockOrder {
return t.toStockOrder1
}
func (t *testStockService) holdSellOrderPositions(*stockOrder) error {
return t.holdSellOrderPositions1
}
func (t *testStockService) validation(*stockOrder, time.Time) error {
return t.validation1
}
func (t *testStockService) cancelAndRelease(*stockOrder, time.Time) error {
t.cancelAndReleaseCount++
return t.cancelAndRelease1
}
func Test_stockService_entry(t *testing.T) {
t.Parallel()
tests := []struct {
name string
stockService *stockService
arg1 *stockOrder
arg2 *symbolPrice
arg3 time.Time
want error
wantArg1 *stockOrder
wantPositionStoreSave []*stockPosition
}{
{name: "引数1がnilならエラー",
stockService: &stockService{},
arg1: nil,
arg2: &symbolPrice{},
want: NilArgumentError,
wantArg1: nil,
wantPositionStoreSave: nil},
{name: "引数2がnilならエラー",
stockService: &stockService{},
arg1: &stockOrder{},
arg2: nil,
want: NilArgumentError,
wantArg1: &stockOrder{},
wantPositionStoreSave: nil},
{name: "約定チェックで約定していなかったら何もしない",
stockService: &stockService{
stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: &confirmContractResult{isContracted: false}}},
arg1: &stockOrder{},
arg2: &symbolPrice{},
want: nil,
wantArg1: &stockOrder{},
wantPositionStoreSave: nil},
{name: "それぞれコードを生成し、注文、ポジションをstoreに保存する",
stockService: &stockService{
stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: &confirmContractResult{
isContracted: true,
price: 1000,
contractedAt: time.Date(2021, 6, 21, 10, 1, 0, 0, time.Local)}},
uuidGenerator: &testUUIDGenerator{generator1: []string{"uuid-1", "uuid-2", "uuid-3"}}},
arg1: &stockOrder{
Code: "sor-1",
SymbolCode: "1234",
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
OrderQuantity: 100,
OrderedAt: time.Date(2021, 6, 21, 10, 0, 0, 0, time.Local),
ConfirmingCount: 1,
},
arg2: &symbolPrice{},
want: nil,
wantArg1: &stockOrder{
Code: "sor-1",
OrderStatus: OrderStatusDone,
SymbolCode: "1234",
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
OrderQuantity: 100,
ContractedQuantity: 100,
OrderedAt: time.Date(2021, 6, 21, 10, 0, 0, 0, time.Local),
Contracts: []*Contract{{ContractCode: "sco-uuid-1", OrderCode: "sor-1", PositionCode: "spo-uuid-2", Price: 1000, Quantity: 100, ContractedAt: time.Date(2021, 6, 21, 10, 1, 0, 0, time.Local)}},
ConfirmingCount: 1,
},
wantPositionStoreSave: []*stockPosition{
{
Code: "spo-uuid-2",
OrderCode: "sor-1",
SymbolCode: "1234",
Side: SideBuy,
ContractedQuantity: 100,
OwnedQuantity: 100,
HoldQuantity: 0,
Price: 1000,
ContractedAt: time.Date(2021, 6, 21, 10, 1, 0, 0, time.Local),
},
}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
stockOrderStore := &testStockOrderStore{}
stockPositionStore := &testStockPositionStore{}
test.stockService.stockOrderStore = stockOrderStore
test.stockService.stockPositionStore = stockPositionStore
got := test.stockService.entry(test.arg1, test.arg2, test.arg3)
if !errors.Is(got, test.want) ||
!reflect.DeepEqual(test.wantArg1, test.arg1) ||
!reflect.DeepEqual(test.wantPositionStoreSave, stockPositionStore.saveHistory) {
t.Errorf("%s error\nwant: %+v, %+v, %+v\ngot: %+v, %+v, %+v\n", t.Name(),
test.want, test.wantArg1, test.wantPositionStoreSave,
got, test.arg1, stockPositionStore.saveHistory)
}
})
}
}
func Test_stockService_exit(t *testing.T) {
t.Parallel()
tests := []struct {
name string
stockService *stockService
stockPositionStore *testStockPositionStore
arg1 *stockOrder
arg2 *symbolPrice
arg3 time.Time
want error
wantArg1 *stockOrder
wantPosition *stockPosition
}{
{name: "引数1がnilならエラー",
stockService: &stockService{},
stockPositionStore: &testStockPositionStore{},
arg1: nil,
arg2: &symbolPrice{},
want: NilArgumentError,
wantArg1: nil,
wantPosition: nil},
{name: "引数2がnilならエラー",
stockService: &stockService{},
stockPositionStore: &testStockPositionStore{},
arg1: &stockOrder{},
arg2: nil,
want: NilArgumentError,
wantArg1: &stockOrder{},
wantPosition: nil},
{name: "約定チェックで約定していなかったら何もしない",
stockService: &stockService{stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: &confirmContractResult{isContracted: false}}},
stockPositionStore: &testStockPositionStore{},
arg1: &stockOrder{},
arg2: &symbolPrice{},
want: nil,
wantArg1: &stockOrder{},
wantPosition: nil},
{name: "注文がholdしていたpositionが見つからなければそのポジションの処理をスキップする",
stockService: &stockService{stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: &confirmContractResult{isContracted: true}}},
stockPositionStore: &testStockPositionStore{getByCode1: nil, getByCode2: NoDataError},
arg1: &stockOrder{Code: "sor-1", OrderQuantity: 400, HoldPositions: []*HoldPosition{{PositionCode: "spo-0", HoldQuantity: 400}}},
arg2: &symbolPrice{},
want: nil,
wantArg1: &stockOrder{Code: "sor-1", OrderQuantity: 400, HoldPositions: []*HoldPosition{{PositionCode: "spo-0", HoldQuantity: 400}}},
wantPosition: nil},
{name: "注文がholdしていたpositionをexitする",
stockService: &stockService{
uuidGenerator: &testUUIDGenerator{generator1: []string{"uuid-1", "uuid-2", "uuid-3", "uuid-4", "uuid-5"}},
stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: &confirmContractResult{isContracted: true, price: 1000, contractedAt: time.Date(2021, 6, 21, 10, 1, 0, 0, time.Local)}}},
stockPositionStore: &testStockPositionStore{getByCode1: &stockPosition{Code: "spo-0", OwnedQuantity: 1000, HoldQuantity: 1000}},
arg1: &stockOrder{Code: "sor-1", OrderQuantity: 400, HoldPositions: []*HoldPosition{{PositionCode: "spo-0", HoldQuantity: 400}}},
arg2: &symbolPrice{},
want: nil,
wantArg1: &stockOrder{
Code: "sor-1",
OrderStatus: OrderStatusDone,
OrderQuantity: 400,
ContractedQuantity: 400,
Contracts: []*Contract{{
ContractCode: "sco-uuid-1",
OrderCode: "sor-1",
PositionCode: "spo-0",
Price: 1000,
Quantity: 400,
ContractedAt: time.Date(2021, 6, 21, 10, 1, 0, 0, time.Local),
}},
HoldPositions: []*HoldPosition{{PositionCode: "spo-0", HoldQuantity: 400, ExitQuantity: 400}}},
wantPosition: &stockPosition{Code: "spo-0", OwnedQuantity: 600, HoldQuantity: 600}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
test.stockService.stockPositionStore = test.stockPositionStore
got := test.stockService.exit(test.arg1, test.arg2, test.arg3)
if !errors.Is(got, test.want) ||
!reflect.DeepEqual(test.wantArg1, test.arg1) ||
!reflect.DeepEqual(test.wantPosition, test.stockPositionStore.getByCode1) {
t.Errorf("%s error\nwant: %+v, %+v, %+v\ngot: %+v, %+v, %+v\n", t.Name(),
test.want, test.wantArg1, test.wantPosition,
got, test.arg1, test.stockPositionStore.getByCode1)
}
})
}
}
func Test_stockService_NewOrderCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
uuidGenerator iUUIDGenerator
want string
}{
{name: "uuidの結果に接頭辞を付けて返す", uuidGenerator: &testUUIDGenerator{generator1: []string{"uuid-1", "uuid-2", "uuid-3"}}, want: "sor-uuid-1"},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{uuidGenerator: test.uuidGenerator}
got := service.newOrderCode()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_GetStockOrders(t *testing.T) {
t.Parallel()
tests := []struct {
name string
stockService iStockService
want []*stockOrder
}{
{name: "storeの結果が空なら空",
stockService: &stockService{stockOrderStore: &testStockOrderStore{getAll1: []*stockOrder{}}},
want: []*stockOrder{}},
{name: "storeの結果をそのまま返す",
stockService: &stockService{stockOrderStore: &testStockOrderStore{getAll1: []*stockOrder{{Code: "sor-1"}, {Code: "sor-2"}, {Code: "sor-3"}}}},
want: []*stockOrder{{Code: "sor-1"}, {Code: "sor-2"}, {Code: "sor-3"}}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.stockService.getStockOrders()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_GetStockOrderByCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
stockService iStockService
arg string
want1 *stockOrder
want2 error
}{
{name: "storeがエラーを返したらエラーを返す",
stockService: &stockService{stockOrderStore: &testStockOrderStore{getByCode1: nil, getByCode2: NoDataError}},
arg: "sor-1",
want1: nil,
want2: NoDataError},
{name: "storeがorderを返したらorderを返す",
stockService: &stockService{stockOrderStore: &testStockOrderStore{getByCode1: &stockOrder{Code: "sor-1"}, getByCode2: nil}},
arg: "sor-1",
want1: &stockOrder{Code: "sor-1"},
want2: nil},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got1, got2 := test.stockService.getStockOrderByCode(test.arg)
if !reflect.DeepEqual(test.want1, got1) || !errors.Is(got2, test.want2) {
t.Errorf("%s error\nwant: %+v, %+v\ngot: %+v, %+v\n", t.Name(), test.want1, test.want2, got1, got2)
}
})
}
}
func Test_stockService_RemoveStockOrderByCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
arg string
removeByCodeHistory []string
}{
{name: "引数をstoreのremoveに渡す",
arg: "sor-1",
removeByCodeHistory: []string{"sor-1"}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
store := &testStockOrderStore{}
service := &stockService{stockOrderStore: store}
service.removeStockOrderByCode(test.arg)
if !reflect.DeepEqual(test.removeByCodeHistory, store.removeByCodeHistory) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.removeByCodeHistory, store.removeByCodeHistory)
}
})
}
}
func Test_stockService_GetStockPositions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
service iStockService
want []*stockPosition
}{
{name: "storeが空配列を返したら彼配列",
service: &stockService{stockPositionStore: &testStockPositionStore{getAll1: []*stockPosition{}}},
want: []*stockPosition{}},
{name: "storeが複数要素を返したラそのまま返す",
service: &stockService{stockPositionStore: &testStockPositionStore{getAll1: []*stockPosition{{Code: "spo-1"}, {Code: "spo-2"}, {Code: "spo-3"}}}},
want: []*stockPosition{{Code: "spo-1"}, {Code: "spo-2"}, {Code: "spo-3"}}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.service.getStockPositions()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_RemoveStockPositionByCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
arg string
removeByCodeHistory []string
}{
{name: "引数をstoreのremoveに渡す",
arg: "spo-1",
removeByCodeHistory: []string{"spo-1"}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
store := &testStockPositionStore{}
service := &stockService{stockPositionStore: store}
service.removeStockPositionByCode(test.arg)
log.Printf("%+v\n", store)
if !reflect.DeepEqual(test.removeByCodeHistory, store.removeByCodeHistory) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.removeByCodeHistory, store.removeByCodeHistory)
}
})
}
}
func Test_stockService_saveStockOrder(t *testing.T) {
t.Parallel()
tests := []struct {
name string
store *testStockOrderStore
arg *stockOrder
wantSaveHistory []*stockOrder
}{
{name: "引数が有効な注文ならstoreに渡す", store: &testStockOrderStore{saveHistory: []*stockOrder{}}, arg: &stockOrder{Code: "sor-1"}, wantSaveHistory: []*stockOrder{{Code: "sor-1"}}},
{name: "引数がnilでもstoreに渡す", store: &testStockOrderStore{saveHistory: []*stockOrder{}}, arg: nil, wantSaveHistory: []*stockOrder{nil}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{stockOrderStore: test.store}
service.saveStockOrder(test.arg)
if !reflect.DeepEqual(test.wantSaveHistory, test.store.saveHistory) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.wantSaveHistory, test.store.saveHistory)
}
})
}
}
func Test_newStockService(t *testing.T) {
t.Parallel()
uuid := &testUUIDGenerator{}
stockOrderStore := &testStockOrderStore{}
stockPositionStore := &testStockPositionStore{}
stockContractComponent := &testStockContractComponent{}
validatorComponent := &testValidatorComponent{}
want := &stockService{uuidGenerator: uuid, stockOrderStore: stockOrderStore, stockPositionStore: stockPositionStore, stockContractComponent: stockContractComponent, validatorComponent: validatorComponent}
got := newStockService(uuid, stockOrderStore, stockPositionStore, validatorComponent, stockContractComponent)
if !reflect.DeepEqual(want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), want, got)
}
}
func Test_stockService_newContractCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
uuidGenerator iUUIDGenerator
want string
}{
{name: "uuidの結果に接頭辞を付けて返す", uuidGenerator: &testUUIDGenerator{generator1: []string{"uuid-1", "uuid-2", "uuid-3"}}, want: "sco-uuid-1"},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{uuidGenerator: test.uuidGenerator}
got := service.newContractCode()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_newPositionCode(t *testing.T) {
t.Parallel()
tests := []struct {
name string
uuidGenerator iUUIDGenerator
want string
}{
{name: "uuidの結果に接頭辞を付けて返す", uuidGenerator: &testUUIDGenerator{generator1: []string{"uuid-1", "uuid-2", "uuid-3"}}, want: "spo-uuid-1"},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{uuidGenerator: test.uuidGenerator}
got := service.newPositionCode()
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_toStockOrder(t *testing.T) {
t.Parallel()
tests := []struct {
name string
service *stockService
arg1 *StockOrderRequest
arg2 time.Time
want *stockOrder
}{
{name: "nilを与えたらnilが返される", service: &stockService{}, arg1: nil, arg2: time.Time{}, want: nil},
{name: "有効期限がゼロ値なら当日の年月日が入る",
service: &stockService{uuidGenerator: &testUUIDGenerator{generator1: []string{"1", "2", "3"}}},
arg1: &StockOrderRequest{
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
SymbolCode: "1234",
Quantity: 1000,
LimitPrice: 0,
ExpiredAt: time.Time{},
StopCondition: nil,
},
arg2: time.Date(2021, 7, 20, 10, 0, 0, 0, time.Local),
want: &stockOrder{
Code: "sor-1",
OrderStatus: OrderStatusInOrder,
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
SymbolCode: "1234",
OrderQuantity: 1000,
ContractedQuantity: 0,
CanceledQuantity: 0,
LimitPrice: 0,
ExpiredAt: time.Date(2021, 7, 20, 0, 0, 0, 0, time.Local),
StopCondition: nil,
OrderedAt: time.Date(2021, 7, 20, 10, 0, 0, 0, time.Local),
CanceledAt: time.Time{},
Contracts: []*Contract{},
ConfirmingCount: 0,
Message: "",
}},
{name: "有効期限がゼロ値でないなら、指定した有効期限の年月日が入る",
service: &stockService{uuidGenerator: &testUUIDGenerator{generator1: []string{"1", "2", "3"}}},
arg1: &StockOrderRequest{
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
SymbolCode: "1234",
Quantity: 1000,
LimitPrice: 0,
ExpiredAt: time.Date(2021, 7, 22, 10, 0, 0, 0, time.Local),
StopCondition: nil,
},
arg2: time.Date(2021, 7, 20, 10, 0, 0, 0, time.Local),
want: &stockOrder{
Code: "sor-1",
OrderStatus: OrderStatusInOrder,
Side: SideBuy,
ExecutionCondition: StockExecutionConditionMO,
SymbolCode: "1234",
OrderQuantity: 1000,
ContractedQuantity: 0,
CanceledQuantity: 0,
LimitPrice: 0,
ExpiredAt: time.Date(2021, 7, 22, 0, 0, 0, 0, time.Local),
StopCondition: nil,
OrderedAt: time.Date(2021, 7, 20, 10, 0, 0, 0, time.Local),
CanceledAt: time.Time{},
Contracts: []*Contract{},
ConfirmingCount: 0,
Message: "",
}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got := test.service.toStockOrder(test.arg1, test.arg2)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_holdSellOrderPositions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
getAll []*stockPosition
arg *stockOrder
want error
wantPositions []*stockPosition
wantArg *stockOrder
}{
{name: "引数がnilならエラー",
getAll: []*stockPosition{},
arg: nil,
want: NilArgumentError,
wantPositions: []*stockPosition{},
wantArg: nil},
{name: "position全てで数量が足りなければエラー",
getAll: []*stockPosition{{OwnedQuantity: 50}, {OwnedQuantity: 30}, {OwnedQuantity: 10}},
arg: &stockOrder{OrderQuantity: 100},
want: NotEnoughOwnedQuantityError,
wantPositions: []*stockPosition{{OwnedQuantity: 50}, {OwnedQuantity: 30}, {OwnedQuantity: 10}},
wantArg: &stockOrder{OrderQuantity: 100}},
{name: "数量が足りればholdする",
getAll: []*stockPosition{{Code: "spo-uuid-01", OwnedQuantity: 50}, {Code: "spo-uuid-02", OwnedQuantity: 30}, {Code: "spo-uuid-03", OwnedQuantity: 30}},
arg: &stockOrder{OrderQuantity: 100},
want: nil,
wantPositions: []*stockPosition{{Code: "spo-uuid-01", OwnedQuantity: 50, HoldQuantity: 50}, {Code: "spo-uuid-02", OwnedQuantity: 30, HoldQuantity: 30}, {Code: "spo-uuid-03", OwnedQuantity: 30, HoldQuantity: 20}},
wantArg: &stockOrder{OrderQuantity: 100, HoldPositions: []*HoldPosition{{PositionCode: "spo-uuid-01", HoldQuantity: 50}, {PositionCode: "spo-uuid-02", HoldQuantity: 30}, {PositionCode: "spo-uuid-03", HoldQuantity: 20}}}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{stockPositionStore: &testStockPositionStore{getAll1: test.getAll}}
got := service.holdSellOrderPositions(test.arg)
if !errors.Is(got, test.want) || !reflect.DeepEqual(test.getAll, test.wantPositions) || !reflect.DeepEqual(test.wantArg, test.arg) {
t.Errorf("%s error\nwant: %+v, %+v, %+v\ngot: %+v, %+v, %+v\n", t.Name(), test.want, test.wantPositions, test.wantArg, got, test.getAll, test.arg)
}
})
}
}
func Test_stockService_validation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
getAll []*stockPosition
isValidStockOrder error
want error
}{
{name: "errorを返されたらerrorを返す",
getAll: []*stockPosition{},
isValidStockOrder: NilArgumentError,
want: NilArgumentError},
{name: "nilを返されたらnilを返す",
getAll: []*stockPosition{},
isValidStockOrder: nil,
want: nil},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{stockPositionStore: &testStockPositionStore{getAll1: test.getAll}, validatorComponent: &testValidatorComponent{isValidStockOrder1: test.isValidStockOrder}}
got := service.validation(nil, time.Time{})
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_confirmContract(t *testing.T) {
t.Parallel()
tests := []struct {
name string
confirmStockOrderContract *confirmContractResult
arg1 *stockOrder
arg2 *symbolPrice
arg3 time.Time
want error
}{
{name: "注文がnilならエラー", arg1: nil, arg2: &symbolPrice{}, want: NilArgumentError},
{name: "価格がnilならエラー", arg1: &stockOrder{}, arg2: nil, want: NilArgumentError},
{name: "売買方向が買いでも売りでもなければエラー", arg1: &stockOrder{Side: SideUnspecified}, arg2: &symbolPrice{}, want: InvalidSideError},
{name: "売買方向が買いならentry",
confirmStockOrderContract: &confirmContractResult{isContracted: false},
arg1: &stockOrder{Side: SideBuy},
arg2: &symbolPrice{},
want: nil},
{name: "売買方向が売りならexit",
confirmStockOrderContract: &confirmContractResult{isContracted: false},
arg1: &stockOrder{Side: SideSell},
arg2: &symbolPrice{},
want: nil},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{stockContractComponent: &testStockContractComponent{confirmStockOrderContract1: test.confirmStockOrderContract}}
got := service.confirmContract(test.arg1, test.arg2, test.arg3)
if !reflect.DeepEqual(test.want, got) {
t.Errorf("%s error\nwant: %+v\ngot: %+v\n", t.Name(), test.want, got)
}
})
}
}
func Test_stockService_cancelAndRelease(t *testing.T) {
t.Parallel()
tests := []struct {
name string
stockPositionStore *testStockPositionStore
arg1 *stockOrder
arg2 time.Time
want error
wantArg1 *stockOrder
wantPosition *stockPosition
}{
{name: "引数がnilならエラー",
stockPositionStore: &testStockPositionStore{},
arg1: nil,
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: NilArgumentError,
wantArg1: nil,
wantPosition: nil},
{name: "キャンセル可能な状態じゃなければエラー",
stockPositionStore: &testStockPositionStore{},
arg1: &stockOrder{OrderStatus: OrderStatusCanceled},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: UncancellableOrderError,
wantArg1: &stockOrder{OrderStatus: OrderStatusCanceled},
wantPosition: nil},
{name: "注文がExitでなければ注文の状態だけ更新して終了",
stockPositionStore: &testStockPositionStore{},
arg1: &stockOrder{Side: SideBuy, OrderStatus: OrderStatusInOrder},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: nil,
wantArg1: &stockOrder{Side: SideBuy, OrderStatus: OrderStatusCanceled, CanceledAt: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local)},
wantPosition: nil},
{name: "注文がExitでも拘束中のポジションがなければ何もしない",
stockPositionStore: &testStockPositionStore{},
arg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusInOrder, HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 100}}},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: nil,
wantArg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusCanceled, CanceledAt: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local), HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 100}}},
wantPosition: nil},
{name: "注文がExitで拘束中のポジションがあれば解放し、ポジションの拘束数を解放する",
stockPositionStore: &testStockPositionStore{getByCode1: &stockPosition{OwnedQuantity: 70, HoldQuantity: 70}},
arg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusInOrder, HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 30}}},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: nil,
wantArg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusCanceled, CanceledAt: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local), HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 30, ExitQuantity: 30}}},
wantPosition: &stockPosition{OwnedQuantity: 70, HoldQuantity: 0}},
{name: "注文がExitで拘束中のポジションがなければエラー",
stockPositionStore: &testStockPositionStore{getByCode2: NoDataError},
arg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusInOrder, HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 30}}},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: NoDataError,
wantArg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusCanceled, CanceledAt: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local), HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 30}}},
wantPosition: nil},
{name: "注文がExitで拘束中のポジションがあっても、releaseに失敗したらエラーを返す",
stockPositionStore: &testStockPositionStore{getByCode1: &stockPosition{OwnedQuantity: 70, HoldQuantity: 0}},
arg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusInOrder, HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 100, ExitQuantity: 30}}},
arg2: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local),
want: NotEnoughHoldQuantityError,
wantArg1: &stockOrder{Side: SideSell, OrderStatus: OrderStatusCanceled, CanceledAt: time.Date(2021, 8, 31, 14, 0, 0, 0, time.Local), HoldPositions: []*HoldPosition{{PositionCode: "mpo-uuid-01", HoldQuantity: 30, ExitQuantity: 30}}},
wantPosition: &stockPosition{OwnedQuantity: 70, HoldQuantity: 0}},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
service := &stockService{stockPositionStore: test.stockPositionStore}
got := service.cancelAndRelease(test.arg1, test.arg2)
if !errors.Is(got, test.want) ||
!reflect.DeepEqual(test.wantArg1, test.arg1) ||
!reflect.DeepEqual(test.wantPosition, test.stockPositionStore.getByCode1) {
t.Errorf("%s error\nwant: %+v, %+v, %+v\ngot: %+v, %+v, %+v\n", t.Name(),
test.want, test.wantArg1, test.wantPosition,
got, test.arg1, test.stockPositionStore.getByCode1)
}
})
}
}
|
package main
import (
"crypto"
"crypto/rsa"
"fmt"
"io"
"io/ioutil"
"log"
"golang.org/x/crypto/ssh"
)
type keychain struct {
key *rsa.PrivateKey
}
func (k *keychain) Key(i int) (ssh.PublicKey, error) {
if i != 0 {
return nil, nil
}
return ssh.NewPublicKey(&k.key.PublicKey)
}
func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
hashFunc := crypto.SHA1
h := hashFunc.New()
h.Write(data)
digest := h.Sum(nil)
return rsa.SignPKCS1v15(rand, k.key, hashFunc, digest)
}
// Reads an OpenSSH key and provides it as a ssh.ClientAuth.
func openSshClientAuth(path string) (ssh.AuthMethod, error) {
privateKey, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(privateKey)
return ssh.PublicKeys(signer), err
}
func newSshConnection(host, keypath string) (*ssh.Client, error) {
clientauth, err := openSshClientAuth(keypath)
if err != nil {
log.Fatal(err)
}
clientConfig := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{clientauth},
}
client, err := ssh.Dial("tcp", host+":22", clientConfig)
if err != nil {
return nil, err
}
return client, nil
}
func sshCommand(host, keypath, command string) (string, error) {
conn, err := newSshConnection(host, keypath)
if err != nil {
return "", err
}
session, err := conn.NewSession()
if err != nil {
return "", err
}
defer session.Close()
if command == "" {
return "", session.Start(command)
}
f, err := ioutil.TempFile("", "dornröschen-")
if err != nil {
return "", err
}
defer f.Close()
session.Stdout = f
session.Stderr = f
if err := session.Run(command); err != nil {
return f.Name(), fmt.Errorf("Could not execute SSH command %q, please see %q", command, f.Name())
}
return f.Name(), nil
}
|
package proto
import (
"cm_liveme_im/libs/bufio"
"cm_liveme_im/libs/bytepool"
"cm_liveme_im/libs/bytes"
"cm_liveme_im/libs/define"
"encoding/binary"
"errors"
"fmt"
log "github.com/thinkboy/log4go"
"time"
)
const (
// required header size
SizePackLen = 4
SizeHdrLen = 2
SizeVer = 2
SizeOpCode = 4
SizeSeqId = 4
MinHeaderSize = SizePackLen + SizeHdrLen + SizeVer + SizeOpCode + SizeSeqId
// required header offset
OffsetPackLen = 0
OffsetHdrLen = OffsetPackLen + SizePackLen
OffsetVer = OffsetHdrLen + SizeHdrLen
OffsetOpCode = OffsetVer + SizeVer
OffsetSeqId = OffsetOpCode + SizeOpCode
// optional header size and offsets
SizeTimeStamp = 8
OffsetTimeStamp = OffsetSeqId + SizeSeqId
)
var (
emptyProto = Proto{}
emptyJSONBody = []byte("{}")
ErrProtoVer = errors.New("incoming packet's version is not supported")
ErrProtoHeaderLen = errors.New("incoming packet's header length is not right")
ProtoReady = &Proto{Operation: define.OP_PROTO_READY}
ProtoFinish = &Proto{Operation: define.OP_PROTO_FINISH}
ProtoKick = &Proto{Operation: define.OP_PROTO_KICK}
)
// Proto roughly represents the message format used in our tcp connections.
// The detail message format pls refer to the ReadXXX and WriteXXX methods below.
// Note that fields in Proto not necessarily used in the message format.
type Proto struct {
HeaderLen uint16 // header length
Ver uint16 // protocol version
Operation uint32 // operation for request
SeqId uint32 // sequence number chosen by client
Body []byte // binary body bytes(json.RawMessage is []byte)
BodySupportReuse bool // as suggested by field name, and the zero value of this is false
BundleData interface{} // use for comet internal data passing around
}
type AuthInfo struct {
Uid string `json:"uid"`
Token string `json:"token"`
}
func (p *Proto) Reset() {
*p = emptyProto
}
func (p *Proto) String() string {
return fmt.Sprintf("\n-------- proto --------\nheader: %d\nver: %d\nop: %d\nseq: %d\nbody: %s\n-----------------------", p.HeaderLen, p.Ver, p.Operation, p.SeqId, string(p.Body))
}
func (p *Proto) WriteTo(b *bytes.Writer) {
var (
buf []byte
packLen uint32
)
p.HeaderLen = MinHeaderSize + SizeTimeStamp
packLen = uint32(p.HeaderLen) + uint32(len(p.Body))
buf = b.Peek(int(p.HeaderLen))
binary.BigEndian.PutUint32(buf[OffsetPackLen:], packLen)
binary.BigEndian.PutUint16(buf[OffsetHdrLen:], p.HeaderLen)
binary.BigEndian.PutUint16(buf[OffsetVer:], p.Ver)
binary.BigEndian.PutUint32(buf[OffsetOpCode:], p.Operation)
binary.BigEndian.PutUint32(buf[OffsetSeqId:], p.SeqId)
binary.BigEndian.PutUint64(buf[OffsetTimeStamp:], uint64(time.Now().UnixNano()))
if p.Body != nil {
b.Write(p.Body)
}
}
func (p *Proto) ReadTCP(rr *bufio.Reader, largeMsgBodyPool *bytepool.BytePool, validMaxBody uint32) (err error) {
var (
bodyLen int
packLen uint32
buf []byte
)
if buf, err = rr.Pop(MinHeaderSize); err != nil {
return
}
packLen = binary.BigEndian.Uint32(buf[OffsetPackLen:])
p.HeaderLen = binary.BigEndian.Uint16(buf[OffsetHdrLen:])
p.Ver = binary.BigEndian.Uint16(buf[OffsetVer:])
// versioning: major + minor
if p.Ver > 0x0100 {
return ErrProtoVer
}
p.Operation = binary.BigEndian.Uint32(buf[OffsetOpCode:])
p.SeqId = binary.BigEndian.Uint32(buf[OffsetSeqId:])
optionalHeaderSize := int(p.HeaderLen) - MinHeaderSize
if optionalHeaderSize < 0 {
return ErrProtoHeaderLen
} else if optionalHeaderSize > 0 {
// currently drop the optional headers
if _, err = rr.Pop(optionalHeaderSize); err != nil {
return
}
}
if bodyLen = int(packLen - uint32(p.HeaderLen)); bodyLen > 0 {
p.Body, err = rr.Pop(bodyLen)
if err == bufio.ErrBufferFull {
if uint32(bodyLen) > validMaxBody {
return fmt.Errorf("incoming packet's body(%d) is too large(limited by %d)", bodyLen, validMaxBody)
}
log.Warn("Incoming packet body(%d)/packet(%d) exceeds bufio's buf capacity(%d), will use a pooled one",
bodyLen, packLen, rr.BufferCapacity())
poolSlice := largeMsgBodyPool.Get(bodyLen)
var (
rPos int = 0
step int = 0
)
err = nil
for rPos < bodyLen && err == nil {
step, err = rr.Read(poolSlice[rPos:])
rPos += step
}
if err != nil {
largeMsgBodyPool.Put(poolSlice)
p.Body = nil
} else {
p.Body = poolSlice
p.BodySupportReuse = true
}
}
} else {
p.Body = nil
}
return
}
func (p *Proto) WriteTCP(wr *bufio.Writer) (err error) {
var (
buf []byte
packLen uint32
)
if p.Operation == define.OP_RAW {
_, err = wr.Write(p.Body)
return
}
p.HeaderLen = MinHeaderSize + SizeTimeStamp
packLen = uint32(p.HeaderLen) + uint32(len(p.Body))
if buf, err = wr.Peek(int(p.HeaderLen)); err != nil {
return
}
binary.BigEndian.PutUint32(buf[OffsetPackLen:], packLen)
binary.BigEndian.PutUint16(buf[OffsetHdrLen:], p.HeaderLen)
binary.BigEndian.PutUint16(buf[OffsetVer:], p.Ver)
binary.BigEndian.PutUint32(buf[OffsetOpCode:], p.Operation)
binary.BigEndian.PutUint32(buf[OffsetSeqId:], p.SeqId)
binary.BigEndian.PutUint64(buf[OffsetTimeStamp:], uint64(time.Now().UnixNano()))
if p.Body != nil {
_, err = wr.Write(p.Body)
}
return
}
|
package dao
import (
"errors"
"git.dustess.com/mk-base/util/crypto"
"git.dustess.com/mk-training/mk-blog-svc/pkg/tags/model"
"go.mongodb.org/mongo-driver/bson"
)
// InsertTags 插入标签数据
func (m *TagDao) InsertTags(data []string) ([]string, error) {
if len(data) == 0 {
return nil, errors.New("tags is empty")
}
var (
updateData []model.Tag
filter bson.M
tags []string
insertData []interface{}
id []string
)
for _, v := range data {
d := model.Tag{
ID: crypto.UUID(),
Name: v,
}
updateData = append(updateData,d)
tags = append(tags, v)
}
filter = bson.M{"name": bson.M{"$in": tags}}
t , _ := m.FindMany(filter)
for _, v := range updateData {
var b bool
for _, vv := range t {
if v.Name == vv.Name {
b = true
id = append(id, vv.ID)
break
}
}
if !b {
insertData = append(insertData, v)
}
}
if len(insertData) < 1 {
return nil, errors.New("tags is empty")
}
r, err := m.dao.InsertMany(m.ctx, insertData)
if r != nil {
for _, v := range r.InsertedIDs {
id = append(id, v.(string))
}
}
return id, err
}
|
package guessit
import (
"encoding/json"
"net/http"
"net/url"
)
const (
BASE_URL = "http://guessit.io/"
)
type GuessResult struct {
AudioChannels string `json:"audioChannels"`
AudioCodec string `json:"audioCodec"`
Container string `json:"container"`
EpisodeNumber int64 `json:"episodeNumber"`
Format string `json:"format"`
MimeType string `json:"mimetype"`
ReleaseGroup string `json:"releaseGroup"`
ScreenSize string `json:"screenSize"`
Season int64 `json:"season"`
Series string `json:"series"`
Title string `json:"title"`
Type string `json:"type"`
VideoCodec string `json:"videoCodec"`
Year int `json:"year"`
}
func Guess(filename string) (*GuessResult, error) {
args := url.Values{}
args.Set("filename", filename)
query, err := url.ParseRequestURI(BASE_URL)
if err != nil {
return nil, err
}
query, err = query.Parse("/guess")
if err != nil {
return nil, err
}
query.RawQuery = args.Encode()
r, err := http.Get(query.String())
if err != nil {
return nil, err
}
var guess GuessResult
err = json.NewDecoder(r.Body).Decode(&guess)
if err != nil {
return nil, err
}
return &guess, err
}
|
package config
import (
)
type Config struct {
DockerURL string
TLSCACert string
TLSCert string
TLSKey string
ActiveActiveSrvcsCnslPath string
BuddyCluster string
RemoteGateWayCnslPath string
AllowInsecure bool
PollInterval string
ConsulHost string
ConsulPort int
ConsulTemplate string
DefaultHealthChkURI string
DefaultHealthChkInterval string
DefaultHealthChkFails string
DefaultHealthChkPasses string
NginxPlusconfig *NginxPlusConfig
}
type ConsulAddr struct {
Host string
Port int
}
type NginxPlusConfig struct {
Name string
ConfigPath string
PidPath string
TemplatePath string
BackendOverrideAddress string
ConnectTimeout int
ServerTimeout int
ClientTimeout int
MaxConn int
Port int
SyslogAddr string
AdminUser string
AdminPass string
SSLCertPath string
SSLCert string
SSLPort int
SSLOpts string
User string
WorkerProcesses int
RLimitNoFile int
ProxyConnectTimeout int
ProxySendTimeout int
ProxyReadTimeout int
SendTimeout int
SSLCiphers string
SSLProtocols string
}
|
package datacenter
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"github.com/sanguohot/medichain/etc"
"github.com/sanguohot/medichain/util"
"github.com/sanguohot/medichain/zap"
"io/ioutil"
"os"
)
type FileAddLog struct {
FileUuid string
OwnerUuid string
UploaderUuid string
OrgUuid string
FileTypeHash string
FileType string
FileDesc string
Keccak256Hash string
Sha256Hash string
CreateTime uint64
Signature string
Signer string
BlockNum uint64
BlockHash string
TransactionHash string
ContractAddress string
}
func init() {
if !util.FilePathExist(etc.GetSqliteFilePath()) {
_, err := os.Create(etc.GetSqliteFilePath())
if err != nil {
zap.Logger.Fatal(err.Error())
}
}
// 确保sql可以重复执行 也就是包含IF NOT EXISTS
if !util.FilePathExist(etc.GetSqliteFileAddLogPath()) {
zap.Logger.Fatal(fmt.Errorf("sqlite: not found %s", etc.GetSqliteFileAddLogPath()).Error())
}
db, err := sql.Open("sqlite3", etc.GetSqliteFilePath())
defer db.Close()
if err != nil {
zap.Logger.Fatal(err.Error())
}
data, err := ioutil.ReadFile(etc.GetSqliteFileAddLogPath())
if err != nil {
zap.Logger.Fatal(err.Error())
}
_, err = db.Exec(string(data))
if err != nil {
zap.Logger.Fatal(err.Error())
}
}
func SqliteSetFileAddLogList(fl []FileAddLog) error {
if fl == nil || len(fl) == 0 {
return nil
}
zap.Sugar.Infof("sqlite: now insert []FileAddLog %d", len(fl))
db, err := sql.Open("sqlite3", etc.GetSqliteFilePath())
defer db.Close()
if err != nil {
return err
}
stmt, err := db.Prepare("INSERT OR IGNORE INTO tbl_file_add_event_log(FileUuid, OwnerUuid, UploaderUuid, OrgUuid, FileTypeHash, FileType" +
", FileDesc, Keccak256Hash, Sha256Hash, CreateTime, Signature, Signer, BlockNum, BlockHash, TransactionHash" +
", ContractAddress) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
if err != nil {
return err
}
var res sql.Result
for _, f := range fl {
res, err = stmt.Exec(f.FileUuid, f.OwnerUuid, f.UploaderUuid, f.OrgUuid, f.FileTypeHash, f.FileType, f.FileDesc, f.Keccak256Hash, f.Sha256Hash, f.CreateTime,
f.Signature, f.Signer, f.BlockNum, f.BlockHash, f.TransactionHash, f.ContractAddress)
if err != nil {
return err
}
}
_, err = res.LastInsertId()
if err != nil {
return err
}
return nil
}
func SqliteGetFileAddLogList(fileUuid, orgUuid, ownerUuid string, fromTime, toTime, start, limit uint64) (error, []FileAddLog) {
db, err := sql.Open("sqlite3", etc.GetSqliteFilePath())
defer db.Close()
if err != nil {
return err, nil
}
sql := getFileAddLogQuerySql(false, fileUuid, orgUuid, ownerUuid, fromTime, toTime, start, limit)
zap.Sugar.Infof("sqlite: %s", sql)
rows, err := db.Query(sql)
defer rows.Close()
if err != nil {
return err, nil
}
var fl []FileAddLog
for rows.Next() {
f := FileAddLog{}
err = rows.Scan(&f.FileUuid, &f.OwnerUuid, &f.UploaderUuid, &f.OrgUuid, &f.FileTypeHash, &f.FileType, &f.FileDesc, &f.Keccak256Hash, &f.Sha256Hash, &f.CreateTime,
&f.Signature, &f.Signer, &f.BlockNum, &f.BlockHash, &f.TransactionHash, &f.ContractAddress)
if err != nil {
return err, nil
}
fl = append(fl, f)
}
return nil, fl
}
func SqliteGetFileAddLogMaxBlockNum() (error, uint64) {
db, err := sql.Open("sqlite3", etc.GetSqliteFilePath())
defer db.Close()
if err != nil {
return err, 0
}
sql := "SELECT MAX(BlockNum) FROM tbl_file_add_event_log"
//fmt.Printf("sqlite: %s\n", sql)
rows, err := db.Query(sql)
defer rows.Close()
if err != nil {
return err, 0
}
// 需要设置为指针, 并且判断是否为nil
var blockNum *uint64
for rows.Next() {
err = rows.Scan(&blockNum)
if err != nil {
return err, 0
}
if blockNum == nil {
return nil, 0
}
break
}
return nil, *blockNum
}
func SqliteGetFileAddLogTotal(fileUuid, orgUuid, ownerUuid string, fromTime, toTime uint64) (error, uint64) {
db, err := sql.Open("sqlite3", etc.GetSqliteFilePath())
defer db.Close()
if err != nil {
return err, 0
}
sql := getFileAddLogQuerySql(true, fileUuid, orgUuid, ownerUuid, fromTime, toTime, 0, 0)
zap.Sugar.Infof("sqlite: %s", sql)
rows, err := db.Query(sql)
defer rows.Close()
if err != nil {
return err, 0
}
// 需要设置为指针, 并且判断是否为nil
var count *uint64
for rows.Next() {
err = rows.Scan(&count)
if err != nil {
return err, 0
}
if count == nil {
return nil, 0
}
break
}
return nil, *count
}
func getFileAddLogQuerySql(isCount bool, fileUuid, orgUuid, ownerUuid string, fromTime, toTime, start, limit uint64) string {
sql := "SELECT * FROM tbl_file_add_event_log WHERE 1=1"
if isCount {
sql = "SELECT COUNT(*) FROM tbl_file_add_event_log WHERE 1=1"
}
if ownerUuid != "" {
sql = fmt.Sprintf("%s AND OwnerUuid=\"%s\"", sql, ownerUuid)
}
if orgUuid != "" {
sql = fmt.Sprintf("%s AND OrgUuid=\"%s\"", sql, orgUuid)
}
if fileUuid != "" {
sql = fmt.Sprintf("%s AND FileUuid=\"%s\"", sql, fileUuid)
}
if fromTime > 0 {
sql = fmt.Sprintf("%s AND CreateTime>=%d", sql, fromTime)
}
if toTime > 0 {
sql = fmt.Sprintf("%s AND CreateTime<=%d", sql, toTime)
}
if !isCount {
sql = fmt.Sprintf("%s ORDER BY CreateTime DESC", sql)
}
if limit > 0 {
sql = fmt.Sprintf("%s LIMIT %d OFFSET %d", sql, limit, start)
}
return sql
}
|
package router
import (
"project/app/admin/apis"
"project/app/admin/middleware"
"strconv"
"github.com/gin-gonic/gin"
)
func init() {
// 无需认证接口
//routerNoCheckRole = append(routerNoCheckRole, roleAuthRouter)
// 认证
routerCheckRole = append(routerCheckRole, roleAuthRouter)
}
func roleAuthRouter(v1 *gin.RouterGroup) {
r := v1.Group("/roles")
{
r.PUT("menu", apis.MenuRolesHandler)
r.GET(":id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err == nil {
apis.SelectRoleHandler(c, id)
}
if c.Param("id") == "all" {
apis.SelectRolesAllHandler(c)
}
if c.Param("id") == "download" {
apis.DownRolesHandler(c)
}
if c.Param("id") == "level" {
apis.LevelRolesHandler(c)
}
})
r.Use(middleware.AuthCheckRole())
r.GET("", apis.SelectRolesHandler)
r.POST("", apis.InsertRolesHandler)
r.PUT("", apis.UpdateRolesHandler)
r.DELETE("", apis.DeleteRolesHandler)
}
}
|
package main
import(
"fmt"
"time"
"math/rand"
)
var a[25]int
var x[25]int
var t int
func main() {
x =[25]int{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}
for k :=0;k<=24;k++{
a[k]=rand.Intn(105)+15
}
for i :=0;i<8;i++ {
go cafe(i)
}
time.Sleep(time.Millisecond)
for v :=8;v<25;v++ {
fmt.Println("Tourist",v+1,"is waiting for turn")
}
var input string
fmt.Scanln(&input)
}
func cafe(i int){
fmt.Println("Tourist",x[i],"is online")
time.Sleep(time.Second*time.Duration(a[i]))
fmt.Println("Tourist ",x[i],"is done , having spent",a[i],"mins online")
t++
if i>=0 && i<17 {
cafe(i+8)
}
if t==25{
fmt.Println("\nThe place is empty, let's close up and go to the beach!")
}
}
|
/*
Copyright 2019 Dmitry Kolesnikov, All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gouldian_test
import (
"testing"
µ "github.com/fogfish/gouldian/v2"
"github.com/fogfish/gouldian/v2/mock"
"github.com/fogfish/it"
itt "github.com/fogfish/it/v2"
)
func TestParams(t *testing.T) {
type foobar struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
type myT struct {
Val foobar `content:"form"`
}
var val myT
lens := µ.Optics1[myT, foobar]()
foo := µ.Params(lens)
req := mock.Input(mock.URL("/?foo=bar&bar=foo"))
err := foo(req)
itt.Then(t).Should(
itt.Nil(err),
itt.Nil(µ.FromContext(req, &val)),
itt.Equal(val.Val.Foo, "bar"),
itt.Equal(val.Val.Bar, "foo"),
)
}
func TestParamIs(t *testing.T) {
foo := µ.Param("foo", "bar")
success := mock.Input(mock.URL("/?foo=bar"))
failure := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(success)).Should().Equal(nil).
If(foo(failure)).ShouldNot().Equal(nil)
}
func TestParamAny(t *testing.T) {
foo := µ.ParamAny("foo")
success1 := mock.Input(mock.URL("/?foo"))
success2 := mock.Input(mock.URL("/?foo=bar"))
success3 := mock.Input(mock.URL("/?foo=baz"))
failure := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(success1)).Should().Equal(nil).
If(foo(success2)).Should().Equal(nil).
If(foo(success3)).Should().Equal(nil).
If(foo(failure)).ShouldNot().Equal(nil)
}
func TestParamString(t *testing.T) {
type myT struct{ Val string }
val := µ.Optics1[myT, string]()
foo := µ.Param("foo", val)
t.Run("string", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal("bar")
})
t.Run("number", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal("1")
})
t.Run("nomatch", func(t *testing.T) {
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
}
func TestParamMaybeString(t *testing.T) {
type myT struct{ Val string }
val := µ.Optics1[myT, string]()
foo := µ.ParamMaybe("foo", val)
t.Run("string", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal("bar")
})
t.Run("nomatch", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal("")
})
}
func TestParamInt(t *testing.T) {
type myT struct{ Val int }
val := µ.Optics1[myT, int]()
foo := µ.Param("foo", val)
t.Run("string", func(t *testing.T) {
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
t.Run("number", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(1)
})
t.Run("nomatch", func(t *testing.T) {
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
}
func TestParamMaybeInt(t *testing.T) {
type myT struct{ Val int }
val := µ.Optics1[myT, int]()
foo := µ.ParamMaybe("foo", val)
t.Run("string", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(0)
})
t.Run("number", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(1)
})
t.Run("nomatch", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(0)
})
}
func TestParamFloat(t *testing.T) {
type myT struct{ Val float64 }
val := µ.Optics1[myT, float64]()
foo := µ.Param("foo", val)
t.Run("integer", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(1.0)
})
t.Run("double", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1.1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(1.1)
})
t.Run("string", func(t *testing.T) {
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
t.Run("nomatch", func(t *testing.T) {
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
}
func TestParamMaybeFloat(t *testing.T) {
type myT struct{ Val float64 }
val := µ.Optics1[myT, float64]()
foo := µ.ParamMaybe("foo", val)
t.Run("double", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=1.1"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(1.1)
})
t.Run("string", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(0.0)
})
t.Run("nomatch", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(0.0)
})
}
type MyT struct {
A string `json:"a"`
B int `json:"b"`
}
func TestParamJSON(t *testing.T) {
type MyS struct {
A string `json:"a"`
B int `json:"b"`
}
type myT struct{ Val MyS }
val := µ.Optics1[myT, MyS]()
foo := µ.ParamJSON("foo", val)
t.Run("json", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=%7B%22a%22%3A%22abc%22%2C%22b%22%3A10%7D"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(MyS{A: "abc", B: 10})
})
t.Run("string", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=bar"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).ShouldNot().Equal(nil)
})
t.Run("nomatch", func(t *testing.T) {
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
t.Run("badformat", func(t *testing.T) {
req := mock.Input(mock.URL("/?foo=%7"))
it.Ok(t).
If(foo(req)).ShouldNot().Equal(nil)
})
}
func TestParamMaybeJSON(t *testing.T) {
type MyS struct {
A string `json:"a"`
B int `json:"b"`
}
type myT struct{ Val MyS }
val := µ.Optics1[myT, MyS]()
foo := µ.ParamMaybeJSON("foo", val)
t.Run("json", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=%7B%22a%22%3A%22abc%22%2C%22b%22%3A10%7D"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(MyS{A: "abc", B: 10})
})
t.Run("nomatch", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?bar=foo"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(MyS{})
})
t.Run("badformat", func(t *testing.T) {
var val myT
req := mock.Input(mock.URL("/?foo=%7"))
it.Ok(t).
If(foo(req)).Should().Equal(nil).
If(µ.FromContext(req, &val)).Should().Equal(nil).
If(val.Val).Should().Equal(MyS{})
})
}
// // func TestParamOr(t *testing.T) {
// // foo := µ.GET(µ.Param(
// // param.Or(param.Any("foo"), param.Any("bar")),
// // ))
// // success1 := mock.Input(mock.URL("/?foo"))
// // success2 := mock.Input(mock.URL("/?bar"))
// // failure := mock.Input(mock.URL("/?baz"))
// // it.Ok(t).
// // If(foo(success1)).Should().Equal(nil).
// // If(foo(success2)).Should().Equal(nil).
// // If(foo(failure)).ShouldNot().Equal(nil)
// // }
|
package torrentapi
import (
"errors"
"fmt"
"reflect"
"strings"
"testing"
"time"
)
func TestTokenIsValid(t *testing.T) {
testData := []struct {
desc string
token Token
want bool
}{
{
desc: "Valid Token",
token: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)},
want: true,
},
{
desc: "Expired Token",
token: Token{Token: "test", Expires: time.Now().Add(time.Second * -100)},
want: false,
},
{
desc: "Empty Token",
token: Token{Token: "", Expires: time.Now().Add(time.Second * 100)},
want: false,
},
}
for i, tc := range testData {
got := tc.token.IsValid()
if got != tc.want {
t.Errorf("Test(%d) %s: (%+v).IsValid() => got %v, want %v", i, tc.desc, tc.token, got, tc.want)
}
}
}
func performQueryStringTest(api *API, expectedResult string) (result bool, text string) {
if !strings.HasSuffix(api.Query, expectedResult) {
text = fmt.Sprintf("api.Query doesn't ends with requested string: %s, Query: %s", expectedResult, api.Query)
return
}
return true, ""
}
func TestAPISearchString(t *testing.T) {
api := new(API)
api = api.SearchString("test")
result, text := performQueryStringTest(api, "&search_string=test")
if !result {
t.Error(text)
}
}
func TestAPICategory(t *testing.T) {
api := new(API)
api = api.Category(1)
if len(api.categories) != 1 {
t.Error("Categories not added")
}
}
func TestAPISearchTVDB(t *testing.T) {
api := new(API)
api = api.SearchTVDB("123")
result, text := performQueryStringTest(api, "&search_tvdb=123")
if !result {
t.Error(text)
}
}
func TestAPISearchIMDb(t *testing.T) {
api := new(API)
api = api.SearchIMDb("tt123")
result, text := performQueryStringTest(api, "&search_imdb=tt123")
if !result {
t.Error(text)
}
}
func TestAPISearchTheMovieDb(t *testing.T) {
api := new(API)
api = api.SearchTheMovieDb("123")
result, text := performQueryStringTest(api, "&search_themoviedb=123")
if !result {
t.Error(text)
}
}
func TestAPIFormat(t *testing.T) {
api := new(API)
api = api.Format("super_format")
result, text := performQueryStringTest(api, "&format=super_format")
if !result {
t.Error(text)
}
}
func TestAPILimit(t *testing.T) {
api := new(API)
api = api.Limit(100)
result, text := performQueryStringTest(api, "&limit=100")
if !result {
t.Error(text)
}
}
func TestAPISort(t *testing.T) {
api := new(API)
api = api.Sort("seeders")
result, text := performQueryStringTest(api, "&sort=seeders")
if !result {
t.Error(text)
}
}
func TestAPIRankedTrue(t *testing.T) {
api := new(API)
api = api.Ranked(true)
result, text := performQueryStringTest(api, "&ranked=1")
if !result {
t.Error(text)
}
}
func TestAPIRankedFalse(t *testing.T) {
api := new(API)
api = api.Ranked(false)
result, text := performQueryStringTest(api, "&ranked=0")
if !result {
t.Error(text)
}
}
func TestAPIRankedMinSeeders(t *testing.T) {
api := new(API)
api = api.MinSeeders(100)
result, text := performQueryStringTest(api, "&min_seeders=100")
if !result {
t.Error(text)
}
}
func TestAPIRankedMinLeechers(t *testing.T) {
api := new(API)
api = api.MinLeechers(100)
result, text := performQueryStringTest(api, "&min_leechers=100")
if !result {
t.Error(text)
}
}
var nrOfErrors int
func TestCall(t *testing.T) {
testData := []struct {
desc string
api API
getRes func(string) (*APIResponse, error)
renewToken func() (Token, error)
want TorrentResults
wantErr bool
}{
{
desc: "Empty torrent response",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return &APIResponse{Torrents: []byte("[]")}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: false,
},
{
desc: "First query returns error",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return nil, errors.New("error")
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "Got expired token response, second query OK",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
if nrOfErrors == 0 {
nrOfErrors++
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 4}, nil
}
return &APIResponse{Torrents: []byte("[]")}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: false,
},
{
desc: "Got expired token response, second query error",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
if nrOfErrors == 0 {
nrOfErrors++
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 4}, nil
}
return &APIResponse{Torrents: []byte("[]")}, errors.New("test")
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "Token invalid, renew returns error",
api: API{APIToken: Token{}},
getRes: func(string) (*APIResponse, error) {
return nil, nil
},
renewToken: func() (Token, error) {
return Token{}, errors.New("token error")
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "Got error in first response",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 5}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "First reponse renew token, error in second response",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
if nrOfErrors == 0 {
nrOfErrors++
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 4}, nil
}
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 5}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "First reponse renew token, error in renew",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 4}, nil
},
renewToken: func() (Token, error) {
return Token{}, errors.New("error")
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "Error in unmarshal",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return &APIResponse{Torrents: []byte("")}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: TorrentResults{},
wantErr: true,
},
{
desc: "No torrents found",
api: API{APIToken: Token{Token: "test", Expires: time.Now().Add(time.Second * 100)}},
getRes: func(string) (*APIResponse, error) {
return &APIResponse{Torrents: nil, Error: "error", ErrorCode: 20}, nil
},
renewToken: func() (Token, error) {
return Token{}, nil
},
want: nil,
wantErr: false,
},
}
for i, tc := range testData {
nrOfErrors = 0
getRes = tc.getRes
renewToken = tc.renewToken
got, err := tc.api.call()
if (err == nil) != !tc.wantErr {
t.Errorf("Test (%d) %s: API.call() %+v => got unexpected error %v", i, tc.desc, tc.api, err)
}
if err != nil {
continue
}
fmt.Println(got == nil)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("Test(%d) %s: API.call() %+v => got: %+v, want: %+v", i, tc.desc, tc.api, got, tc.want)
}
}
}
|
package gotappd
// Interface for parameter objects
type parameter interface {
// Get the parameters formatter as url parameters
urlformat() string
}
// Parameters for querying user information
type UserInfoParams struct {
// compact (string, optional) - You can pass "true" here only show the user information,
// and remove the "checkins", "media", "recent_brews", etc attributes
Compact bool
}
type SortType int
const (
SORT_NONE SortType = iota
SORT_DATE
SORT_CHECKIN
SORT_HIGHEST_RATED
SORT_LOWEST_RATED
SORT_HIGHEST_ABV
SORT_LOWEST_ABV
SORT_HIGHEST_RATED_YOU
SORT_LOWEST_RATED_YOU
SORT_NAME
)
// Parameters for querying user wish list information
type UserWishListParams struct {
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of results to return, max of 50, default is 25
Limit uint64
// sort (string, optional) - You can sort the results using these values: date -
// sorts by date (default), checkin - sorted by highest checkin, highest_rated - sorts
// by global rating descending order, lowest_rated - sorts by global rating ascending
// order, highest_abv - highest ABV from the wishlist, lowest_abv - lowest ABV from the
// wishlist
Sort SortType
}
// Parameters for querying user friends list information
type UserFriendsParams struct {
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of results to return, max of 25, default is 25
Limit uint64
}
// Parameters for querying user badgers list information
type UserBadgesParams struct {
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of badges to return in your result set
Limit uint64
}
// Parameters for querying user unique beers infromation
type UserBeersParams struct {
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of results to return, max of 50, default is 25
Limit uint64
// sort (string, optional) - Your can sort the results using these values:
// date - sorts by date (default), checkin - sorted by highest checkin,
// highest_rated - sorts by global rating descending order, lowest_rated -
// sorts by global rating ascending order, highest_rated_you - the user's
// highest rated beer, lowest_rated_you - the user's lowest rated beer
Sort SortType
}
// Parameters when querying brewery info
type BreweryInfoParams struct {
// compact (string, optional) - You can pass "true" here only show the user information,
// and remove the "checkins", "media", "recent_brews", etc attributes
Compact bool
}
// Parameters when querying beer info
type BeerInfoParams struct {
// compact (string, optional) - You can pass "true" here only show the user information,
// and remove the "checkins", "media", "recent_brews", etc attributes
Compact bool
}
// Parameters when querying venue info
type VenueInfoParams struct {
// compact (string, optional) - You can pass "true" here only show the user information,
// and remove the "checkins", "media", "recent_brews", etc attributes
Compact bool
}
// Parameters when searching for a beer
type BeerSearchParams struct {
// query (string, required) - The search term that you want to search.
query string
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of results to return, max of 50, default is 25
Limit uint64
// sort (string, optional) - Your can sort the results using these values:
// checkin - sorts by checkin count (default), name - sorted by alphabetic beer name
Sort SortType
}
// Parameters when searching for a brewery
type BrewerySearchParams struct {
// query (string, required) - The search term that you want to search.
query string
// offset (int, optional) - The numeric offset that you what results to start
Offset uint64
// limit (int, optional) - The number of results to return, max of 50, default is 25
Limit uint64
}
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sort"
"strings"
"sync"
"time"
)
var (
sourceURLValidatorMap = map[string]lineValidator{
`https://raw.githubusercontent.com/notracking/hosts-blocklists/master/hostnames.txt`: hostLine("0.0.0.0"),
`http://dn-mwsl-hosts.qbox.me/hosts`: hostLine("191.101.231.96"),
`https://adaway.org/hosts.txt`: hostLine("127.0.0.1"),
`http://sysctl.org/cameleon/hosts`: hostLine("127.0.0.1"),
`http://www.hostsfile.org/Downloads/hosts.txt`: hostLine("127.0.0.1"),
`https://raw.githubusercontent.com/yous/YousList/master/hosts.txt`: hostLine("0.0.0.0"),
`https://download.dnscrypt.info/blacklists/domains/mybase.txt`: domainListLine(),
`https://raw.githubusercontent.com/koala0529/adhost/master/adhosts`: hostLine("127.0.0.1"),
`http://mirror1.malwaredomains.com/files/justdomains`: domainListLine(),
`http://ransomwaretracker.abuse.ch/downloads/RW_DOMBL.txt`: domainListLine(),
`https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt`: domainListLine(),
`https://raw.githubusercontent.com/azet12/KADhosts/master/KADhosts.txt`: hostLine("0.0.0.0"),
`https://raw.githubusercontent.com/lack006/Android-Hosts-L/master/hosts_files/2016_hosts/AD`: hostLine("127.0.0.1"),
`https://gitlab.com/ZeroDot1/CoinBlockerLists/raw/master/hosts`: hostLine("0.0.0.0"),
}
shortURLs = []string{
`db.tt`,
`www.db.tt`,
`j.mp`,
`www.j.mp`,
`bit.ly`,
`www.bit.ly`,
`pix.bit.ly`,
`goo.gl`,
`www.goo.gl`,
}
whitelist = []whitelistChecker{
contains(`google-analytics`),
suffix(`msedge.net`),
equal(`amazonaws.com`),
equal(`mp.weixin.qq.com`),
equal(`url.cn`),
regex(`^s3[\d\w\-]*.amazonaws.com`),
suffix(`internetdownloadmanager.com`),
suffix(`.alcohol-soft.com`),
equal(`scootersoftware.com`),
regex(`[^ad]\.mail\.ru`),
regex(`[^ad]\.daum\.net`),
regex(`^\w{1,10}\.yandex\.`),
suffix(`.googlevideo.com`),
regex(`^[^\.]+\.elb\.amazonaws\.com`),
suffix(`.in-addr.arpa`),
suffix(`.url.cn`),
equal(`qq.com`),
equal(`www.qq.com`),
equal(`analytics.163.com`),
equal(`163.com`),
equal(`behance.net`),
suffix(`.verisign.com`),
contains(`mozilla`),
}
tlds = make(map[string]struct{})
tldsMutex sync.Mutex
effectiveTLDsNames []string
mutex sync.Mutex
sema = newSemaphore(50)
finalDomains = make(map[string]struct{})
blockDomain = make(chan string, 20)
quit = make(chan bool)
)
const (
blocklist = `toblock.lst`
blocklistWithoutShortURL = `toblock-without-shorturl.lst`
blocklistOptimized = `toblock-optimized.lst`
blocklistWithoutShortURLOptimized = `toblock-without-shorturl-optimized.lst`
tldsURL = `http://data.iana.org/TLD/tlds-alpha-by-domain.txt`
effectiveTLDsNamesURL = `https://publicsuffix.org/list/effective_tld_names.dat`
)
type semaphore struct {
c chan int
}
func newSemaphore(n int) *semaphore {
s := &semaphore{
c: make(chan int, n),
}
return s
}
func (s *semaphore) Acquire() {
s.c <- 0
}
func (s *semaphore) Release() {
<-s.c
}
type lineValidator func(s string) string
func hostLine(addr string) lineValidator {
regexPattern := fmt.Sprintf(`^(%s)\s+([\w\d\-\._]+)`, strings.Replace(addr, `.`, `\.`, -1))
validDomain := regexp.MustCompile(`^((xn--)?[\w\d]+([\w\d\-_]+)*\.)+\w{2,}$`)
validLine := regexp.MustCompile(regexPattern)
return func(s string) string {
ss := validLine.FindStringSubmatch(s)
if len(ss) > 1 {
if validDomain.MatchString(ss[2]) {
return ss[2]
}
}
log.Println("invalid line:", s)
return ""
}
}
func domainListLine() lineValidator {
validDomain := regexp.MustCompile(`^((xn--)?[\w\d]+([\w\d\-_]+)*\.)+\w{2,}$`)
return func(s string) string {
if validDomain.MatchString(s) {
return s
}
log.Println("invalid domain:", s)
return ""
}
}
type whitelistChecker func(s string) bool
func contains(pattern string) whitelistChecker {
return func(s string) bool {
return strings.Contains(s, pattern)
}
}
func suffix(pattern string) whitelistChecker {
return func(s string) bool {
return strings.HasSuffix(s, pattern)
}
}
func prefix(pattern string) whitelistChecker {
return func(s string) bool {
return strings.HasPrefix(s, pattern)
}
}
func equal(pattern string) whitelistChecker {
return func(s string) bool {
return pattern == s
}
}
func regex(pattern string) whitelistChecker {
r := regexp.MustCompile(pattern)
return func(s string) bool {
return r.MatchString(s)
}
}
func downloadRemoteContent(remoteLink string) (io.ReadCloser, error) {
response, err := http.Get(remoteLink)
if err != nil {
log.Println(err)
return nil, err
}
return response.Body, nil
}
func matchTLDs(domain string) bool {
dd := strings.Split(domain, ".")
lastSection := dd[len(dd)-1]
if _, ok := tlds[lastSection]; ok {
return true
}
for _, v := range effectiveTLDsNames {
if strings.HasSuffix(domain, v) {
return true
}
}
return false
}
func inWhitelist(domain string) bool {
for _, wl := range whitelist {
if wl(domain) {
return true
}
}
return false
}
func existent(domain string) (bool, error) {
req, err := http.NewRequest("GET", "https://dns.google.com/resolve", nil)
if err != nil {
log.Println("creating request failed:", domain, err)
return true, err
}
q := req.URL.Query()
q.Add("name", domain)
req.URL.RawQuery = q.Encode()
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
log.Println("doing request failed:", domain, err)
return true, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Println(domain, resp.Status)
return true, fmt.Errorf("unexpected status code:%s", resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("reading response failed:", domain, err)
return true, err
}
var response struct {
Status int `json:"Status"`
}
if err = json.Unmarshal(body, &response); err != nil {
log.Println("unmarshalling response failed:", domain, err)
return true, err
}
if response.Status == 3 {
return false, nil
}
return true, nil
}
func process(r io.ReadCloser, validator lineValidator) (domains []string, err error) {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
// extract valid lines
domain := validator(strings.ToLower(scanner.Text()))
if domain == "" {
continue
}
// remove items that don't match TLDs
if !matchTLDs(domain) {
log.Println("don't match TLDs:", domain)
continue
}
// remove items in white list
if inWhitelist(domain) {
log.Println("in whitelist:", domain)
continue
}
domains = append(domains, domain)
}
r.Close()
return
}
func saveToFile(content string, path string) error {
file, err := os.OpenFile(path, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0644)
if err == nil {
file.WriteString(content)
file.Close()
return nil
}
log.Println(err)
return err
}
func generateTLDs(wg *sync.WaitGroup) {
err := os.ErrNotExist
var r io.ReadCloser
for i := 0; i < 10 && err != nil; time.Sleep(5 * time.Second) {
r, err = downloadRemoteContent(tldsURL)
i++
}
if err == nil {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
tldsMutex.Lock()
tlds[strings.ToLower(scanner.Text())] = struct{}{}
tldsMutex.Unlock()
}
r.Close()
}
wg.Done()
}
func generateEffectiveTLDsNames(wg *sync.WaitGroup) {
err := os.ErrNotExist
var r io.ReadCloser
for i := 0; i < 10 && err != nil; time.Sleep(5 * time.Second) {
r, err = downloadRemoteContent(effectiveTLDsNamesURL)
i++
}
if err == nil {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := strings.ToLower(scanner.Text())
if len(line) == 0 {
continue
}
c := line[0]
if c >= byte('a') && c <= byte('z') || c >= byte('0') && c <= byte('9') {
if strings.IndexByte(line, byte('.')) < 0 {
tldsMutex.Lock()
tlds[line] = struct{}{}
tldsMutex.Unlock()
} else {
effectiveTLDsNames = append(effectiveTLDsNames, "."+line)
}
}
}
r.Close()
}
wg.Done()
}
func getDomains(u string, v lineValidator, domains map[string]struct{}, wg *sync.WaitGroup) {
// download hosts
err := os.ErrNotExist
var r io.ReadCloser
for i := 0; i < 10 && err != nil; time.Sleep(5 * time.Second) {
r, err = downloadRemoteContent(u)
i++
}
if err == nil {
d, _ := process(r, v)
for _, domain := range d {
// so could remove duplicates
mutex.Lock()
domains[domain] = struct{}{}
mutex.Unlock()
}
}
wg.Done()
}
func receiveDomains() {
for {
select {
case domain := <-blockDomain:
finalDomains[domain] = struct{}{}
case <-quit:
return
}
}
}
func checkExistent(domain string, wg *sync.WaitGroup) {
// remove items that doesn't exist actually
for i := 0; i < 10; time.Sleep(3 * time.Second) {
exists, err := existent(domain)
if err != nil {
continue
}
if exists {
blockDomain <- domain
} else {
log.Println("google dns reports as non-exist:", domain)
}
break
}
sema.Release()
wg.Done()
}
func main() {
var wg sync.WaitGroup
// generate TLDs
wg.Add(2)
go generateTLDs(&wg)
go generateEffectiveTLDsNames(&wg)
wg.Wait()
// get blocked domain names
domains := make(map[string]struct{})
wg.Add(len(sourceURLValidatorMap))
for u, v := range sourceURLValidatorMap {
go getDomains(u, v, domains, &wg)
}
wg.Wait()
// remove non-exist domain names
go receiveDomains()
wg.Add(len(domains))
for domain := range domains {
sema.Acquire()
go checkExistent(domain, &wg)
}
wg.Wait()
quit <- true
// handle domain names of short URL services
for _, v := range shortURLs {
delete(finalDomains, v)
}
d := make([]string, len(finalDomains))
i := 0
for k := range finalDomains {
d[i] = k
i++
}
// save to file in order
sort.Strings(d)
c := strings.Join(d, "\n")
saveToFile(c, blocklistWithoutShortURL)
d = append(d, shortURLs...)
sort.Strings(d)
c = strings.Join(d, "\n")
saveToFile(c, blocklist)
// optimized
d = make([]string, len(finalDomains))
i = 0
for k := range finalDomains {
pick := true
kk := strings.Split(k, ".")
for l := 1; l < len(kk); l++ {
dn := strings.Join(kk[l:], ".")
if _, ok := finalDomains[dn]; ok {
pick = false
break
}
}
if pick {
d[i] = k
i++
}
}
d = d[:i]
// save to file in order
sort.Strings(d)
c = strings.Join(d, "\n")
saveToFile(c, blocklistWithoutShortURLOptimized)
d = append(d, shortURLs...)
sort.Strings(d)
c = strings.Join(d, "\n")
saveToFile(c, blocklistOptimized)
}
|
package main
import (
"flag"
"fmt"
"os"
"path"
"strings"
utils "github.com/yametech/cloud-native-tools/pkg/utils"
)
func main() {
var url, codeType, projectPath, command string
var unitTest, sonar bool
flag.StringVar(&url, "url", "./Dockerfile", "-url ./")
flag.StringVar(&codeType, "codetype", "java-maven", "-codetype java-maven")
flag.StringVar(&projectPath, "path", "", "-path subdirectory")
flag.StringVar(&command, "command", "", "-Command go")
flag.BoolVar(&unitTest, "unittest", false, "-unittest True")
flag.BoolVar(&sonar, "sonar", false, "-sonar True")
flag.Parse()
fmt.Printf("url=%v codeType=%v ", url, codeType)
if unitTest {
fmt.Printf("unitTest command:%s\n", url, codeType, command)
}
err := CheckDockerFile(url, codeType, projectPath, unitTest, command, sonar)
if err != nil {
panic(err)
}
}
func CheckDockerFile(url, codeType, projectPath string, unitTest bool, command string, sonar bool) error {
count := strings.Index(url, "Dockerfile")
if count == -1 {
url = path.Join(url, "Dockerfile")
}
if sonar {
fmt.Printf("enter sonar mode\n")
err := sonarDocker(url, codeType)
if err != nil {
return err
}
return nil
}
switch codeType {
case "django":
err := djangoDocker(url)
if err != nil {
return err
}
case "java-maven":
err := javaDocker(url, projectPath, unitTest, command)
if err != nil {
return err
}
case "easyswoole":
err := easyswooleDocker(url)
if err != nil {
return err
}
case "web":
err := webDocker(url)
if err != nil {
return err
}
}
return nil
}
func sonarDocker(url, projectName string) error {
url = "/workspace/git/Dockerfile"
type Param struct {
Command string
}
fmt.Printf("project name: %s\n", projectName)
param := &Param{Command: projectName}
_ = param
content, err := Render(param, sonarContent)
err = utils.GenerateFile(url, content)
if err != nil {
return err
}
return nil
}
func webDocker(url string) error {
if _, err := os.Stat(url); os.IsNotExist(err) {
err = utils.GenerateFile(url, webContent)
if err != nil {
return err
}
}
ngFile := strings.Replace(url, "Dockerfile", "nginx.conf", -1)
if _, err := os.Stat(ngFile); os.IsNotExist(err) {
err = utils.GenerateFile(ngFile, ngContent)
if err != nil {
return err
}
}
return nil
}
func djangoDocker(filename string) error {
if _, err := os.Stat(filename); os.IsNotExist(err) {
err = utils.GenerateFile(filename, djangoDockerFileContent)
if err != nil {
return err
}
}
return nil
}
func javaDocker(filename, projectPath string, unitTest bool, command string) error {
type Param struct {
ProjectPath string
SkipTest string
Command string
}
param := &Param{ProjectPath: "*", SkipTest: ""}
if len(strings.Trim(projectPath, "")) > 0 {
param.ProjectPath = projectPath
}
if unitTest {
param.SkipTest = "-Dmaven.test.skip=true"
if len(command) != 0 {
param.Command = command
} else {
param.Command = "mvn test"
}
}
content, err := Render(param, javaMavenDockerfileContentTpl)
if err != nil {
panic(err)
}
if _, err := os.Stat(filename); os.IsNotExist(err) {
err = utils.GenerateFile(filename, content)
if err != nil {
return err
}
}
// if settings.xml not exists, create it too
xmlFile := strings.Replace(filename, "Dockerfile", "settings.xml", -1)
if _, err := os.Stat(xmlFile); os.IsNotExist(err) {
err = utils.GenerateFile(xmlFile, javaXmlContent)
if err != nil {
return err
}
}
if unitTest {
unitList := strings.Split(filename, "/")
unitList = unitList[:len(unitList)-1]
unitDockerfile := strings.Join(unitList, "/")
unitDockerfile = fmt.Sprintf("%s/%s", unitDockerfile, "Dockerfile-unittest")
content, err := Render(param, javaMavenUnitContent)
err = utils.GenerateFile(unitDockerfile, content)
if err != nil {
return err
}
}
return nil
}
func easyswooleDocker(filename string) error {
if _, err := os.Stat(filename); os.IsNotExist(err) {
err = utils.GenerateFile(filename, easySwooleContent)
if err != nil {
return err
}
}
return nil
}
|
package parser_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"testing"
"github.com/bddbnet/gospy/engine"
"github.com/bddbnet/gospy/model"
"github.com/bddbnet/gospy/parser/h.bilibili.com"
)
// step 4 获取用户图片总数
func TestUserUploadCount(t *testing.T) {
bytes, err := ioutil.ReadFile("count.json")
if err != nil {
t.Error(err)
}
j := engine.UploadCount{}
json.Unmarshal(bytes, &j)
userUploadCount := model.UserUploadCount{}
userUploadCount.DllCount = j.Data.AllCount
userUploadCount.DailyCount = j.Data.DailyCount
userUploadCount.DrawCount = j.Data.DrawCount
userUploadCount.PhotoCount = j.Data.PhotoCount
parseResult := h_bilibili_com.UserUploadCount(bytes, "")
if userUploadCount != parseResult.Items[0].Payload {
t.Error("not match")
fmt.Println(userUploadCount)
fmt.Println("----------")
fmt.Println(parseResult.Items[0])
}
}
|
// Package jobcontroller is the main Job runner for peridot.
// It operates as a set of gRPC clients, with each Agent separately
// running its own gRPC server.
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
package jobcontroller
import (
"context"
"fmt"
"log"
"sync"
"github.com/swinslow/peridot-core/pkg/agent"
)
// jobsData is the main set of data about the Jobs being managed by
// a JobController.
type jobsData struct {
// cfg is the JobController's own configuration
cfg Config
// jobs is where the actual master record of the Job's status lives
jobs map[uint64]*JobRecord
}
// JobController is the main Job runner function. It creates and returns
// three channels (described from the caller's perspective):
// * inJobStream, a write-only channel to submit new JobRequests, which must
// be closed by the caller
// * inJobUpdateStream, a write-only channel to submit a request for an
// update of one Job's status given its jobID, or 0 for all Jobs
// * jobRecordStream, a read-only channel with jobRecord updates
// * errc, a read-only channel where an error will be written or else
// nil if no errors in the controller itself are encountered.
func JobController(ctx context.Context, cfg Config) (chan<- JobRequest, chan<- uint64, <-chan JobRecord, <-chan error) {
// the caller will own the inJobStream channel and must close it
inJobStream := make(chan JobRequest)
// the caller will also own the inJobUpdateStream channel and must close it
inJobUpdateStream := make(chan uint64)
// we own the jobRecordStream channel
jobRecordStream := make(chan JobRecord)
// we own the errc channel. make it buffered so we can write 1 error
// without blocking.
errc := make(chan error, 1)
js := jobsData{
cfg: cfg,
jobs: map[uint64]*JobRecord{},
}
// rc is the response channel for all Job status messages.
rc := make(chan JobUpdate)
// n is the WaitGroup used to synchronize agent completion.
// Each runJob goroutine adds 1 to n when it starts.
var n sync.WaitGroup
// Here the JobController itself also adds 1 to n, and this 1 is
// Done()'d when the JobController's context gets cancelled,
// signalling the termination of the JobController.
n.Add(1)
// start a separate goroutine to wait on the waitgroup until all agents
// AND the JobController are done, and then close the response channel
go func() {
n.Wait()
close(rc)
}()
// now we start a goroutine to listen to channels and waiting for
// things to happen
go func() {
// note that this could introduce a race condition IF the JobController
// were to receive a cancel signal from context, and decremented n to
// zero, AND then a new Job were started, which would try to reuse
// the zeroed waitgroup. To avoid this, we set exiting to true before
// calling n.Done(), and after exiting is true we don't create any
// new Jobs.
exiting := false
for !exiting {
select {
case <-ctx.Done():
// the JobController has been cancelled and should shut down
exiting = true
n.Done()
case jr := <-inJobStream:
// the caller has submitted a new JobRequest; create the job
newJobID := startNewJob(ctx, &js, jr, &n, rc, errc)
// if newJobID is 0, we couldn't create a new job record.
if newJobID != 0 {
// otherwise broadcast the job record, whether or not it was
// started successfully, as long as it actually got a job ID.
updateJobRecord(&js, newJobID, nil, jobRecordStream)
}
case ju := <-rc:
// an agent has sent a JobUpdate
updateJobRecord(&js, ju.JobID, &ju, jobRecordStream)
case jobID := <-inJobUpdateStream:
// the caller has submitted a request for a JobRecord update
// we can get it by sending nil to updateJobRecord
updateJobRecord(&js, jobID, nil, jobRecordStream)
}
}
// FIXME as we are exiting, do we first need to drain any remaining
// FIXME updates from rc, and then report out all JobRecords?
}()
// finally we return the channels so that the caller can kick things off
return inJobStream, inJobUpdateStream, jobRecordStream, errc
}
func startNewJob(ctx context.Context, js *jobsData, jr JobRequest, n *sync.WaitGroup, rc chan<- JobUpdate, errc chan<- error) uint64 {
log.Printf("===> In startNewJob: jr = %s\n", jr.String())
// check that this job ID isn't already taken
_, ok := js.jobs[jr.JobID]
if ok {
// job ID is already in use; send error and bail out
err := fmt.Errorf("Requested new Job with ID %d but that ID is already used", jr.JobID)
errc <- err
return 0
}
// create a new JobRecord and fill it in
rec := &JobRecord{
JobID: jr.JobID,
AgentName: jr.AgentName,
Cfg: jr.Cfg,
// fill in default Status data since we haven't talked to the agent yet
Status: agent.StatusReport{
RunStatus: agent.JobRunStatus_STARTUP,
HealthStatus: agent.JobHealthStatus_OK,
},
}
js.jobs[rec.JobID] = rec
// check whether the requested agent name is valid
ar, ok := js.cfg.Agents[rec.AgentName]
if !ok {
log.Printf("===> Error\n")
// agent name is invalid; set error and bail out
rec.Err = fmt.Errorf("unknown agent name: %s", rec.AgentName)
return rec.JobID
}
// agent name was valid, we have the AgentRef now
// time to actually create the job
n.Add(1)
go runJobAgent(ctx, rec.JobID, ar, rec.Cfg, n, rc)
// return new job's ID
return rec.JobID
}
func updateJobRecord(js *jobsData, jobID uint64, ju *JobUpdate, jobRecordStream chan<- JobRecord) {
// if ju is nil, we're just sending the original record upon job creation
if ju != nil {
// if ju is non-nil, we need to update the record first
// look up job ID to make sure it's present
jr, ok := js.jobs[jobID]
if !ok {
// if the job ID doesn't exist, we can't do anything with this message
// but we also don't want to send it out on the stream; just exit
return
}
jr.Status = ju.Status
jr.Err = ju.Err
}
// now we broadcast the updated (or not) record
// make sure the job with this jobID exists (if ju was nil, we
// didn't check earlier)
jr, ok := js.jobs[jobID]
if !ok {
// if the job ID doesn't exist, we can't do anything with this message
// but we also don't want to send it out on the stream; just exit
return
}
jobRecordStream <- *jr
}
|
package main
import (
"time"
"strconv"
_ "net/http/pprof"
"net/http"
"log"
"fmt"
"os"
"io/ioutil"
"runtime/debug"
"io"
)
type Item int64
type Holder struct {
objects map[string]*Item
}
func (h *Holder) survive(dur time.Duration) {
time.Sleep(dur)
}
func main() {
h1 := Holder{
objects: make(map[string]*Item),
}
h2 := Holder{
objects: make(map[string]*Item),
}
fmt.Println("Setup")
http.Handle("/debug/pprof/heapdump", http.HandlerFunc(func(rw http.ResponseWriter, req*http.Request) {
f, err := ioutil.TempFile("", "dump")
if err != nil {
rw.WriteHeader(http.StatusServiceUnavailable)
io.WriteString(rw, err.Error())
return
}
fmt.Printf("Using %s as heap dump", f.Name())
defer os.Remove(f.Name())
defer f.Close()
debug.WriteHeapDump(f.Fd())
f.Close()
f2, err := os.Open(f.Name())
if err != nil {
rw.WriteHeader(http.StatusServiceUnavailable)
io.WriteString(rw, err.Error())
return
}
defer f2.Close()
io.Copy(rw, f2)
}))
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
for i := 0; i < 1000000; i++ {
it := Item(i)
s := strconv.FormatInt(int64(i), 10)
h1.objects[s] = &it
h2.objects[s] = &it
}
fmt.Println("Surviving")
go h1.survive(time.Second)
h1.survive(time.Hour * 24)
}
|
package main
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCatJSON(t *testing.T) {
tests := []struct {
name string
b []byte
want Cat
}{
{
b: []byte(`{"name":"Cheshire"}`),
want: Cat{Animal: &Animal{Name: "Cheshire"}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got Cat
err := json.Unmarshal(tt.b, &got)
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
|
package process
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"nginx-manager/utils"
"os"
)
type ResponseInfo struct {
Status int
Message string
Data interface{}
}
const nginxHttpDir = "/opt/nginx/conf/conf.d/"
const nginxBinaryFile = "/opt/nginx/sbin/nginx"
func Upload(c *gin.Context) {
msg, status := write(c)
c.JSON(http.StatusOK, gin.H{"status": status, "result": msg, "data": ""})
}
func Download(c *gin.Context) {
fileName := c.Query("name")
path := nginxHttpDir + fileName
rep := read(path)
c.JSONP(http.StatusOK, rep)
}
/**
尝试写入配置文件
*/
func write(c *gin.Context) (string, int) {
msg, status := "", 0
file, _ := c.FormFile("file")
name := file.Filename
path := nginxHttpDir + name
if utils.Exists(path) {
msg = "文件已存在:" + name
status = 1
logrus.Info(msg)
} else {
c.SaveUploadedFile(file, nginxHttpDir+name)
if re, code := Shell(nginxBinaryFile + " -t"); code != 0 {
status = 1
msg = "配置文件检测未通过:" + re
os.Remove(path)
} else {
Shell(nginxBinaryFile + " -s reload")
msg = "配置文件检测通过,并已生效"
}
}
return msg, status
}
func read(path string) (rep ResponseInfo) {
if !utils.Exists(path) {
rep.Status = 1
rep.Message = "文件不存在!"
} else {
b, err := ioutil.ReadFile(path)
logrus.Info("文件内容为:%b", string(b[:]))
if err != nil {
rep.Message = err.Error()
rep.Status = 1
} else {
rep.Status = 0
rep.Data = string(b[:])
}
}
return
}
|
package grade
import (
md "github.com/ebikode/eLearning-core/model"
tr "github.com/ebikode/eLearning-core/translation"
)
// GradeService provides grade operations
type GradeService interface {
GetGradeReports(int, int) []*md.GradeReport
GetGrade(uint) *md.Grade
GetGrades(int, int) []*md.Grade
GetGradesByApplication(int) *md.Grade
GetUserGrades(string) []*md.Grade
GetCourseGrades(string, int, int, int) []*md.Grade
CreateGrade(md.Grade) (*md.Grade, tr.TParam, error)
UpdateGrade(*md.Grade) (*md.Grade, tr.TParam, error)
}
type service struct {
pRepo GradeRepository
}
// NewService creates p grade service with the necessary dependencies
func NewService(
pRepo GradeRepository,
) GradeService {
return &service{pRepo}
}
/*
* Get single grade of a user
* @param userID => the ID of the user whose grade is needed
* @param gradeID => the ID of the grade requested.
*/
func (s *service) GetGrade(gradeID uint) *md.Grade {
return s.pRepo.Get(gradeID)
}
/*
* Get all grades
* @param page => the page number to return
* @param limit => limit per page to return
*/
func (s *service) GetGrades(page, limit int) []*md.Grade {
return s.pRepo.GetAll(page, limit)
}
func (s *service) GetGradesByApplication(applicationID int) *md.Grade {
return s.pRepo.GetByApplication(applicationID)
}
/*
* Get Grade Reports for each months
* @param page => the page number to return
* @param limit => limit per page to return
*/
func (s *service) GetGradeReports(page, limit int) []*md.GradeReport {
return s.pRepo.GetReports(page, limit)
}
/*
* Get all grades of a user
* @param userID => the ID of the user whose grade is needed
*/
func (s *service) GetUserGrades(userID string) []*md.Grade {
return s.pRepo.GetByUser(userID)
}
/*
* Get all grades of a course
* @param userID => the ID of the user who own the course
* @param courseID => the ID of the course whose grade is needed
* @param page => the page number to return
* @param limit => limit per page to return
*/
func (s *service) GetCourseGrades(userID string, courseID, page, limit int) []*md.Grade {
return s.pRepo.GetByCourse(userID, courseID, page, limit)
}
// Create New grade
func (s *service) CreateGrade(p md.Grade) (*md.Grade, tr.TParam, error) {
grade, err := s.pRepo.Store(p)
if err != nil {
tParam := tr.TParam{
Key: "error.resource_creation_error",
TemplateData: nil,
PluralCount: nil,
}
return grade, tParam, err
}
return grade, tr.TParam{}, nil
}
// update existing grade
func (s *service) UpdateGrade(p *md.Grade) (*md.Grade, tr.TParam, error) {
grade, err := s.pRepo.Update(p)
if err != nil {
tParam := tr.TParam{
Key: "error.resource_update_error",
TemplateData: nil,
PluralCount: nil,
}
return grade, tParam, err
}
return grade, tr.TParam{}, nil
}
|
package task
import (
"github.com/robfig/cron"
)
func PrepareCron() {
spec := "0, 10, 1, *, *, *" // 每天6:40
c := cron.New()
c.AddFunc(spec, taskEveryDay())
c.Start()
}
|
package parser
import (
"regexp"
)
func tokenize(sexpr string) []string {
re := regexp.MustCompile(`[\s,]*(~@|[\[\]{}()'` + "`" +
`~^@]|"(?:\\.|[^\\"])*"?|;.*|[^\s\[\]{}('"` + "`" +
`,;)]*)`)
rawTokens := []string{}
for _, group := range re.FindAllStringSubmatch(sexpr, -1) {
if (group[1] == "") || (group[1][0] == ';') {
continue
}
rawTokens = append(rawTokens, group[1])
}
tokens := []string{}
for index, rawToken := range rawTokens {
lToken := rawToken
rToken := rawToken
if index+1 < len(rawTokens) {
rToken = rawTokens[index+1]
if lToken == "~" && rToken == "@" {
tokens = append(tokens, "~@")
} else {
tokens = append(tokens, rawToken)
}
} else {
tokens = append(tokens, rawToken)
}
}
return tokens
}
|
package pgsql
import (
"testing"
)
func TestPath(t *testing.T) {
testlist2{{
valuer: PathFromFloat64Array2Slice,
scanner: PathToFloat64Array2Slice,
data: []testdata{
{input: [][2]float64(nil), output: [][2]float64(nil)},
{
input: [][2]float64{{0, 0}},
output: [][2]float64{{0, 0}}},
{
input: [][2]float64{{0, 0}, {1, 1}, {2, 0}},
output: [][2]float64{{0, 0}, {1, 1}, {2, 0}}},
{
input: [][2]float64{{0, 0.5}, {1.5, 1}, {2.4, 0.4}},
output: [][2]float64{{0, 0.5}, {1.5, 1}, {2.4, 0.4}}},
},
}, {
data: []testdata{
{input: string(`((0,0))`), output: string(`((0,0))`)},
{
input: string(`((0,0),(1,1))`),
output: string(`((0,0),(1,1))`)},
{
input: string(`[(0,0.5),(1.5,1),(2.23,0.623)]`),
output: string(`[(0,0.5),(1.5,1),(2.23,0.623)]`)},
},
}, {
data: []testdata{
{input: []byte(`((0,0))`), output: []byte(`((0,0))`)},
{
input: []byte(`((0,0),(1,1))`),
output: []byte(`((0,0),(1,1))`)},
{
input: []byte(`[(0,0.5),(1.5,1),(2.23,0.623)]`),
output: []byte(`[(0,0.5),(1.5,1),(2.23,0.623)]`)},
},
}}.execute(t, "path")
}
|
package main
import (
"io/ioutil"
"net/http"
"regexp"
)
func main(){
url := "https://github.com/probloys/webCatchForGit/file-list/master"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
ioutil.WriteFile("response.txt",body,0644)
//fmt.Println(res)
//fmt.Println(string(body))
//https://github.com/probloys/webCatchForGit/commit/f2a506ff81b9f1ee026e379d25227085c062bea3
//github.githubassets.com js-repo-pjax-container
x:=MatchLine(string(body))
for _,v:=range x{
println(v)
}
}
func MatchLine(partern string)[]string{
regexp.QuoteMeta("*href*")
regex,err:=regexp.Compile("href.*")
if err !=nil{
print("compile pattern error")
return nil
}
resultString:=regex.FindAllString(partern,10)
return resultString
}
|
package utils
import "testing"
func BenchmarkSlice2String(b *testing.B) {
info := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
for i := 0; i < b.N; i++ {
_, _ = Slice2String(info)
}
}
func TestSlice2String(t *testing.T) {
info := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
result := "1,2,3,4,5,6,7,8,9"
str, _ := Slice2String(info)
if str != result {
t.Errorf("程序错误,%s", str)
}
}
|
// Written in 2014 by Petar Maymounkov.
//
// It helps future understanding of past knowledge to save
// this notice, so peers of other times and backgrounds can
// see history clearly.
package model
import (
"github.com/hoijui/escher/pkg/be"
cir "github.com/hoijui/escher/pkg/circuit"
"github.com/hoijui/escher/pkg/faculty"
)
func init() {
faculty.Register(be.NewMaterializer(IgnoreValves{}), "model", "IgnoreValves")
}
type IgnoreValves struct{}
func (IgnoreValves) Spark(*be.Eye, cir.Circuit, ...interface{}) cir.Value {
return nil
}
func (IgnoreValves) CognizeCircuit(eye *be.Eye, v interface{}) {
u := v.(cir.Circuit).Copy()
n := u.Unify("ignoreValves")
u.Gate[n] = cir.NewVerbAddress("*", "Ignore")
u.Reflow(cir.Super, n)
eye.Show(cir.DefaultValve, u)
}
func (IgnoreValves) Cognize(eye *be.Eye, v interface{}) {}
|
package helpers
import (
"golang.org/x/crypto/bcrypt"
)
//HashPassword from string
func HashPassword(pwd string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(pwd), 10)
return string(bytes), err
}
//CheckPasswordHash compares regular password to hashpassword. Returns true in success or false on failure
func CheckPasswordHash(pwd, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
return err == nil
}
|
package connect
import (
"context"
"database/sql"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/lifenglin/micro-library/helper"
"github.com/sirupsen/logrus"
mysql2 "gorm.io/driver/mysql"
gorm2 "gorm.io/gorm"
"gorm.io/plugin/prometheus"
"path/filepath"
"sync"
"time"
)
var dbs *Dbs
type Dbs struct {
sync.RWMutex
Map map[string]*gorm.DB
}
func init() {
dbs = new(Dbs)
dbs.Map = make(map[string]*gorm.DB)
}
type mysqlClusterConfig struct {
ConnMaxLifetime int `json:"conn_max_lifetime"`
Dsn string `json:"dsn"`
MaxIdleConns int `json:"max_idle_conns"`
MaxOpenConns int `json:"max_open_conns"`
}
func MysqlInit(srvName string) {
var connSlice []*sql.Conn
defer func() {
for _, c := range connSlice {
_ = c.Close()
}
}()
hlp := new(helper.Helper)
hlp.Timer = new(helper.Timer)
hlp.MysqlLog = MysqlLog.WithTime(time.Now())
conf, _, err := newConfig(filepath.Join(srvName, "database"))
if err != nil {
hlp.MysqlLog.WithFields(logrus.Fields{
"err": err,
}).Error("get config")
return
}
var config map[string]interface{}
err = conf.Get(srvName, "database").Scan(&config)
if err != nil {
hlp.MysqlLog.WithFields(logrus.Fields{
"err": err,
}).Error("scan config")
return
}
for k, _ := range config {
db, err := ConnectDB(context.Background(), hlp, srvName, k, "master")
if err != nil {
hlp.MysqlLog.WithFields(logrus.Fields{
"name": k,
"err": err,
"cluster": "master",
}).Error("connect mysql error")
} else {
for i := 0; i < 10; i++ {
c, err := db.DB().Conn(context.Background())
if err == nil {
connSlice = append(connSlice, c)
}
}
}
db, err = ConnectDB(context.Background(), hlp, srvName, k, "slave")
if err != nil {
hlp.MysqlLog.WithFields(logrus.Fields{
"name": k,
"err": err,
"cluster": "slave",
}).Error("connect mysql error")
} else {
for i := 0; i < 10; i++ {
c, err := db.DB().Conn(context.Background())
if err == nil {
connSlice = append(connSlice, c)
}
}
}
}
}
func ConnectDB(ctx context.Context, hlp *helper.Helper, srvName string, name string, cluster string) (*gorm.DB, error) {
timer := hlp.Timer
timer.Start("connectDB")
defer timer.End("connectDB")
dbsKey := name + "." + cluster
mysqlLog := hlp.MysqlLog
dbs.RLock()
db, ok := dbs.Map[dbsKey]
dbs.RUnlock()
if !ok {
dbs.Lock()
existDb, ok := dbs.Map[dbsKey]
if ok {
db = existDb
} else {
conf, watcher, err := newConfig(filepath.Join(srvName, "database"))
if err != nil {
mysqlLog.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("read database config fail")
dbs.Unlock()
return nil, fmt.Errorf("read database config fail: %w", err)
}
var clusterConfig mysqlClusterConfig
conf.Get(srvName, "database", name, cluster).Scan(&clusterConfig)
mysqlLog.WithFields(logrus.Fields{
"srvName": srvName,
"name": name,
"cluster": cluster,
"dsn": clusterConfig.Dsn,
}).Info("connect mysql info")
db, err = gorm.Open("mysql", clusterConfig.Dsn)
if err != nil {
mysqlLog.WithFields(logrus.Fields{
"dsn": clusterConfig.Dsn,
"error": err.Error(),
}).Error("connect mysql fail")
dbs.Unlock()
return nil, fmt.Errorf("connect mysql fail: %w", err)
}
//设置连接池
db.DB().SetMaxIdleConns(clusterConfig.MaxIdleConns)
db.DB().SetMaxOpenConns(clusterConfig.MaxOpenConns)
db.DB().SetConnMaxLifetime(time.Duration(clusterConfig.ConnMaxLifetime) * time.Second)
db.SingularTable(true)
db.BlockGlobalUpdate(false)
dbs.Map[dbsKey] = db
db2, err := gorm2.Open(mysql2.Open(clusterConfig.Dsn), &gorm2.Config{})
if err == nil {
db2.ConnPool = db.DB()
db2.Use(prometheus.New(prometheus.Config{
DBName: srvName,
MetricsCollector: []prometheus.MetricsCollector{
&prometheus.MySQL{VariableNames: []string{"Threads_running"}},
},
}))
}
go func() {
v, err := watcher.Next()
if err != nil {
mysqlLog.WithFields(logrus.Fields{
"error": err,
"name": name,
"cluster": cluster,
"file": string(v.Bytes()),
}).Warn("reconect db")
} else {
mysqlLog.WithFields(logrus.Fields{
"name": name,
"cluster": cluster,
"file": string(v.Bytes()),
}).Info("reconnect db")
//配置更新了,释放所有已有的dbs对象,关闭连接
dbs.RLock()
db, ok := dbs.Map[dbsKey]
dbs.RUnlock()
if !ok {
return
}
dbs.Lock()
delete(dbs.Map, dbsKey)
dbs.Unlock()
//10秒后,关闭旧的数据库连接
time.Sleep(time.Duration(10) * time.Second)
err = db.Close()
if err == nil {
mysqlLog.WithFields(logrus.Fields{
"name": name,
"cluster": cluster,
"file": string(v.Bytes()),
}).Info("close db")
} else {
mysqlLog.WithFields(logrus.Fields{
"error": err,
"name": name,
"cluster": cluster,
"file": string(v.Bytes()),
}).Warn("close db error")
}
}
return
}()
}
dbs.Unlock()
}
newDb := db.New()
newDb.SetLogger(mysqlLog)
conf, _, err := ConnectConfig(srvName, "log")
if err != nil {
//配置获取失败
mysqlLog.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("read log config fail")
} else {
newDb.LogMode(conf.Get(srvName, "log", "mysql_detailed_log").Bool(false))
}
return newDb, nil
}
|
package pas
import (
"fmt"
"github.com/galaco/bsp/lumps"
"log"
)
func Calculate(numPortalClusters int) {
var bitbyte int32
var dest, src *int64
var scan *byte
var uncompressed [lumps.MAX_MAP_LEAFS/8]byte
var compressed [lumps.MAX_MAP_LEAFS/8]byte
fmt.Printf("Building PAS...\n")
count := 0
for i := 0; i < numPortalClusters; i++ {
scan = uncompressedvis + i*leafbytes
memcpy (uncompressed, scan, leafbytes)
for j := 0; j < leafbytes; j++ {
bitbyte = scan[j]
if bitbyte < 1 {
continue
}
for k := 0; k < 8; k++ {
if !(bitbyte & (1<<k)) {
continue
}
// OR this pvs row into the phs
index := (j<<3)+k
if index >= numPortalClusters {
log.Fatal("Bad bit in PVS") // pad bits should be 0
}
src = (long *)(uncompressedvis + index*leafbytes)
dest = (long *)uncompressed
for l := 0; l < leaflongs; l++ {
((long *)uncompressed)[l] |= src[l]
}
}
}
for j := 0; j < numPortalClusters; j++ {
if CheckBit( uncompressed, j ) {
count++
}
}
//
// compress the bit string
//
j := CompressVis (uncompressed, compressed)
dest = (long *)vismap_p
vismap_p += j
if (vismap_p > vismap_end)
log.Fatal("Vismap expansion overflow")
dvis->bitofs[i][DVIS_PAS] = (byte *)dest-vismap
memcpy (dest, compressed, j)
}
fmt.Printf("Average clusters audible: %i\n", count / numPortalClusters)
}
|
package dbl
import (
"database/sql"
"fmt"
"net"
"net/http"
"net/http/httputil"
//"path"
"github.com/dustin/go-humanize"
"github.com/espebra/filebin2/ds"
"strconv"
"time"
//"github.com/gorilla/mux"
)
type TransactionDao struct {
db *sql.DB
}
func (d *TransactionDao) Register(r *http.Request, bin string, filename string, timestamp time.Time, completed time.Time, status int, size int64) (transaction *ds.Transaction, err error) {
// Clean up before logging
r.Header.Del("authorization")
tr := &ds.Transaction{}
tr.BinId = bin
tr.Filename = filename
tr.Method = r.Method
tr.Path = r.URL.Path
tr.IP = r.RemoteAddr
tr.ClientId = r.Header.Get("CID")
// Remove the port if it's part of RemoteAddr
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
tr.IP = host
}
reqHeaders, err := httputil.DumpRequest(r, false)
if err != nil {
fmt.Printf("Unable to dump request: %s\n", err.Error())
}
tr.Headers = string(reqHeaders)
tr.Timestamp = timestamp
tr.CompletedAt = completed
tr.Status = status
tr.RespBytes = size
// XXX: It would be nice to count request body bytes instead
if r.Header.Get("content-length") != "" {
i, err := strconv.ParseInt(r.Header.Get("content-length"), 10, 0)
if err != nil {
// Did not get a valid content-length header, so
// set the log entry to -1 bytes to show that
// something is wrong. The request should be
// aborted, but the logging should not.
tr.ReqBytes = -1
}
tr.ReqBytes = i
}
err = d.Insert(tr)
return tr, err
}
//func (d *TransactionDao) Finish(tr *ds.Transaction) (err error) {
// var id string
// now := time.Now().UTC().Truncate(time.Microsecond)
// sqlStatement := "UPDATE transaction SET finished_at = $1 WHERE id = $2 RETURNING id"
// err = d.db.QueryRow(sqlStatement, now, tr.Id).Scan(&id)
// if err != nil {
// return err
// }
// tr.FinishedAt.Time = now
// tr.FinishedAtRelative = humanize.Time(tr.FinishedAt.Time)
// return nil
//}
func (d *TransactionDao) GetByClientId(id string) (transactions []ds.Transaction, err error) {
sqlStatement := "SELECT id, bin_id, filename, operation, method, path, ip, client_id, headers, timestamp, req_bytes, resp_bytes, status, completed FROM transaction WHERE client_id = $1 ORDER BY timestamp DESC"
rows, err := d.db.Query(sqlStatement, id)
if err != nil {
return transactions, err
}
defer rows.Close()
for rows.Next() {
var t ds.Transaction
err = rows.Scan(&t.Id, &t.BinId, &t.Filename, &t.Operation, &t.Method, &t.Path, &t.IP, &t.ClientId, &t.Headers, &t.Timestamp, &t.ReqBytes, &t.RespBytes, &t.Status, &t.CompletedAt)
if err != nil {
return transactions, err
}
t.TimestampRelative = humanize.Time(t.Timestamp)
t.ReqBytesReadable = humanize.Bytes(uint64(t.ReqBytes))
t.RespBytesReadable = humanize.Bytes(uint64(t.RespBytes))
t.Duration = t.CompletedAt.Sub(t.Timestamp)
transactions = append(transactions, t)
}
return transactions, nil
}
func (d *TransactionDao) GetByIP(ip string) (transactions []ds.Transaction, err error) {
sqlStatement := "SELECT id, bin_id, filename, operation, method, path, ip, client_id, headers, timestamp, req_bytes, resp_bytes, status, completed FROM transaction WHERE ip = $1 ORDER BY timestamp DESC"
rows, err := d.db.Query(sqlStatement, ip)
if err != nil {
return transactions, err
}
defer rows.Close()
for rows.Next() {
var t ds.Transaction
err = rows.Scan(&t.Id, &t.BinId, &t.Filename, &t.Operation, &t.Method, &t.Path, &t.IP, &t.ClientId, &t.Headers, &t.Timestamp, &t.ReqBytes, &t.RespBytes, &t.Status, &t.CompletedAt)
if err != nil {
return transactions, err
}
t.TimestampRelative = humanize.Time(t.Timestamp)
t.ReqBytesReadable = humanize.Bytes(uint64(t.ReqBytes))
t.RespBytesReadable = humanize.Bytes(uint64(t.RespBytes))
t.Duration = t.CompletedAt.Sub(t.Timestamp)
transactions = append(transactions, t)
}
return transactions, nil
}
func (d *TransactionDao) GetByBin(bin string) (transactions []ds.Transaction, err error) {
sqlStatement := "SELECT id, bin_id, filename, operation, method, path, ip, client_id, headers, timestamp, req_bytes, resp_bytes, status, completed FROM transaction WHERE bin_id = $1 ORDER BY timestamp DESC"
rows, err := d.db.Query(sqlStatement, bin)
if err != nil {
return transactions, err
}
defer rows.Close()
for rows.Next() {
var t ds.Transaction
err = rows.Scan(&t.Id, &t.BinId, &t.Filename, &t.Operation, &t.Method, &t.Path, &t.IP, &t.ClientId, &t.Headers, &t.Timestamp, &t.ReqBytes, &t.RespBytes, &t.Status, &t.CompletedAt)
if err != nil {
return transactions, err
}
t.TimestampRelative = humanize.Time(t.Timestamp)
t.ReqBytesReadable = humanize.Bytes(uint64(t.ReqBytes))
t.RespBytesReadable = humanize.Bytes(uint64(t.RespBytes))
t.Duration = t.CompletedAt.Sub(t.Timestamp)
transactions = append(transactions, t)
}
return transactions, nil
}
func (d *TransactionDao) Insert(t *ds.Transaction) (err error) {
//if t.Method == "POST" && t.Path == path.Join("/", t.BinId, t.Filename) {
// t.Operation = "file-upload"
//} else if t.Method == "GET" && t.Path == path.Join("/", t.BinId, t.Filename) {
// t.Operation = "file-download"
//} else if t.Path == path.Join("/archive", t.BinId, "zip") {
// t.Operation = "zip-download"
//} else if t.Path == path.Join("/archive", t.BinId, "tar") {
// t.Operation = "tar-download"
//} else if t.Method == "DELETE" && t.Path == path.Join("/", t.BinId) && t.Filename == "" {
// t.Operation = "bin-delete"
//} else if t.Method == "DELETE" && t.Path == path.Join("/", t.BinId, t.Filename) && t.Filename != "" {
// t.Operation = "file-delete"
//} else if t.Method == "PUT" && t.Path == path.Join("/", t.BinId) && t.Filename == "" {
// t.Operation = "bin-lock"
//}
sqlStatement := "INSERT INTO transaction (bin_id, filename, operation, method, path, ip, client_id, headers, timestamp, status, req_bytes, resp_bytes, completed) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id"
if err := d.db.QueryRow(sqlStatement, t.BinId, t.Filename, t.Operation, t.Method, t.Path, t.IP, t.ClientId, t.Headers, t.Timestamp, t.Status, t.ReqBytes, t.RespBytes, t.CompletedAt).Scan(&t.Id); err != nil {
return err
}
t.TimestampRelative = humanize.Time(t.Timestamp)
return nil
}
func (d *TransactionDao) Update(t *ds.Transaction) (err error) {
var id string
//now := time.Now().UTC().Truncate(time.Microsecond)
sqlStatement := "UPDATE transaction SET headers = $1 WHERE id = $2 RETURNING id"
err = d.db.QueryRow(sqlStatement, t.Headers, t.Id).Scan(&id)
if err != nil {
return err
}
//bin.UpdatedAt = now
//bin.UpdatedAtRelative = humanize.Time(bin.UpdatedAt)
return nil
}
func (d *TransactionDao) Cleanup(retention uint64) (count int64, err error) {
sqlStatement := fmt.Sprintf("DELETE FROM transaction WHERE timestamp < NOW() - INTERVAL '%d days'", retention)
res, err := d.db.Exec(sqlStatement)
if err != nil {
return count, err
}
n, err := res.RowsAffected()
count = n
if err != nil {
return count, err
}
return count, nil
}
|
package paramedic
const Version = "0.1.6"
|
package main
import "fmt"
/*
@Time : 2020/8/12 15:27
@Author : DELL ricemarch@foxmail.com
@tips: https://leetcode-cn.com/problems/merge-sorted-array/
*/
func merge(nums1 []int, m int, nums2 []int, n int) {
max := m + n
left, right := m-1, n-1
i := 1
for left >= 0 && right >= 0 {
if nums1[left] < nums2[right] {
nums1[max-i] = nums2[right]
i++
right--
} else {
nums1[max-i] = nums1[left]
i++
left--
}
}
if left == -1 {
for i := right; i >= 0; i-- {
nums1[i] = nums2[i]
}
}
}
func main() {
var nums1 = []int{0}
merge(nums1, 0, []int{1}, 1)
fmt.Println(nums1)
}
|
/*
* Copyright 2018 Haines Chan
*
* This program is free software; you can redistribute and/or modify it
* under the terms of the standard MIT license. See LICENSE for more details
*/
package runtime
// Runtime is the interface for runtime of the CNI
type Runtime interface {
}
|
package library
//file scope
import "fmt"
//package scope
var gopher = "gopher!!"
func bye() {
//block scope
var msg = "bye bye"
fmt.Println("from library hello.go:", msg, gopher)
}
|
package gag9
import (
"bytes"
"reflect"
"testing"
)
const RAW_HTML = `
<a class="badge-evt badge-track"
data-evt="PostList,TapPost,Tag,,PostTitle"
data-track="post,v,,,d,aKDjw1N,l"
data-entry-id="aKDjw1N"
data-position="1"
href="/gag/aKDjw1N"
target="_blank">
When you mix MJ with Got
</a>
<a class="badge-evt badge-track"
data-evt="PostList,TapPost,Tag,,PostTitle"
data-track="post,v,,,d,anjMq4b,l"
data-entry-id="anjMq4b"
data-position="4"
href="/gag/anjMq4b"
target="_blank">
Dammit Gilly !!! Tell your brother to step down ....
</a>
<a class="badge-evt badge-track"
data-evt="PostList,TapPost,Tag,,PostTitle"
data-track="post,v,,,d,aQe3PXK,l"
data-entry-id="aQe3PXK"
data-position="3"
href="/gag/aQe3PXK"
target="_blank">
[SPOILER] Nothing more to say
</a>
`
var gag9 *Gag9
func init() {
gag9 = New()
}
func TestFind(t *testing.T) {
memes := gag9.Find()
if memes == nil || len(memes) == 0 {
t.Error("expected list of memes")
}
}
func TestFindByTag(t *testing.T) {
memes := gag9.FindByTag("love")
if memes == nil || len(memes) == 0 {
t.Error("expected list of memes")
}
}
func TestCrawl(t *testing.T) {
expectedMemes := []Meme{
Meme{
Description: "When you mix MJ with Got",
Image: "https://img-9gag-fun.9cache.com/photo/aKDjw1N_460s.jpg",
},
Meme{
Description: "Dammit Gilly !!! Tell your brother to step down ....",
Image: "https://img-9gag-fun.9cache.com/photo/anjMq4b_460s.jpg",
},
Meme{
Description: "[SPOILER] Nothing more to say",
Image: "https://img-9gag-fun.9cache.com/photo/aQe3PXK_460s.jpg",
},
}
gotMemes := crawl(bytes.NewBufferString(RAW_HTML))
if !reflect.DeepEqual(expectedMemes, gotMemes) {
t.Error(
"expected", expectedMemes,
"got", gotMemes,
)
}
}
|
/*
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
package main
import (
"fmt"
"strings"
)
func main() {
s := "uqinntq"
fmt.Println(lengthOfLongestSubstring(s))
}
func lengthOfLongestSubstring(s string) int {
max, count := 1, 1
var (
index_begin int
index_repeat int
curmax_string string
cur byte
)
if len(s) == 0 {
return 0
}
index_begin = 0
for i := 1; i < len(s); i++ {
cur = s[i]
curmax_string = s[index_begin : count+index_begin]
index_repeat = strings.IndexByte(curmax_string, cur)
if index_repeat == -1 {
count++
if count > max {
max = count
}
} else {
count = count - index_repeat
index_begin = index_begin + index_repeat + 1
}
}
return max
}
|
package slacktest
import (
"testing"
slack "github.com/nlopes/slack"
"github.com/stretchr/testify/assert"
)
func TestPostMessageHandler(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
channel, tstamp, err := client.PostMessage("foo", t.Name(), slack.PostMessageParameters{})
assert.NoError(t, err, "should not error out")
assert.Equal(t, "foo", channel, "channel should be correct")
assert.NotEmpty(t, tstamp, "timestamp should not be empty")
}
func TestServerListChannels(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
channels, err := client.GetChannels(true)
assert.NoError(t, err)
assert.Len(t, channels, 2)
assert.Equal(t, "C024BE91L", channels[0].ID)
assert.Equal(t, "C024BE92L", channels[1].ID)
for _, channel := range channels {
assert.Equal(t, "W012A3CDE", channel.Creator)
}
}
func TestUserInfoHandler(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
user, err := client.GetUserInfo("123456")
assert.NoError(t, err)
assert.Equal(t, "W012A3CDE", user.ID)
assert.Equal(t, "spengler", user.Name)
assert.True(t, user.IsAdmin)
}
func TestBotInfoHandler(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
bot, err := client.GetBotInfo(s.BotID)
assert.NoError(t, err)
assert.Equal(t, s.BotID, bot.ID)
assert.Equal(t, s.BotName, bot.Name)
assert.False(t, bot.Deleted)
}
func TestListGroupsHandler(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
groups, err := client.GetGroups(true)
assert.NoError(t, err)
if !assert.Len(t, groups, 1, "should have one group") {
t.FailNow()
}
mygroup := groups[0]
assert.Equal(t, "G024BE91L", mygroup.ID, "id should match")
assert.Equal(t, "secretplans", mygroup.Name, "name should match")
assert.True(t, mygroup.IsGroup, "should be a group")
}
func TestListChannelsHandler(t *testing.T) {
s := NewTestServer()
go s.Start()
slack.SLACK_API = s.GetAPIURL()
client := slack.New("ABCDEFG")
channels, err := client.GetChannels(true)
assert.NoError(t, err)
if !assert.Len(t, channels, 2, "should have two channels") {
t.FailNow()
}
generalChan := channels[0]
otherChan := channels[1]
assert.Equal(t, "C024BE91L", generalChan.ID, "id should match")
assert.Equal(t, "general", generalChan.Name, "name should match")
assert.Equal(t, "Fun times", generalChan.Topic.Value)
assert.True(t, generalChan.IsMember, "should be in channel")
assert.Equal(t, "C024BE92L", otherChan.ID, "id should match")
assert.Equal(t, "bot-playground", otherChan.Name, "name should match")
assert.Equal(t, "Fun times", otherChan.Topic.Value)
assert.True(t, otherChan.IsMember, "should be in channel")
}
|
// storage
package models
import (
"container/list"
"fmt"
)
const (
MAX_USER = 100 // max user in this system
MAX_PLAYER = 10 // max player in one court
)
// error state code
type ErrCode int
const (
NO_ERR = iota
ERR_MAX_USER
ERR_ANY = -1
)
// define interactive messges with external
type MsgID int
const (
USER_REGISTER = iota
USER_LOGIN
COURT_ADD
COURT_REMOVE
COURT_MODIFY
PLAYER_ADD
PLAYER_REMOVE
)
// usually we let court owner decided the courtType
type CourtType int
const (
MULTI_BALLS = iota
COMPETITION
PRACTISE
)
type UserInfo struct {
UserID int
NickName string
Password string
Phone string
Email string
}
var userList = list.New()
func Register(user *UserInfo) ErrCode {
if userList.Len() > MAX_USER {
return ERR_MAX_USER
}
if user.UserID <= 0 || len(user.NickName) == 0 || len(user.Password) == 0 || len(user.Phone) == 0 {
return ERR_ANY
}
// add user to list
userList.PushBack(*user)
return NO_ERR
}
func Login(user *UserInfo) ErrCode {
if user.UserID <= 0 || len(user.Password) <= 0 {
return ERR_ANY
}
for list := userList.Front(); list != nil; list = list.Next() {
if user.UserID == list.Value.(UserInfo).UserID && user.Password == list.Value.(UserInfo).Password {
return NO_ERR
}
}
return ERR_ANY
}
func GetNickName(uID int) string {
for list := userList.Front(); list != nil; list = list.Next() {
if uID == list.Value.(UserInfo).UserID {
return list.Value.(UserInfo).NickName
}
}
return ""
}
func init() {
fmt.Println("STORAGE Init add Test Data .... ")
user1 := UserInfo{123, "ken", "kenchow", "15220090853", "buzz@boos.com"}
Register(&user1)
}
type CourtInfo struct {
Index int
Owner int
Number int
CourtType CourtType
Date string
Start_time int
End_time int
PlayersID []int
}
var courtList = list.New()
func AddCourt(court *CourtInfo) ErrCode {
var vaild = int(0)
// check the user list if the user had registered
for users := userList.Front(); users != nil; users = users.Next() {
if users.Value.(UserInfo).UserID == court.Owner {
vaild = 1
}
}
if vaild == 0 {
return ERR_ANY
}
// in case court repeat adding
for courts := courtList.Front(); courts != nil; courts = courts.Next() {
if courts.Value.(CourtInfo).Number == court.Number && courts.Value.(CourtInfo).Date == court.Date && courts.Value.(CourtInfo).Start_time == court.Start_time {
return ERR_ANY
}
}
if courtList.Front() != nil {
// apply unique index for the court
court.Index = courtList.Back().Value.(CourtInfo).Index + 1
}
courtList.PushBack(*court)
return NO_ERR
}
func RemoveCourt(court *CourtInfo) ErrCode {
for list := courtList.Front(); list != nil; list = list.Next() {
if list.Value.(CourtInfo).Index == court.Index {
courtList.Remove(list)
return NO_ERR
}
}
return ERR_ANY
}
func ModifyCourt(court *CourtInfo) ErrCode {
// TODO
return ERR_ANY
}
func indexOfPlayer(players []int, UserID int) int {
for i, v := range players {
if v == UserID {
return i
}
}
return ERR_ANY
}
func AddPlayer(courtIndex int, UserID int) ErrCode {
for list := courtList.Front(); list != nil; list = list.Next() {
if list.Value.(CourtInfo).Index == courtIndex {
tmp := list.Value.(CourtInfo)
// verify user if he got another court at the same time
// TODO
// find space for the new player
tmp.PlayersID = append(tmp.PlayersID, UserID)
list.Value = tmp
}
}
return NO_ERR
}
func RemovePlayer(courtIndex int, UserID int) ErrCode {
for list := courtList.Front(); list != nil; list = list.Next() {
if list.Value.(CourtInfo).Index == courtIndex {
tmp := list.Value.(CourtInfo)
index := indexOfPlayer(tmp.PlayersID, UserID)
// delete index value
tmp.PlayersID = append(tmp.PlayersID[:index], tmp.PlayersID[index+1:]...)
list.Value = tmp
}
}
return NO_ERR
}
type ScoreBoard struct {
UserID int
joinTimes int
totalScore int
average int
}
|
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"time"
dapr "github.com/dapr/go-sdk/client"
"github.com/dapr/go-sdk/service/common"
daprd "github.com/dapr/go-sdk/service/http"
"github.com/ohler55/ojg/jp"
"github.com/ohler55/ojg/oj"
"github.com/rs/xid"
)
func main() {
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
c, err := dapr.NewClient()
if err != nil {
logger.Fatal(err)
}
defer c.Close()
secrets, err := c.GetSecret(context.Background(), "kubernetes", "azure-maps", nil)
if err != nil {
logger.Fatal(err)
}
key, ok := secrets["subscription-key"]
if !ok {
logger.Fatal("subscription-key missing")
}
h := handler{
logger: logger,
key: key,
u: url.URL{
Scheme: "https",
Host: "atlas.microsoft.com",
},
p: url.Values{
"api-version": []string{"1.0"},
"language": []string{"en-US"},
"query": []string{},
"subscription-key": []string{key},
},
parser: oj.Parser{},
c: c,
}
s := daprd.NewService(":8080")
sub := &common.Subscription{
PubsubName: "pubsub",
Topic: "delivery-requests",
Route: "/delivery-requests",
}
err = s.AddTopicEventHandler(sub, h.handle())
if err != nil {
logger.Fatal(err)
}
logger.Printf("listening on :8080")
logger.Fatal(s.Start())
}
type handler struct {
logger *log.Logger
key string
u url.URL
p url.Values
parser oj.Parser
c dapr.Client
}
type topicEventHandlerFunc func(context.Context, *common.TopicEvent) (bool, error)
func (h handler) handle() topicEventHandlerFunc {
return func(ctx context.Context, e *common.TopicEvent) (bool, error) {
h.logger.Printf(
"event - PubsubName:%s, Topic:%s, ID:%s, Data: %v",
e.PubsubName, e.Topic, e.ID, e.Data,
)
var req deliveryRequest
err := oj.Unmarshal([]byte(e.Data.(string)), &req)
if err != nil {
return true, nil
}
from, err := h.findGeolocation(req.From)
if err != nil {
return true, nil
}
to, err := h.findGeolocation(req.To)
if err != nil {
return true, nil
}
r, err := h.findRoute(from, to)
if err != nil {
return true, nil
}
id := xid.New().String()
d := delivery{
ID: id,
From: from,
To: to,
Route: route{
Distance: r.LengthInMeters,
EstimatedTravelTime: r.TravelTimeInSeconds,
},
}
_, err = h.scheduleDelivery(ctx, d)
if err != nil {
return true, nil
}
return false, nil
}
}
type deliveryRequest struct {
ID string `json:"id,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
}
func (h *handler) findGeolocation(address string) (geolocation, error) {
h.logger.Printf("finding geolocation for address: %s", address)
h.p.Set("query", address)
h.u.Path = "search/address/json"
h.u.RawQuery = h.p.Encode()
resp, err := http.Get(h.u.String())
if err != nil {
return geolocation{}, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return geolocation{}, err
}
data, err := h.parser.Parse(b)
if err != nil {
return geolocation{}, err
}
x := jp.MustParseString("$.results[?(@.type == 'Point Address' || @.type == 'Address Range')].position")
result := x.Get(data)[0]
var g geolocation
err = h.parser.Unmarshal([]byte(oj.JSON(result)), &g)
if err != nil {
return geolocation{}, nil
}
h.logger.Printf("geolocation: %v", g.String())
return g, nil
}
type geolocation struct {
Lat float64 `json:"lat,omitempty"`
Lon float64 `json:"lon,omitempty"`
}
func (g geolocation) String() string {
return fmt.Sprintf("%v,%v", g.Lat, g.Lon)
}
func (h *handler) findRoute(from, to geolocation) (azureRoute, error) {
h.logger.Printf("finding route between %v and %v", from, to)
h.p.Set("query", fmt.Sprintf("%s:%s", from.String(), to.String()))
h.u.Path = "route/directions/json"
h.u.RawQuery = h.p.Encode()
resp, err := http.Get(h.u.String())
if err != nil {
return azureRoute{}, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return azureRoute{}, err
}
data, err := h.parser.Parse(b)
if err != nil {
return azureRoute{}, err
}
x := jp.MustParseString("$.routes[0].summary")
result := x.Get(data)[0]
var r azureRoute
err = h.parser.Unmarshal([]byte(oj.JSON(result)), &r)
if err != nil {
return azureRoute{}, err
}
h.logger.Printf("distance: %v", r.LengthInMeters)
h.logger.Printf("estimated travel time: %v", r.TravelTimeInSeconds)
return r, nil
}
type azureRoute struct {
LengthInMeters int `json:"lengthInMeters,omitempty"`
TravelTimeInSeconds time.Duration `json:"travelTimeInSeconds,omitempty"`
}
type route struct {
Distance int `json:"distance,omitempty"`
EstimatedTravelTime time.Duration `json:"estimated_travel_time,omitempty"`
}
func (h *handler) scheduleDelivery(ctx context.Context, d delivery) (string, error) {
h.logger.Printf("scheduling delivery: %#v", d)
b, err := oj.Marshal(d)
if err != nil {
return "", err
}
b, err = h.c.InvokeMethodWithContent(ctx, "courier", "schedule-delivery", http.MethodPost, &dapr.DataContent{
ContentType: "application/json",
Data: b,
})
if err != nil {
return "", err
}
h.logger.Printf("scheduled delivery with courier: %v", string(b))
return string(b), err
}
type delivery struct {
ID string `json:"id,omitempty"`
From geolocation `json:"from,omitempty"`
To geolocation `json:"to,omitempty"`
Route route `json:"route,omitempty"`
}
|
// Copyright 2018 Lars Hoogestraat
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package middleware
import (
"encoding/json"
"net/http"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/models"
)
// JSONHandler marshals JSON and writes to the http response
type JSONHandler struct {
AppCtx *AppContext
Handler JHandler
}
// JHandler enriches handler with the AppContext
type JHandler func(*AppContext, http.ResponseWriter, *http.Request) (*models.JSONData, error)
func (fn JSONHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
logWithIP := logger.Log.WithField("ip", getIP(r))
code := http.StatusOK
rw.Header().Set("Content-Type", "application/json")
data, err := fn.Handler(fn.AppCtx, rw, r)
if err != nil {
switch e := err.(type) {
case *httperror.Error:
code = e.HTTPStatus
default:
code = http.StatusInternalServerError
}
logWithIP.Error(err)
j, err := json.Marshal(err)
if err != nil {
logWithIP.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.WriteHeader(code)
_, err = rw.Write(j)
if err != nil {
logWithIP.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
return
}
j, err := json.Marshal(data)
if err != nil {
logWithIP.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(code)
_, err = rw.Write(j)
if err != nil {
logWithIP.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
|
package main
import (
_ "git.code.oa.com/trpc-go/trpc-filter/debuglog"
_ "git.code.oa.com/trpc-go/trpc-filter/recovery"
"git.code.oa.com/trpc-go/trpc-go"
thttp "git.code.oa.com/trpc-go/trpc-go/http"
"git.code.oa.com/trpc-go/trpc-go/log"
"git.woa.com/trpc-go/helloworld/pkg"
"git.woa.com/trpc-go/helloworld/pkg/admin"
pb "git.woa.com/trpcprotocol/helloworld"
"github.com/gorilla/mux"
)
func main() {
config, err := trpc.LoadConfig("./trpc_go.yaml")
if err != nil {
panic("load config fail: " + err.Error())
}
server := trpc.NewServerWithConfig(config)
//单服务多协议,naming肯定是全局唯一的,这样就可以rpc和http都可以调用了。
pb.RegisterGreeterService(server.Service("trpc.helloworld.Greeter"), pkg.Greeter)
pb.RegisterGreeterService(server.Service("trpc.helloworld.Greeter.http"), pkg.Greeter)
//thttp.RegisterServiceMux()
router := mux.NewRouter()
thttp.RegisterNoProtocolServiceMux(server.Service("helloworld.openapi"), router)
Router(router, &admin.Service{})
if err := server.Serve(); err != nil {
log.Fatal(err)
}
}
|
package fill
import "fmt"
type exampleStruct struct {
FieldA string
FieldB bool
FieldC int
}
type parentStruct struct {
exampleStruct
Struct exampleStruct
InterfaceStruct exampleStruct
MapStruct map[string]string
}
var interfaceData map[string]interface{}
func ExampleFill_interfaceData() {
interfaceData = make(map[string]interface{})
interfaceData["FieldA"] = "foo"
interfaceData["FieldB"] = true
interfaceData["FieldC"] = 1234
interfaceData["Text"] = "bar"
interfaceData["Struct"] = exampleStruct{"Struct 1", true, 10}
interfaceData["InterfaceStruct"] = map[string]interface{}{
"FieldA": "Struct 2",
"FieldB": false,
"FieldC": 34,
}
interfaceData["MapStruct"] = map[string]interface{}{
"FieldA": "Struct 3",
"FieldB": true,
"FieldC": 56,
}
}
func ExampleFill_a() {
resultA := make(map[string]string)
Fill(interfaceData, resultA)
fmt.Println(resultA["FieldA"])
fmt.Println(resultA["Text"])
fmt.Println("nothing:", resultA["FieldB"])
// Output:
// foo
// bar
// nothing:
}
func ExampleFill_b() {
resultB := make(map[string]exampleStruct)
Fill(interfaceData, resultB)
fmt.Println(resultB["Struct"])
fmt.Println(resultB["InterfaceStruct"])
// Output:
// {Struct 1 true 10}
// {Struct 2 false 34}
}
func ExampleFill_c() {
var resultC parentStruct
Fill(interfaceData, &resultC)
fmt.Println(resultC.FieldA)
fmt.Println(resultC.FieldC)
fmt.Println(resultC.Struct.FieldA)
fmt.Println(resultC.InterfaceStruct.FieldA)
fmt.Println(resultC.MapStruct["FieldA"])
// Output:
// foo
// 1234
// Struct 1
// Struct 2
// Struct 3
}
func init() {
ExampleFill_interfaceData()
}
|
/*
The Challenge
Create a program that brute-force* decodes the MD5-hashed string, given here: 92a7c9116fa52eb83cf4c2919599c24a which translates to code-golf
The Rules
You may not use any built-in functions that decode the hash for you if the language you choose has such.
You may not use an online service to decode the hash for you.
This is code-golf, the program that accomplishes the task in the shortest amount of characters wins.
Good luck. May the brute-force be with you.
*Brute-Force definition: looping from a-zzz.. including abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[]\;',./~!@#$%^&*()_+{}|:"`<>? in a string, hashing it,
and testing it against the hash given until the correct string that has been hashed has been found. Print the string to the program's output stream.
*/
package main
import (
"bytes"
"crypto/md5"
"fmt"
)
func main() {
var (
hash = "92a7c9116fa52eb83cf4c2919599c24a"
alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[]\\;',./~!@#$%^&*()_+{}|:\"`<>?"
seed = mkseed("code-golf", alpha)
)
fmt.Println(brute(hash, alpha, seed))
}
func brute(h, a string, d []int) string {
var (
r string
p = d
)
for {
s := mkstr(p, a)
m := fmt.Sprintf("%x", md5.Sum([]byte(s)))
if h == m {
r = s
break
}
p = iter(p, a)
}
return r
}
func iter(p []int, a string) []int {
n := len(a)
i := 0
for ; i < len(p); i++ {
if p[i]++; p[i] >= n {
p[i] = 0
} else {
break
}
}
if i >= len(p) {
p = append(p, 0)
}
return p
}
func mkstr(p []int, a string) string {
w := new(bytes.Buffer)
for _, i := range p {
w.WriteByte(a[i])
}
return w.String()
}
func mkseed(s, a string) []int {
p := []int{}
loop:
for i := range s {
for j := range a {
if s[i] == a[j] {
p = append(p, j)
continue loop
}
}
}
return p
}
|
/*
Create a function that keeps only strings with repeating identical characters (in other words, it has a set size of 1).
Examples
identicalFilter(["aaaaaa", "bc", "d", "eeee", "xyz"])
➞ ["aaaaaa", "d", "eeee"]
identicalFilter(["88", "999", "22", "545", "133"])
➞ ["88", "999", "22"]
identicalFilter(["xxxxo", "oxo", "xox", "ooxxoo", "oxo"])
➞ []
Notes
A string with a single character is trivially counted as a string with repeating identical characters.
If there are no strings with repeating identical characters, return an empty array (see example #3).
*/
package main
func main() {
eq(filter([]string{"aaaaaa", "bc", "d", "eeee", "xyz"}), []string{"aaaaaa", "d", "eeee"})
eq(filter([]string{"88", "999", "22", "545", "133"}), []string{"88", "999", "22"})
eq(filter([]string{"xxxxo", "oxo", "xox", "ooxxoo", "oxo"}), []string{})
eq(filter([]string{"aaaaaa", "bc", "d", "eeee", "xyz"}), []string{"aaaaaa", "d", "eeee"})
eq(filter([]string{"1", "2", "3"}), []string{"1", "2", "3"})
}
func filter(s []string) []string {
var p []string
for i := range s {
if isrepeat(s[i]) {
p = append(p, s[i])
}
}
return p
}
func isrepeat(s string) bool {
var lr rune
for i, r := range s {
if i == 0 {
lr = r
}
if lr != r {
return false
}
}
return true
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func eq(s, t []string) {
assert(len(s) == len(t))
for i := range s {
assert(s[i] == t[i])
}
}
|
package countAndSay
import "strconv"
func countAndSay(n int) string {
prev, cur := "1", "1"
for i := 1; i < n; i++ {
cur = ""
num, value, nextPos := 0, "", 0
for nextPos != -1 {
num, value, nextPos = calc(prev, nextPos)
cur += strconv.Itoa(num) + value
}
prev = cur
}
return cur
}
func calc(s string, pos int) (num int, value string, nextPos int) {
value = s[pos : pos+1]
i := pos + 1
for ; i < len(s); i++ {
if s[i] != value[0] {
break
}
}
if i == len(s) { //normal
nextPos = -1
} else { //break
nextPos = i
}
return i - pos, value, nextPos
}
|
package backend
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"sync"
pkgerr "github.com/pkg/errors"
"github.com/square/beancounter/deriver"
"github.com/square/beancounter/reporter"
)
// FixtureBackend loads data from a file that was previously recorded by
// RecorderBackend
type FixtureBackend struct {
addrIndexMu sync.Mutex
addrIndex map[string]AddrResponse
txIndexMu sync.Mutex
txIndex map[string]TxResponse
blockIndexMu sync.Mutex
blockIndex map[uint32]BlockResponse
// channels used to communicate with the Accounter
addrRequests chan *deriver.Address
addrResponses chan *AddrResponse
txRequests chan string
txResponses chan *TxResponse
// channels used to communicate with the Blockfinder
blockRequests chan uint32
blockResponses chan *BlockResponse
transactionsMu sync.Mutex // mutex to guard read/writes to transactions map
transactions map[string]int64
// internal channels
doneCh chan bool
readOnly bool
height uint32
}
// NewFixtureBackend returns a new FixtureBackend structs or errors.
func NewFixtureBackend(filepath string) (*FixtureBackend, error) {
cb := &FixtureBackend{
addrRequests: make(chan *deriver.Address, 10),
addrResponses: make(chan *AddrResponse, 10),
txRequests: make(chan string, 1000),
txResponses: make(chan *TxResponse, 1000),
blockRequests: make(chan uint32, 10),
blockResponses: make(chan *BlockResponse, 10),
addrIndex: make(map[string]AddrResponse),
txIndex: make(map[string]TxResponse),
blockIndex: make(map[uint32]BlockResponse),
transactions: make(map[string]int64),
doneCh: make(chan bool),
}
f, err := os.Open(filepath)
if err != nil {
return nil, pkgerr.Wrap(err, "cannot open a fixture file")
}
defer f.Close()
if err := cb.loadFromFile(f); err != nil {
return nil, pkgerr.Wrap(err, "cannot load data from a fixture file")
}
go cb.processRequests()
return cb, nil
}
// AddrRequest schedules a request to the backend to lookup information related
// to the given address.
func (fb *FixtureBackend) AddrRequest(addr *deriver.Address) {
reporter.GetInstance().IncAddressesScheduled()
reporter.GetInstance().Logf("[fixture] scheduling address: %s", addr)
fb.addrRequests <- addr
}
// TxRequest schedules a request to the backend to lookup information related
// to the given transaction hash.
func (fb *FixtureBackend) TxRequest(txHash string) {
reporter.GetInstance().IncTxScheduled()
reporter.GetInstance().Logf("[fixture] scheduling tx: %s", txHash)
fb.txRequests <- txHash
}
func (fb *FixtureBackend) BlockRequest(height uint32) {
fb.blockRequests <- height
}
// AddrResponses exposes a channel that allows to consume backend's responses to
// address requests created with AddrRequest()
func (fb *FixtureBackend) AddrResponses() <-chan *AddrResponse {
return fb.addrResponses
}
// TxResponses exposes a channel that allows to consume backend's responses to
// address requests created with addrrequest().
// if an address has any transactions then they will be sent to this channel by the
// backend.
func (fb *FixtureBackend) TxResponses() <-chan *TxResponse {
return fb.txResponses
}
func (fb *FixtureBackend) BlockResponses() <-chan *BlockResponse {
return fb.blockResponses
}
// Finish informs the backend to stop doing its work.
func (fb *FixtureBackend) Finish() {
close(fb.doneCh)
}
func (fb *FixtureBackend) ChainHeight() uint32 {
return fb.height
}
func (fb *FixtureBackend) processRequests() {
for {
select {
case addr := <-fb.addrRequests:
fb.processAddrRequest(addr)
case tx := <-fb.txRequests:
fb.processTxRequest(tx)
case addrResp, ok := <-fb.addrResponses:
if !ok {
fb.addrResponses = nil
continue
}
fb.addrResponses <- addrResp
case txResp, ok := <-fb.txResponses:
if !ok {
fb.txResponses = nil
continue
}
fb.txResponses <- txResp
case block := <-fb.blockRequests:
fb.processBlockRequest(block)
case <-fb.doneCh:
return
}
}
}
func (fb *FixtureBackend) processAddrRequest(addr *deriver.Address) {
fb.addrIndexMu.Lock()
resp, exists := fb.addrIndex[addr.String()]
fb.addrIndexMu.Unlock()
if exists {
fb.addrResponses <- &resp
return
}
// assuming that address has not been used
fb.addrResponses <- &AddrResponse{
Address: addr,
}
}
func (fb *FixtureBackend) processTxRequest(txHash string) {
fb.txIndexMu.Lock()
resp, exists := fb.txIndex[txHash]
fb.txIndexMu.Unlock()
if exists {
fb.txResponses <- &resp
return
}
// assuming that transaction does not exist in the fixture file
}
func (fb *FixtureBackend) processBlockRequest(height uint32) {
fb.blockIndexMu.Lock()
resp, exists := fb.blockIndex[height]
fb.blockIndexMu.Unlock()
if exists {
fb.blockResponses <- &resp
return
}
log.Panicf("fixture doesn't contain block %d", height)
}
func (fb *FixtureBackend) loadFromFile(f *os.File) error {
var cachedData index
byteValue, err := ioutil.ReadAll(f)
if err != nil {
return err
}
err = json.Unmarshal(byteValue, &cachedData)
if err != nil {
return err
}
fb.height = cachedData.Metadata.Height
for _, addr := range cachedData.Addresses {
a := AddrResponse{
Address: deriver.NewAddress(addr.Path, addr.Address, addr.Network, addr.Change, addr.AddressIndex),
TxHashes: addr.TxHashes,
}
fb.addrIndex[addr.Address] = a
}
for _, tx := range cachedData.Transactions {
fb.txIndex[tx.Hash] = TxResponse{
Hash: tx.Hash,
Height: tx.Height,
Hex: tx.Hex,
}
fb.transactions[tx.Hash] = tx.Height
}
for _, b := range cachedData.Blocks {
fb.blockIndex[b.Height] = BlockResponse{
Height: b.Height,
Timestamp: b.Timestamp,
}
}
return nil
}
|
package gstreams
import (
"context"
"fmt"
"sync"
"github.com/davecgh/go-spew/spew"
"github.com/twmb/franz-go/pkg/kgo"
)
const (
stateCreated = iota
stateStarting
statePartitionsRevoked
statePartitionsAssigned
stateRunning
statePendingShutdown
statePending
)
type StreamThread struct {
tasks map[string]map[int32]*Task
m sync.Mutex
consumer *kgo.Client
}
func NewStreamThread(group string, topics ...string) *StreamThread {
client, _ := kgo.NewClient(kgo.SeedBrokers([]string{"localhost:9092"}...))
st := &StreamThread{
tasks: make(map[string]map[int32]*Task),
consumer: client,
}
client.AssignGroup(group, kgo.DisableAutoCommit(), kgo.GroupTopics(topics...), kgo.OnAssigned(func(ctx context.Context, topicPartitions map[string][]int32) {
st.m.Lock()
defer st.m.Unlock()
for topic, partitions := range topicPartitions {
if _, ok := st.tasks[topic]; !ok {
st.tasks[topic] = make(map[int32]*Task)
for _, p := range partitions {
// TODO - need TOPOLOGY here!
st.tasks[topic][p] = NewTask(client)
}
}
}
fmt.Println("assigned", topicPartitions)
}), kgo.OnRevoked(func(ctx context.Context, data map[string][]int32) {
// Commit task
// Close task
fmt.Println("Revoked")
spew.Dump(data)
}))
return st
}
func (st *StreamThread) Start() {
go st.run()
}
func (st *StreamThread) run() {
for {
// 1. Fetch records from client
fetches := st.consumer.PollFetches(context.TODO())
iter := fetches.RecordIter()
for _, fetchErr := range fetches.Errors() {
fmt.Printf(
"error consuming from topic: topic=%s, partition=%d, err=%v",
fetchErr.Topic, fetchErr.Partition, fetchErr.Err,
)
}
// 2. Add records to corresponding tasks
for !iter.Done() {
record := iter.Next()
fmt.Printf("consumed record with message: %v\n", string(record.Value))
if x, ok := st.tasks[record.Topic]; ok {
if m, ok := x[record.Partition]; ok {
m.AddRecords([]*kgo.Record{record})
}
}
}
// 3. Process tasks
for _, partition := range st.tasks {
for _, task := range partition {
task.Process()
}
}
// 4. Commit
// 4.1 Flush tasks -> individual nodes
// 4.2 Do actual commit
for _, partition := range st.tasks {
for _, task := range partition {
_ = task.Commit()
}
}
}
}
|
package apiclient
import (
"context"
workflowpkg "github.com/argoproj/argo/pkg/apiclient/workflow"
)
type logsIntermediary struct {
abstractIntermediary
logEntries chan *workflowpkg.LogEntry
}
func (c *logsIntermediary) Send(logEntry *workflowpkg.LogEntry) error {
c.logEntries <- logEntry
return nil
}
func (c *logsIntermediary) Recv() (*workflowpkg.LogEntry, error) {
select {
case err := <-c.error:
return nil, err
case logEntry := <-c.logEntries:
return logEntry, nil
}
}
func newLogsIntermediary(ctx context.Context) *logsIntermediary {
return &logsIntermediary{newAbstractIntermediary(ctx), make(chan *workflowpkg.LogEntry)}
}
|
package main
import (
"net/http"
"github.com/GeertJohan/go.rice"
"github.com/insionng/vodka"
)
func main() {
handler := http.StripPrefix(
"/static/", http.FileServer(rice.MustFindBox("app").HTTPBox()),
)
e := vodka.New()
e.Get("/static/*", func(c *vodka.Context) error {
handler.ServeHTTP(c.Response().Writer(), c.Request())
return nil
})
e.Run("localhost:1234")
}
|
package main
import "testing"
func TestP62(t *testing.T) {
v := solve()
out := 127035954683
if v != out {
t.Errorf("P62: %v\tExpected: %v", v, out)
}
}
|
//go:generate go run generate.go
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"regexp"
"sort"
"strings"
"github.com/elliotchance/pie/functions"
)
func check(err error) {
if err != nil {
panic(err)
}
}
func getIdentName(e ast.Expr) string {
switch v := e.(type) {
case *ast.Ident:
return v.Name
case *ast.StarExpr:
return "*" + getIdentName(v.X)
default:
panic(fmt.Sprintf("cannot decode %T", e))
}
}
func getKeyAndElementType(pkg *ast.Package, name string, typeSpec *ast.TypeSpec) (string, string, string, *TypeExplorer) {
pkgName := pkg.Name
if t, ok := typeSpec.Type.(*ast.ArrayType); ok {
explorer := NewTypeExplorer(pkg, getIdentName(t.Elt))
switch v := t.Elt.(type) {
case *ast.Ident:
if v == nil || v.Obj == nil {
break
}
if ts, ok := v.Obj.Decl.(*ast.TypeSpec); ok {
if _, ok := ts.Type.(*ast.InterfaceType); ok {
explorer.IsInterface = true
}
}
}
return pkgName, "", getIdentName(t.Elt), explorer
}
if t, ok := typeSpec.Type.(*ast.MapType); ok {
explorer := NewTypeExplorer(pkg, getIdentName(t.Value))
return pkgName, getIdentName(t.Key), getIdentName(t.Value), explorer
}
panic(fmt.Sprintf("type %s must be a slice or map", name))
}
func findType(pkgs map[string]*ast.Package, name string) (packageName, keyType, elementType string, explorer *TypeExplorer) {
for _, pkg := range pkgs {
for _, file := range pkg.Files {
for _, decl := range file.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
for _, spec := range genDecl.Specs {
if typeSpec, ok := spec.(*ast.TypeSpec); ok {
if typeSpec.Name.String() == name {
return getKeyAndElementType(pkg, name, typeSpec)
}
}
}
}
}
}
}
panic(fmt.Sprintf("type %s does not exist", name))
}
func getType(keyType, elementType string) int {
if keyType != "" {
return functions.ForMaps
}
switch elementType {
case "int8", "uint8", "byte", "int16", "uint16", "int32", "rune", "uint32",
"int64", "uint64", "int", "uint", "uintptr", "float32", "float64",
"complex64", "complex128":
return functions.ForNumbers
case "string":
return functions.ForStrings
}
return functions.ForStructs
}
func getImports(packageName, s string) (imports []string) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", s, parser.ImportsOnly)
if err != nil {
panic(err)
}
for _, s := range f.Imports {
importName := s.Path.Value
if importName == `"github.com/elliotchance/pie/pie"` &&
isSelfPackage(packageName) {
continue
}
imports = append(imports, importName)
}
return
}
func getAllImports(packageName string, files []string, explorer *TypeExplorer) (imports []string) {
mapImports := map[string]struct{}{}
for _, file := range files {
if !explorer.HasString() && strings.Contains(file, "mightBeString") {
mapImports[`"fmt"`] = struct{}{}
}
for _, imp := range getImports(packageName, file) {
mapImports[imp] = struct{}{}
}
}
for imp := range mapImports {
imports = append(imports, imp)
}
sort.Strings(imports)
return
}
// We have to generate imports slightly differently when we are building code
// that will go into its own packages vs an external package.
func isSelfPackage(packageName string) bool {
return packageName == "pie"
}
func main() {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, ".", nil, 0)
check(err)
for _, arg := range os.Args[1:] {
mapOrSliceType, fns := getFunctionsFromArg(arg)
packageName, keyType, elementType, explorer := findType(pkgs, mapOrSliceType)
kind := getType(keyType, elementType)
var templates []string
for _, function := range functions.Functions {
if fns[0] != "*" && !stringSliceContains(fns, function.Name) {
continue
}
if function.For&kind != 0 {
templates = append(templates, pieTemplates[function.Name])
}
}
// Aggregate imports.
t := fmt.Sprintf("package %s\n\n", packageName)
imports := getAllImports(packageName, templates, explorer)
if len(imports) > 0 {
t += "import ("
for _, imp := range imports {
t += fmt.Sprintf("\n\t%s", imp)
}
t += "\n)\n\n"
}
for _, tmpl := range templates {
i := strings.Index(tmpl, "//")
t += tmpl[i:] + "\n"
}
t = strings.Replace(t, "StringSliceType", mapOrSliceType, -1)
t = strings.Replace(t, "StringElementType", elementType, -1)
t = strings.Replace(t, "ElementType", elementType, -1)
t = strings.Replace(t, "MapType", mapOrSliceType, -1)
t = strings.Replace(t, "KeyType", elementType, -1)
t = strings.Replace(t, "KeySliceType", "[]"+keyType, -1)
t = strings.Replace(t, "SliceType", mapOrSliceType, -1)
if !explorer.HasEquals() {
re := regexp.MustCompile(`([\w_]+|[\w_]+\[\w+\])\.Equals\(([^)]+)\)`)
t = ReplaceAllStringSubmatchFunc(re, t, func(groups []string) string {
return fmt.Sprintf("%s == %s", groups[1], groups[2])
})
}
if !explorer.HasString() {
t = strings.Replace(t, "mightBeString.String()", `fmt.Sprintf("%v", mightBeString)`, -1)
}
switch kind {
case functions.ForNumbers:
t = strings.Replace(t, "ElementZeroValue", "0", -1)
case functions.ForStrings:
t = strings.Replace(t, "ElementZeroValue", `""`, -1)
case functions.ForStructs:
zeroValue := fmt.Sprintf("%s{}", elementType)
// If its a pointer we need to replace '*' -> '&' when
// instantiating.
if elementType[0] == '*' || explorer.IsInterface {
zeroValue = "nil"
}
t = strings.Replace(t, "ElementZeroValue", zeroValue, -1)
}
if isSelfPackage(packageName) {
t = strings.Replace(t, "pie.Strings", "Strings", -1)
t = strings.Replace(t, "pie.Ints", "Ints", -1)
t = strings.Replace(t, "pie.Float64s", "Float64s", -1)
}
// The TrimRight is important to remove an extra new line that conflicts
// with go fmt.
t = strings.TrimRight(t, "\n") + "\n"
err := ioutil.WriteFile(strings.ToLower(mapOrSliceType)+"_pie.go", []byte(t), 0755)
check(err)
}
}
func getFunctionsFromArg(arg string) (mapOrSliceType string, fns []string) {
parts := strings.Split(arg, ".")
if len(parts) < 2 {
panic("must specify at least one function or *: " + arg)
}
return parts[0], parts[1:]
}
func stringSliceContains(haystack []string, needle string) bool {
if haystack == nil {
return false
}
for _, w := range haystack {
if w == needle {
return true
}
}
return false
}
// http://elliot.land/post/go-replace-string-with-regular-expression-callback
func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
result := ""
lastIndex := 0
for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
groups := []string{}
for i := 0; i < len(v); i += 2 {
groups = append(groups, str[v[i]:v[i+1]])
}
if isNegative(str[v[0]-1]) {
result += str[lastIndex:v[0]] + addBrackets(repl(groups))
} else {
result += str[lastIndex:v[0]] + repl(groups)
}
lastIndex = v[1]
}
return result + str[lastIndex:]
}
func isNegative(b byte) bool {
return b == '!'
}
func addBrackets(str string) string {
return `(` + str + `)`
}
|
package engine
import (
"html/template"
"path/filepath"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/gin-gonic/contrib/renders/multitemplate"
"github.com/gin-gonic/gin"
"github.com/GoPex/caretaker/controllers"
"github.com/GoPex/caretaker/helpers"
)
// Application struct holding everything needed to serve Caretaker application
type Application struct {
Engine *gin.Engine
Config *helpers.Specification
}
// loadTemplates loads every templates applying includes while loading them
func loadTemplates(templatesDir string) multitemplate.Render {
r := multitemplate.New()
layouts, err := filepath.Glob(filepath.Join(templatesDir, "layouts/*.tmpl"))
if err != nil {
panic(err.Error())
}
includes, err := filepath.Glob(filepath.Join(templatesDir, "includes/*.tmpl"))
if err != nil {
panic(err.Error())
}
// Generate our templates map from our layouts/ and includes/ directories
for _, layout := range layouts {
files := append(includes, layout)
layoutName := strings.TrimSuffix(filepath.Base(layout), filepath.Ext(layout))
r.Add(layoutName, template.Must(template.ParseFiles(files...)))
}
return r
}
// Initialize to be executed before the application runs
func (caretaker *Application) Initialize(config *helpers.Specification) error {
// Set the log level to debug
logLevel, err := log.ParseLevel(config.LogLevel)
if err != nil {
return err
}
log.SetLevel(logLevel)
// Print all configuration variables
config.Describe()
// Assign the incoming configuration
caretaker.Config = config
// FIXME: Attribute the configuration globally for ease of use
helpers.Config = config
return nil
}
// New initialize the Application application based on the gin http framework
func New() *Application {
// Will be used to hold everything needed to serve Caretaker
var application Application
// Create an empty configuration to avoid panic
application.Config = &helpers.Specification{}
// Create a default gin stack
application.Engine = gin.Default()
// Load templates
application.Engine.HTMLRender = loadTemplates("templates")
// Routes
// Ping route
application.Engine.GET("/ping", controllers.GetPing)
// Info routes
info := application.Engine.Group("/info")
info.GET("/status", controllers.GetStatus)
info.GET("/version", controllers.GetVersion)
// Root
application.Engine.GET("/", controllers.GetHome)
// Load all static assets
application.Engine.Static("/static", "./static")
return &application
}
|
/*
Package signal manages signal handling.
*/
package signal
import (
"os"
"os/signal"
"syscall"
)
// Ignore sets all signals to be ignored
func Ignore() {
signal.Ignore()
}
// Hup sets f() to be run on receipt of SIGHUP
// SIGHUP is meant to be used to refresh program configuration
func Hup(f func()) {
sighup := make(chan os.Signal, 1)
signal.Notify(sighup, syscall.SIGHUP)
go func() {
for {
<-sighup
f()
}
}()
}
// Int sets f() to be run on receipt of SIGINT
// SIGINT is meant to be used to stop the program
func Int(f func()) {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT)
go func() {
<-sigint
f()
}()
}
// Quit sets f() to be run on receipt of SIGQUIT
// SIGQUIT is meant to be used to stop the program gracefully
func Quit(f func()) {
sigquit := make(chan os.Signal, 1)
signal.Notify(sigquit, syscall.SIGQUIT)
go func() {
<-sigquit
f()
}()
}
// Term sets f() to be run on receipt of SIGTERM
// SIGTERM is meant to be used to stop the program
func Term(f func()) {
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGTERM)
go func() {
<-sigterm
f()
}()
}
|
// Copyright 2015 Dejian Xu. All rights reserved.
/*
缠中说禅走势中枢某级别走势类型中,被至少三个连续次级别走势类型 所重叠 的部分。
具体的计算以前三个连续次级别的重叠为准,
严格的公式可以这样表示
次级别的连续三个走势类型 A、B、C,分别的高、低点是 a1\a2,b1\b2,c1\c2。
则,中枢的区间就是(max(a2,b2,c2),min(a1,b1,c1))
而实际上用目测就 可以,不用这么复 杂。
注意,次级别的前三个走势类型都是完成的才构成该级 别的缠中说禅走势中枢,
完成的走势类型,在次级别图上是很明显的,根本就不 用着再看次级别下面级别 的图了。
缠中说禅盘整
在任何级别的任何走势中,
某完成的走势类型只包含一个缠中说禅 走势中枢,
就称为该级别的缠中说禅盘整。
缠中说禅趋势
在任何级别的任何走势中,
某完成的走势类型至少包含两个以上依 次同向的缠中说禅走势中枢,
就称为该级别的缠中说禅趋势。
该方向向上就称为 上涨,
向下就称为下跌。
注意,趋势中的缠中说禅走势中枢之间必须绝对不存在 重叠。
缠中说禅技术分析基本原理一
任何级别的任何走势类型终要完成。
缠中说禅技术分析基本原理二
任何级别任何完成的走势类型,必然包含一个以上的缠中说禅走势中枢。
缠中说禅走势分解定理一
任何级别的任何走势,都可以分解成同级别“盘整”、“下跌”与“上涨”三种走势类型的连接。
缠中说禅走势分解定理二
任何级别的任何走势类型,都至少由三段以上次级别走势类型构成。
缠中说禅走势中枢定理一
在趋势中,连接两个同级别“缠中说禅走势中枢” 的必然是次级别以下级别(注次级别以及次级别以下级别)的走势类型。
缠中说禅走势中枢定理二
在盘整中,无论是离开还是返回“缠中说禅走势中枢”的走势类型必然是次级别以下的。
*/
package crawl
|
// +build unit
package api
import (
"flag"
"github.com/open-horizon/anax/exchange"
"github.com/open-horizon/anax/persistence"
"testing"
)
func init() {
flag.Set("alsologtostderr", "true")
flag.Set("v", "7")
// no need to parse flags, that's done by test framework
}
func Test_CreateService0(t *testing.T) {
dir, db, err := utsetup()
if err != nil {
t.Error(err)
}
defer cleanTestDir(dir)
surl := "http://dummy.com"
myOrg := "myorg"
vers := "[1.0.0,INFINITY)"
attrs := []Attribute{}
autoU := true
activeU := true
service := &Service{
Url: &surl,
Org: &myOrg,
VersionRange: &vers,
AutoUpgrade: &autoU,
ActiveUpgrade: &activeU,
Attributes: &attrs,
}
_, err = persistence.SaveNewExchangeDevice(db, "testid", "testtoken", "testname", false, myOrg, "apattern", persistence.CONFIGSTATE_CONFIGURING)
if err != nil {
t.Errorf("failed to create persisted device, error %v", err)
}
var myError error
errorhandler := GetPassThroughErrorHandler(&myError)
sHandler := getVariableServiceHandler(exchange.UserInput{})
errHandled, newService, msg := CreateService(service, errorhandler, getDummyGetPatterns(), getDummyServiceResolver(), sHandler, db, getBasicConfig(), false)
if errHandled {
t.Errorf("unexpected error (%T) %v", myError, myError)
} else if newService == nil {
t.Errorf("returned service should not be nil")
} else if msg == nil {
t.Errorf("returned msg should not be nil")
}
}
|
package app
// env vars settings.yaml
type Specification struct {
// Common App variables
AppName string `split_words:"true" default:"LocalOrderNumberGenerator"`
GitHash string `split_words:"true" default:"Github-Hash"`
Branch string `split_words:"true" default:"Github-Branch"`
BuildNumber string `split_words:"true" default:"Jenkins-BuildNumber"`
Environment string `split_words:"true" default:"LOCAL"`
NewRelicLicense string `split_words:"true"`
DatacenterId string `split_words:"true"`
MongoHost string `split_words:"true" default:"localhost:27017"`
}
var Configuration *Specification
|
package picker
import (
"context"
"testing"
"time"
)
func sleepAndSend(delay int, in chan<- interface{}, input interface{}) {
time.Sleep(time.Millisecond * time.Duration(delay))
in <- input
}
func sleepAndClose(delay int, in chan interface{}) {
time.Sleep(time.Millisecond * time.Duration(delay))
close(in)
}
func TestPicker_Basic(t *testing.T) {
in := make(chan interface{})
fast := SelectFast(context.Background(), in)
go sleepAndSend(20, in, 1)
go sleepAndSend(30, in, 2)
go sleepAndClose(40, in)
number, exist := <-fast
if !exist || number != 1 {
t.Error("should recv 1", exist, number)
}
}
func TestPicker_Timeout(t *testing.T) {
in := make(chan interface{})
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*5)
defer cancel()
fast := SelectFast(ctx, in)
go sleepAndSend(20, in, 1)
go sleepAndClose(30, in)
_, exist := <-fast
if exist {
t.Error("should recv false")
}
}
|
package gmgo
import (
"fmt"
"testing"
"time"
"github.com/globalsign/mgo/bson"
)
func testDBSession() *DbSession {
dbConfig := DbConfig{HostURL: "mongodb://localhost:27017/phildb-prod", DBName: "phildb-prod", UserName: "", Password: "", Mode: 1}
err := Setup(dbConfig)
if err != nil {
fmt.Printf("Connection failed %s", err)
return nil
}
philDB, err := Get("phildb-prod")
if err != nil {
fmt.Printf("Get db failed %s", err)
return nil
}
fmt.Println(philDB.Config.DBName)
return philDB.Session()
}
//test user object
type user struct {
ID bson.ObjectId `json:"id" bson:"_id,omitempty"`
CreatedDate *time.Time `json:"createdDate" bson:"createdDate,omitempty"`
UpdatedDate *time.Time `json:"updatedDate" bson:"updatedDate,omitempty"`
FullName string `json:"fullName" bson:"fullName" binding:"required"`
Email string `json:"email" bson:"email" binding:"required"`
PhoneNumber string `json:"phoneNumber" bson:"phoneNumber,omitempty"`
FromNumber string `json:"fromNumber" bson:"fromNumber,omitempty"`
ZipCode string `json:"zipCode" bson:"zipCode" binding:"required"`
City string `json:"city" bson:"city,omitempty"`
State string `json:"state" bson:"state,omitempty"`
}
func (u *user) CollectionName() string {
return "rexUser"
}
var TotalUserCount = -1
func xxTestPagedQuery(t *testing.T) {
session := testDBSession()
defer session.Close()
count := 0
pd := session.DocumentIterator(Q{"state": "CA"}, "rexUser")
//The Snashopt ($snapshot) operator prevents the cursor from returning a document more than
//once because an intervening write operation results in a move of the document.
pd.Load(IteratorConfig{PageSize: 50, Snapshot: true})
for pd.HasMore() {
usr := new(user)
err := pd.Next(usr)
if err != nil {
println(err.Error())
return
}
count = count + 1
}
if TotalUserCount == -1 {
println("Test failed. Set the value of TotalUserCount")
} else if count == TotalUserCount {
println("Test passed")
} else {
println("Test failed")
}
}
func xxTestSorting(t *testing.T) {
session := testDBSession()
defer session.Close()
itr := session.DocumentIterator(Q{"state": "CA"}, "rexUser")
itr.Load(IteratorConfig{Limit: 20, SortBy: []string{"-_id"}})
result, err := itr.All(new(user))
if err != nil {
println(err)
return
}
users := result.([]*user)
for _, usr := range users {
println(usr.ID.Hex() + " -- " + usr.CreatedDate.String())
}
}
func xxTestBatchAll(t *testing.T) {
session := testDBSession()
defer session.Close()
itr := session.DocumentIterator(Q{"state": "CA"}, "rexUser")
itr.Load(IteratorConfig{})
result, err := itr.All(new(user))
if err != nil {
println(err)
return
}
users := result.([]*user)
println(len(users))
}
func xxTestReadGridFSFile(t *testing.T) {
session := testDBSession()
file := new(File)
file.ByteLength = 1024
err := session.ReadFile("5713f1b0e4b067fc28d6fbaa", "rex_files", file)
if err != nil {
t.Errorf("File read failed %s", err)
return
}
fmt.Printf("File name:%s, Content Type: %s\n", file.Name, file.ContentType)
}
|
package cmd
import "github.com/urfave/cli"
var MXJobSubCommand = cli.Command{
Name: "mxjob",
Aliases: []string{"mx"},
Usage: "submit a MXJob as training job.",
Action: func(c *cli.Context) error {
return nil
},
}
|
package gmx
// syscall.Rusage instrumentation for linux
import "syscall"
import "time"
// constant copied from C header <linux/resource.h> to avoid requiring cgo
// (this is a kernel API, so it is going to be very very stable)
const RUSAGE_SELF = 0
func init() {
// publish the total CPU time (userspace+system) used by this process, in seconds
Publish("runtime.cpu.time", rusageCpu)
}
func rusageCpu() interface{} {
var rusage syscall.Rusage
err := syscall.Getrusage(RUSAGE_SELF, &rusage)
if err != nil {
return -1 // return an obviously wrong result
}
total := time.Second * time.Duration(rusage.Stime.Sec+rusage.Utime.Sec)
total += time.Microsecond * time.Duration(rusage.Stime.Usec+rusage.Utime.Usec)
return total.Seconds()
}
|
package main
import "fmt"
func main() {
nums := []int{2, 7, 11, 15}
target := 9
fmt.Println(twoSum1(nums, target))
fmt.Println(twoSum2(nums, target))
}
func twoSum1(nums []int, target int) []int {
m := make(map[int]int)
for idx, num := range nums {
if v, found := m[target-num]; found {
return []int{nums[v], num}
}
m[num] = idx
}
return nil
}
func twoSum2(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if (nums[i] + nums[j]) == target {
return []int{nums[i], nums[j]}
}
}
}
return []int{}
}
|
package dhmiddleware
import (
"github.com/cyongxue/magicbox/xhiris/xhdiagnose"
"github.com/cyongxue/magicbox/xhiris/xhlog"
"github.com/kataras/iris/v12"
"sync"
"time"
)
// todo: 其他同样类似算法实现
// https://mp.weixin.qq.com/s/5wPpHi8wwaGjen71qXon_A
type LimitUtil struct {
limitNumber int64 // 触发受限阈值
minSafeTime int64 // 最小安全期
limitTime int64 // 受限时长
cacheMutex sync.RWMutex
cacheMap map[string][]int64 // key ----- [access count, first access time]
limitMutex sync.RWMutex
limitMap map[string]int64 // key ----- release time
}
var LimitEngine *LimitUtil
func InitLimitUtil(limitNumber int, minSafeTime int, limitTime int) {
LimitEngine = &LimitUtil{
limitNumber: int64(limitNumber),
minSafeTime: int64(minSafeTime),
limitTime: int64(limitTime),
cacheMutex: sync.RWMutex{},
cacheMap: make(map[string][]int64),
limitMutex: sync.RWMutex{},
limitMap: make(map[string]int64),
}
go LimitEngine.intervalClearMap()
}
func (l *LimitUtil) intervalClearMap() {
defer xhdiagnose.RecoverFunc()
ticker := time.NewTicker(time.Duration(l.minSafeTime) * time.Second)
for {
select {
case <-ticker.C:
l.cacheMutex.Lock()
l.cacheMap = make(map[string][]int64)
l.cacheMutex.Unlock()
}
}
}
func (l *LimitUtil) filterLimitedMap() {
l.limitMutex.Lock()
defer l.limitMutex.Unlock()
nowSec := time.Now().Unix()
for k, v := range l.limitMap {
if v <= nowSec {
delete(l.limitMap, k)
}
}
}
func (l *LimitUtil) isLimit(ctx iris.Context, key string) bool {
l.limitMutex.RLock()
defer l.limitMutex.RUnlock()
if _, has := l.limitMap[key]; has {
return true
}
return false
}
func (l *LimitUtil) initKeyNumber(ctx iris.Context, key string) {
info := make([]int64, 2)
info[0] = 0
info[1] = time.Now().Unix()
l.cacheMap[key] = info
}
func (l *LimitUtil) CheckKeyLimit(ctx iris.Context, key string) bool {
if len(key) == 0 {
return false
}
l.filterLimitedMap()
if l.isLimit(ctx, key) {
xhlog.Warn(ctx, "CheckKeyLimit", map[string]interface{}{
"key": key,
"msg": "is limited",
})
return true
}
l.cacheMutex.Lock()
defer l.cacheMutex.Unlock()
if _, has := l.cacheMap[key]; has {
info := l.cacheMap[key]
info[0] = info[0] + 1
if info[0] > l.limitNumber {
firstAccessTime := info[1]
now := time.Now().Unix()
if now-firstAccessTime <= l.minSafeTime {
l.limitMutex.Lock()
l.limitMap[key] = now + l.limitTime
l.limitMutex.Unlock()
xhlog.Warn(ctx, "CheckKeyLimit", map[string]interface{}{
"key": key,
"now": now,
"firstAccessTime": firstAccessTime,
"duration": now - firstAccessTime,
"minSafeTime": l.minSafeTime,
"accessTime": info[0],
"msg": "is limited",
})
} else {
l.initKeyNumber(ctx, key)
xhlog.Info(ctx, "CheckKeyLimit", map[string]interface{}{
"key": key,
"firstAccessTime": time.Now().Unix(),
"minSafeTime": l.minSafeTime,
"msg": "reset count",
})
}
}
} else {
l.initKeyNumber(ctx, key)
xhlog.Info(ctx, "CheckKeyLimit", map[string]interface{}{
"key": key,
"firstAccessTime": time.Now().Unix(),
})
}
return false
}
|
package main
import "fmt"
type pessoa struct {
nome string
idade int
}
type dentista struct {
pessoa
dentesArrancados int
salario float64
}
type arquiteto struct {
pessoa
tipoConstrucao string
tamanhoLoucura string
}
type profissional interface {
saudacao()
}
func (d dentista) saudacao() {
fmt.Println("Olá, bom dia!", "Eu", d.nome, "já arraquei", d.dentesArrancados, "dentes")
}
func (a arquiteto) saudacao() {
fmt.Println("Olá, bom dia!", "Eu", a.nome, "faço construições do tipo", a.tipoConstrucao)
}
func mandarSaudar(ps ...profissional) {
for _, p := range ps {
p.saudacao()
}
}
func main() {
mrDente := dentista{
pessoa: pessoa{
nome: "Mr. Dente",
idade: 30,
},
dentesArrancados: 987,
salario: 8271.50,
}
mrPredio := arquiteto{
pessoa: pessoa{
nome: "Mr. Prédio",
idade: 50,
},
tipoConstrucao: "Verfical",
tamanhoLoucura: "D+",
}
// métodos
mrDente.saudacao()
mrPredio.saudacao()
fmt.Println()
// interface
mandarSaudar(mrDente, mrPredio)
}
|
package devto
import "testing"
func TestRetrieveTags(t *testing.T) {
client := NewClient("")
opt := &RetrieveTagsOption{
Page: 1,
}
tags, err := client.RetrieveTags(opt)
if err != nil {
t.Fatal(err)
}
if tags[0].Name != "javascript" {
t.Errorf("Got wrong name expect: %s, actual: %s\n", "javascritp", tags[0].Name)
}
}
|
/* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2019 Intel Corporation
*/
package ngcnef_test
import (
"context"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
ngcnef "github.com/open-ness/epcforedge/ngc/pkg/nef"
)
var _ = Describe("NefServer", func() {
var (
ctx context.Context
cancel func()
//testErr error
)
Describe("NefServer init", func() {
It("Will init NefServer - Invalid Configurations",
func() {
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
err := ngcnef.Run(ctx, "noconfig")
Expect(err).NotTo(BeNil())
})
It("Will init NefServer - No HTTP endpoints",
func() {
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
err := ngcnef.Run(ctx,
NefTestCfgBasepath+"invalid_no_eps.json")
Expect(err).NotTo(BeNil())
})
/*
// Commenting since its covered through other tests
It("Will init NefServer - Valid Configurations",
func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
testErr = ngcnef.Run(ctx,
NefTestCfgBasepath+"valid.json")
}()
// Send a cancel after 3 seconds
time.Sleep(3 * time.Second)
cancel()
Expect(testErr).To(BeNil())
})
*/
})
})
|
package requests
import "time"
var _ = time.Time{}
type CreateGithubCommit struct {
RepoName string
Comments string
UserName string
BranchName string
}
type UpdateGithubCommit struct {
RepoName string
Comments string
UserName string
BranchName string
}
func (c *CreateGithubCommit) Valid() error {
return validate.Struct(c)
}
func (c *UpdateGithubCommit) Valid() error {
return validate.Struct(c)
}
|
package main
import "fmt"
func main() {
printPointerMessage()
}
func printPointerMessage() {
count := 20
countPointer := &count
pointerValue := *countPointer
fmt.Printf("countPointer: %x\n", countPointer)
fmt.Printf("countPointerValue: %d", pointerValue)
}
|
package feed
import (
"camp/feed/api"
"camp/feed/service"
"camp/lib"
"encoding/json"
"github.com/globalsign/mgo/bson"
"github.com/simplejia/clog/api"
"net/http"
)
type AddReq struct {
Txt string `json:"txt"`
}
func (addReq *AddReq) Regular() (ok bool) {
if addReq == nil {
return
}
if addReq.Txt == "" {
return
}
return true
}
type AddResp struct {
Id bson.ObjectId `json:"id" bson:"_id"`
Txt string `json:"txt"`
}
// @prefilter("Cors")
func (feed *Feed) Add(w http.ResponseWriter, r *http.Request) {
fun := "feed.Feed.Add"
var addReq *AddReq
if err := json.Unmarshal(feed.ReadBody(r), &addReq); err != nil || !addReq.Regular() {
clog.Error("%s param err: %v, req: %v", fun, err, addReq)
feed.ReplyFail(w, lib.CodePara)
return
}
feedApi := api.NewFeed()
feedApi.Txt = addReq.Txt
feedApi.Id = bson.NewObjectId()
if err := service.NewFeed().Add(feedApi); err != nil {
clog.Error("%s feed.Add err: %v, req: %v", fun, err, addReq)
feed.ReplyFail(w, lib.CodeSrv)
return
}
resp := AddResp{feedApi.Id, feedApi.Txt}
feed.ReplyOk(w, &resp)
}
|
// -------------------------------------------------------------------
//
// salter: Tool for bootstrap salt clusters in EC2
//
// Copyright (c) 2013-2014 Orchestrate, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------
// +build (NOT darwin) AND (NOT linux)
package main
// Does nothing for platforms where there either isn't a need to closefrom()
// or there isn't a way to make it work.
func closeFrom(i int) {
}
|
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package light
import (
"github.com/hecate-tech/engine/core"
"github.com/hecate-tech/engine/gls"
)
// ILight is the interface that must be implemented for all light types.
type ILight interface {
RenderSetup(gs *gls.GLS, rinfo *core.RenderInfo, idx int)
}
|
/*
Package setupserver assists in setting up TLS credentials for a server.
Package setupserver provides convenience functions for setting up a server
with TLS credentials.
The package loads client and server certificates from files and registers
them with the lib/srpc package. The following command-line flags are
registered with the standard flag package:
-caFile: Name of file containing the root of trust
-certFile: Name of file containing the SSL certificate
-keyFile: Name of file containing the SSL key
*/
package setupserver
import (
"github.com/Cloud-Foundations/Dominator/lib/log"
)
type Params struct {
ClientOnly bool // If true, only register client certificate and key.
FailIfExpired bool // If true, fail if certificate not yet valid or expired.
Logger log.DebugLogger
}
func SetupTls() error {
return setupTls(Params{})
}
func SetupTlsClientOnly() error {
return setupTls(Params{ClientOnly: true})
}
func SetupTlsWithParams(params Params) error {
return setupTls(params)
}
|
package main
import (
"fmt"
)
func main() {
// pow := multiply("1099511627776", "1099511627776")
// fmt.Println(pow, getDigitsSum(pow))
pow := multiply("2", "1")
n := 40
for i := 2; i <= n; i++ {
pow = multiply(pow, "2")
fmt.Println("i=", i, pow)
}
fmt.Println("n=", n, getDigitsSum(pow), pow)
}
|
package main
import "fmt"
func main() {
sol := average([]float64{1.12341234, 2.4234, 3.24234, 4.5342534, 6.3245345})
fmt.Println(sol)
}
func average(slice []float64) (avg float64) {
var sum float64
for _, val := range slice {
sum += val
}
avg = sum / float64(len(slice))
return
}
func bubbleSort(slice []int {
for i, item := range slice {
// TODO:
}
}
|
package main
import (
"crypto/tls"
"crypto/x509"
"github.com/streadway/amqp"
"io/ioutil"
"log"
)
func main() {
// To get started with SSL/TLS follow the instructions for adding SSL/TLS
// support in RabbitMQ with a private certificate authority here:
//
// http://www.rabbitmq.com/ssl.html
//
// Then in your rabbitmq.config, disable the plain AMQP port, verify clients
// and fail if no certificate is presented with the following:
//
// [
// {rabbit, [
// {tcp_listeners, []}, % listens on 127.0.0.1:5672
// {ssl_listeners, [5671]}, % listens on 0.0.0.0:5671
// {ssl_options, [{cacertfile,"/path/to/your/testca/cacert.pem"},
// {certfile,"/path/to/your/server/cert.pem"},
// {keyfile,"/path/to/your/server/key.pem"},
// {verify,verify_peer},
// {fail_if_no_peer_cert,true}]}
// ]}
// ].
cfg := new(tls.Config)
// The self-signing certificate authority's certificate must be included in
// the RootCAs to be trusted so that the server certificate can be verified.
//
// Alternatively to adding it to the tls.Config you can add the CA's cert to
// your system's root CAs. The tls package will use the system roots
// specific to each support OS. Under OS X, add (drag/drop) your cacert.pem
// file to the 'Certificates' section of KeyChain.app to add and always
// trust.
//
// Or with the command line add and trust the DER encoded certificate:
//
// security add-certificate testca/cacert.cer
// security add-trusted-cert testca/cacert.cer
//
// If you depend on the system root CAs, then use nil for the RootCAs field
// so the system roots will be loaded.
cfg.RootCAs = x509.NewCertPool()
if ca, err := ioutil.ReadFile("testca/cacert.pem"); err == nil {
cfg.RootCAs.AppendCertsFromPEM(ca)
}
// Move the client cert and key to a location specific to your application
// and load them here.
if cert, err := tls.LoadX509KeyPair("client/cert.pem", "client/key.pem"); err == nil {
cfg.Certificates = append(cfg.Certificates, cert)
}
// Server names are validated by the crypto/tls package, so the server
// certificate must be made for the hostname in the URL. Find the commonName
// (CN) and make sure the hostname in the URL matches this common name. Per
// the RabbitMQ instructions for a self-signed cert, this defautls to the
// current hostname.
//
// openssl x509 -noout -in server/cert.pem -subject
//
// If your server name in your certificate is different than the host you are
// connecting to, set the hostname used for verification in
// ServerName field of the tls.Config struct.
conn, err := amqp.DialTLS("amqps://server-name-from-certificate/", cfg)
log.Print("conn: %v, err: %v", conn, err)
}
|
/*
Given a string, create a function which outputs an array, building and deconstructing the string letter by letter. See the examples below for some helpful guidance.
Examples
constructDeconstruct("Hello") ➞ [
"H",
"He",
"Hel",
"Hell",
"Hello",
"Hell",
"Hel",
"He",
"H"
]
constructDeconstruct("edabit") ➞ [
"e",
"ed",
"eda",
"edab",
"edabi",
"edabit",
"edabi",
"edab",
"eda",
"ed",
"e"
]
constructDeconstruct("the sun") ➞ [
"t",
"th",
"the",
"the ",
"the s",
"the su",
"the sun",
"the su",
"the s",
"the ",
"the",
"th",
"t"
]
Notes
Include spaces (see example #3).
*/
package main
import (
"bytes"
"fmt"
"reflect"
)
func main() {
test("Hello", []string{
"H",
"He",
"Hel",
"Hell",
"Hello",
"Hell",
"Hel",
"He",
"H",
})
test("edabit", []string{
"e",
"ed",
"eda",
"edab",
"edabi",
"edabit",
"edabi",
"edab",
"eda",
"ed",
"e",
})
test("the sun", []string{
"t",
"th",
"the",
"the ",
"the s",
"the su",
"the sun",
"the su",
"the s",
"the ",
"the",
"th",
"t",
})
test("so long partner", []string{"s", "so", "so ", "so l", "so lo", "so lon", "so long", "so long ", "so long p", "so long pa", "so long par", "so long part", "so long partn", "so long partne", "so long partner", "so long partne", "so long partn", "so long part", "so long par", "so long pa", "so long p", "so long ", "so long", "so lon", "so lo", "so l", "so ", "so", "s"})
test("s p a c e s", []string{"s", "s ", "s p", "s p ", "s p a", "s p a ", "s p a c", "s p a c ", "s p a c e", "s p a c e ", "s p a c e s", "s p a c e ", "s p a c e", "s p a c ", "s p a c", "s p a ", "s p a", "s p ", "s p", "s ", "s"})
test("edabit is a awesome", []string{"e", "ed", "eda", "edab", "edabi", "edabit", "edabit ", "edabit i", "edabit is", "edabit is ", "edabit is a", "edabit is a ", "edabit is a a", "edabit is a aw", "edabit is a awe", "edabit is a awes", "edabit is a aweso", "edabit is a awesom", "edabit is a awesome", "edabit is a awesom", "edabit is a aweso", "edabit is a awes", "edabit is a awe", "edabit is a aw", "edabit is a a", "edabit is a ", "edabit is a", "edabit is ", "edabit is", "edabit i", "edabit ", "edabit", "edabi", "edab", "eda", "ed", "e"})
test("123456789", []string{"1", "12", "123", "1234", "12345", "123456", "1234567", "12345678", "123456789", "12345678", "1234567", "123456", "12345", "1234", "123", "12", "1"})
test("", []string{})
test(" ", []string{" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "})
}
func test(s string, r []string) {
p := unravel(s)
fmt.Println(p)
assert(reflect.DeepEqual(p, r))
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func unravel(s string) []string {
r := []string{}
p := []rune(s)
for i := 0; i < len(p); i++ {
w := new(bytes.Buffer)
for j := 0; j <= i; j++ {
w.WriteRune(p[j])
}
r = append(r, w.String())
}
for i := len(r) - 2; i >= 0; i-- {
r = append(r, r[i])
}
return r
}
|
package blog
import (
"net/http"
)
type blogView struct {
}
func NewBlogView() *blogView {
v := new(blogView)
return v
}
func (v *blogView) Render(responseWriter http.ResponseWriter) error {
var err error
_, err = responseWriter.Write([]byte("<html><head></head><body>"))
if err != nil {
return err
}
_, err = responseWriter.Write([]byte("it/blog"))
if err != nil {
return err
}
_, err = responseWriter.Write([]byte("</body></html>"))
if err != nil {
return err
}
return err
}
|
package cmd
import (
"github.com/profiralex/go-bootstrap-redis/pkg/config"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "go-bootstrap-redis",
Short: "bootstrapped golang api",
Long: "bootstrapped golang api",
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
cobra.OnInitialize(initConfig)
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
config.Init()
}
|
package main
import (
"reflect"
"testing"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/grpc/greeter"
"golang.org/x/net/context"
)
func TestGreeter_Greet(t *testing.T) {
type fields struct {
Exclaim bool
}
type args struct {
ctx context.Context
r *greeter.GreetRequest
}
tests := []struct {
name string
fields fields
args args
want *greeter.GreetResponse
wantErr bool
}{
{"exclaim", fields{true}, args{context.Background(), &greeter.GreetRequest{Greeting: "Hello", Name: "there"}}, &greeter.GreetResponse{Response: "Hello there!"}, false},
{"goodbye", fields{false}, args{context.Background(), &greeter.GreetRequest{Greeting: "Goodbye", Name: "there"}}, &greeter.GreetResponse{Response: "Goodbye there."}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Greeter{
Exclaim: tt.fields.Exclaim,
}
got, err := g.Greet(tt.args.ctx, tt.args.r)
if (err != nil) != tt.wantErr {
t.Errorf("Greeter.Greet() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Greeter.Greet() = %v, want %v", got, tt.want)
}
})
}
}
|
package main
import (
"log"
)
type ConnectionLimiter struct {
concurrentConn int
bucket chan int
}
func NewConnLimiter(cc int) *ConnectionLimiter {
return &ConnectionLimiter{
concurrentConn: cc,
bucket: make(chan int, cc),
}
}
func (cl *ConnectionLimiter) GetConn() bool {
if len(cl.bucket) >= cl.concurrentConn {
log.Printf("Reached the rate limitation.")
return false
}
cl.bucket <- 1
return true
}
func (cl *ConnectionLimiter) ReleaseConn() {
c := <-cl.bucket
log.Printf("New connction coming: %d", c)
}
|
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package restore_test
import (
"context"
"testing"
"github.com/pingcap/kvproto/pkg/metapb"
recovpb "github.com/pingcap/kvproto/pkg/recoverdatapb"
"github.com/pingcap/tidb/br/pkg/conn"
"github.com/pingcap/tidb/br/pkg/gluetidb"
"github.com/pingcap/tidb/br/pkg/pdutil"
"github.com/pingcap/tidb/br/pkg/restore"
"github.com/stretchr/testify/require"
"github.com/tikv/client-go/v2/testutils"
pd "github.com/tikv/pd/client"
)
const (
numOnlineStore = 3
// test max allocate id
maxAllocateId = 0x176f
)
type testData struct {
ctx context.Context
cancel context.CancelFunc
mockPDClient pd.Client
mockRecovery restore.Recovery
}
func newRegionMeta(
RegionId uint64,
PeerId uint64,
LastLogTerm uint64,
LastIndex uint64,
CommitIndex uint64,
Version uint64,
Tombstone bool,
StartKey []byte,
EndKey []byte,
) *recovpb.RegionMeta {
return &recovpb.RegionMeta{
RegionId: RegionId,
PeerId: PeerId,
LastLogTerm: LastLogTerm,
LastIndex: LastIndex,
CommitIndex: CommitIndex,
Version: Version,
Tombstone: Tombstone,
StartKey: StartKey,
EndKey: EndKey,
}
}
func (t *testData) generateRegionMeta() {
storeMeta0 := restore.NewStoreMeta(1)
storeMeta0.RegionMetas = append(storeMeta0.RegionMetas, newRegionMeta(11, 24, 8, 5, 4, 1, false, []byte(""), []byte("b")))
storeMeta0.RegionMetas = append(storeMeta0.RegionMetas, newRegionMeta(12, 34, 5, 6, 5, 1, false, []byte("b"), []byte("c")))
storeMeta0.RegionMetas = append(storeMeta0.RegionMetas, newRegionMeta(13, 44, 1200, 7, 6, 1, false, []byte("c"), []byte("")))
t.mockRecovery.StoreMetas[0] = storeMeta0
storeMeta1 := restore.NewStoreMeta(2)
storeMeta1.RegionMetas = append(storeMeta1.RegionMetas, newRegionMeta(11, 25, 7, 6, 4, 1, false, []byte(""), []byte("b")))
storeMeta1.RegionMetas = append(storeMeta1.RegionMetas, newRegionMeta(12, 35, 5, 6, 5, 1, false, []byte("b"), []byte("c")))
storeMeta1.RegionMetas = append(storeMeta1.RegionMetas, newRegionMeta(13, 45, 1200, 6, 6, 1, false, []byte("c"), []byte("")))
t.mockRecovery.StoreMetas[1] = storeMeta1
storeMeta2 := restore.NewStoreMeta(3)
storeMeta2.RegionMetas = append(storeMeta2.RegionMetas, newRegionMeta(11, 26, 7, 5, 4, 1, false, []byte(""), []byte("b")))
storeMeta2.RegionMetas = append(storeMeta2.RegionMetas, newRegionMeta(12, 36, 5, 6, 6, 1, false, []byte("b"), []byte("c")))
storeMeta2.RegionMetas = append(storeMeta2.RegionMetas, newRegionMeta(13, maxAllocateId, 1200, 6, 6, 1, false, []byte("c"), []byte("")))
t.mockRecovery.StoreMetas[2] = storeMeta2
}
func (t *testData) cleanUp() {
t.mockPDClient.Close()
}
func createStores() []*metapb.Store {
return []*metapb.Store{
{Id: 1, Labels: []*metapb.StoreLabel{{Key: "engine", Value: "tikv"}}},
{Id: 2, Labels: []*metapb.StoreLabel{{Key: "else", Value: "tikv"}, {Key: "engine", Value: "tiflash"}}},
{Id: 3, Labels: []*metapb.StoreLabel{{Key: "else", Value: "tiflash"}, {Key: "engine", Value: "tikv"}}},
}
}
func createDataSuite(t *testing.T) *testData {
tikvClient, _, pdClient, err := testutils.NewMockTiKV("", nil)
require.NoError(t, err)
mockGlue := &gluetidb.MockGlue{}
ctx, cancel := context.WithCancel(context.Background())
mockMgr := &conn.Mgr{PdController: &pdutil.PdController{}}
mockMgr.SetPDClient(pdClient)
mockMgr.SetHTTP([]string{"test"}, nil)
fakeProgress := mockGlue.StartProgress(ctx, "Restore Data", int64(numOnlineStore*3), false)
var recovery = restore.NewRecovery(createStores(), mockMgr, fakeProgress, 64)
tikvClient.Close()
return &testData{
ctx: ctx,
cancel: cancel,
mockPDClient: pdClient,
mockRecovery: recovery,
}
}
func TestGetTotalRegions(t *testing.T) {
testData := createDataSuite(t)
testData.generateRegionMeta()
totalRegion := testData.mockRecovery.GetTotalRegions()
require.Equal(t, totalRegion, 3)
testData.cleanUp()
}
func TestMakeRecoveryPlan(t *testing.T) {
testData := createDataSuite(t)
testData.generateRegionMeta()
err := testData.mockRecovery.MakeRecoveryPlan()
require.NoError(t, err)
require.Equal(t, testData.mockRecovery.MaxAllocID, uint64(maxAllocateId))
require.Equal(t, len(testData.mockRecovery.RecoveryPlan), 2)
testData.cleanUp()
}
|
package main
import "fmt"
func sendData(sendch chan<- int) {
sendch<- 10
}
func main() {
cha1 := make(chan int)
go sendData(cha1)
//cha1<-10
fmt.Println(<-cha1)
}
|
package sessions
import (
"time"
"github.com/rs/xid"
)
// Session abstracts a session made of a last seen record and an uid
type Session struct {
lastSeen time.Time
uid string
}
// sessionMap abstracts a hash table of multiple Session sorted by their flow data
type sessionMap map[string]*Session
var (
// SessionMap is the global sessions hash table
SessionMap = make(sessionMap)
)
func (m sessionMap) GetUID(flow string) string {
if session, ok := m[flow]; ok {
return session.uid
}
return m.add(flow)
}
func (m *sessionMap) add(flow string) string {
//var ts = strconv.FormatInt(time.Now().UnixNano(), 10)
var ts = xid.New().String()
(*m)[flow] = &Session{
uid: ts,
lastSeen: time.Now(),
}
return ts
}
// FlushOlderThan cleans the session mapping of sessions not seen since the given deadline
func (m *sessionMap) FlushOlderThan(deadline time.Time) {
for flow, session := range *m {
if session.lastSeen.Before(deadline) {
delete(*m, flow)
}
}
}
// FlushAll removes all sessions from the session mapping
func (m *sessionMap) FlushAll() {
for flow := range *m {
delete(*m, flow)
}
}
|
package main
import (
"log"
"github.com/pressly/goose"
"github.com/snapiz/go-vue-starter/packages/cgo"
"github.com/spf13/cobra"
)
func init() {
root.AddCommand(&cobra.Command{
Use: "db:down",
Short: "Rollback database schema",
Run: func(cmd *cobra.Command, args []string) {
db, err := cgo.NewDB("", false)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := goose.Down(db, "migrations"); err != nil {
log.Fatal(err)
}
},
})
}
|
package mongo
import (
// Standard Library Imports
"testing"
// Internal Imports
"github.com/matthewhartstonge/storage"
)
func TestCacheMongoManager_ImplementsStorageConfigurer(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.Configurer); !ok {
t.Error("CacheManager does not implement interface storage.Configurer")
}
}
func TestCacheMongoManager_ImplementsStorageCacheStorer(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.CacheStorer); !ok {
t.Error("CacheManager does not implement interface storage.CacheStorer")
}
}
func TestCacheMongoManager_ImplementsStorageCacheManager(t *testing.T) {
c := &CacheManager{}
var i interface{} = c
if _, ok := i.(storage.CacheManager); !ok {
t.Error("CacheManager does not implement interface storage.CacheManager")
}
}
|
package main
import (
"fmt"
"sync"
)
// Moves creates the moves that one person can make from one brick to another
func moves() (m sync.Map) {
var fromKey string
var toMoves []string
for x := 10; x <= 50; x++ {
for y := 10; y <= 50; y++ {
for z := 10; z <= 50; z++ {
fromKey = fmt.Sprintf("%v_%v_%v", x, y, z)
toMoves = nil
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x+1, y, z))
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x-1, y, z))
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x, y+1, z))
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x, y-1, z))
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x, y, z+1))
toMoves = append(toMoves, fmt.Sprintf("%v_%v_%v", x, y, z-1))
m.Store(fromKey, toMoves)
}
}
}
return
}
|
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func part2() {
// Assumes current working directory is `day-01/`!
fileContent, err := ioutil.ReadFile("puzzle-input.txt")
if err != nil {
fmt.Println(err)
}
frequencyChangeList := strings.Split(string(fileContent), "\n")
var resultingFrequency float64
historicalFrequencyList := make(map[float64]bool)
resultingFrequency = determineRepeatedFrequency(resultingFrequency, frequencyChangeList, historicalFrequencyList)
fmt.Printf("DUPE: %v\n", resultingFrequency)
fmt.Printf("TIMES RUN: %v\n", recurseCounter)
}
func determineRepeatedFrequency(currentFrequency float64, frequencyChangeList []string, historicalFrequencyList map[float64]bool) float64 {
var duplicatedFrequency float64
for _, frequencyChangeString := range frequencyChangeList {
if frequencyChangeString == "" {
continue
}
frequencyChange, err := strconv.ParseFloat(frequencyChangeString, 64)
if err != nil {
fmt.Println(err)
}
currentFrequency += frequencyChange
if _, ok := historicalFrequencyList[currentFrequency]; !ok {
historicalFrequencyList[currentFrequency] = true
} else {
duplicatedFrequency = currentFrequency
break
}
}
if duplicatedFrequency == 0.0 {
currentFrequency = determineRepeatedFrequency(currentFrequency, frequencyChangeList, historicalFrequencyList)
}
recurseCounter++
return currentFrequency
}
|
package controller
import (
"github.com/labstack/echo"
"net/http"
)
func Aboutus(c echo.Context) error {
//session, _ := session.Get("session", c)
//authKey := session.Values["authKey"]
//if authKey == nil {
// return c.Redirect(http.StatusMovedPermanently, "/login")
//}
//session.Save(c.Request(), c.Response())
//return c.Redirect(http.StatusMovedPermanently, "/login")
return c.Render(http.StatusOK, "body.html", map[string]interface{}{
"title": "ABOUT US",
"topMenu": "aboutus",
"Content": "aboutus.html"})
}
|
package main
import "fmt"
func f( x float64) float64{
sum := 0.0
for i := 0; i < int(x)/10; i++{
sum += float64(i)
}
return sum
}
func trap( a float64, b float64, h float64) float64{
return (f(a)+f(b))*h
}
func main(){
var sum float64 = 0
n := 200.0
h := 1000000000.0/n
var mesh [201]float64
for i := 0; i <= int(n); i++{
mesh[i] = h*float64(i)
}
for i := 0; i < int(n); i++{
sum += trap(mesh[i],mesh[i+1],h)
}
fmt.Println(sum)
}
|
package kafka
import (
"github.com/Shopify/sarama"
"github.com/astaxie/beego/logs"
"log"
"logCollector/config"
"logCollector/elasticsearch"
"sync"
)
var consumer sarama.Consumer
func InitKafka(){
var err error
consumer, err = sarama.NewConsumer(config.KafkaAddressList, nil)
if err != nil {
log.Fatal(err)
}
go createTopicTask()
}
func createTopicTask() {
var wg sync.WaitGroup
partitionList, err := consumer.Partitions("log")
if err != nil {
logs.Error("get topic: [%s] partitions failed, err: %s", "log", err)
}
for partition := range partitionList {
pc, err := consumer.ConsumePartition("log", int32(partition), sarama.OffsetNewest)
if err != nil {
logs.Warn("topic: [%s] start consumer partition failed, err: %s", "log", err)
continue
}
wg.Add(1)
go func(sarama.PartitionConsumer) {
for msg := range pc.Messages() {
elasticsearch.ESChan <- string(msg.Value)
}
defer pc.AsyncClose()
wg.Done()
}(pc)
}
wg.Wait()
}
|
package 二分
import "sort"
// ---------------------------- 方法1: 暴力版 ----------------------------
const INF = 1000000000
func findTheDistanceValue(arr1 []int, arr2 []int, d int) int {
return getDistanceValueOfFirstArrayToSecondArray(arr1, arr2, d)
}
func getDistanceValueOfFirstArrayToSecondArray(firstArr, secondArr []int, d int) int {
distanceValue := 0
for i := 0; i < len(firstArr); i++ {
if getMinDistance(secondArr, firstArr[i]) > d {
distanceValue++
}
}
return distanceValue
}
func getMinDistance(arr []int, ref int) int {
minDistance := INF
for i := 0; i < len(arr); i++ {
minDistance = min(minDistance, abs(arr[i]-ref))
}
return minDistance
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
// ---------------------------- 方法2: 二分查找版 ----------------------------
func findTheDistanceValue(arr1 []int, arr2 []int, d int) int {
return getDistanceValueOfFirstArrayToSecondArray(arr1, arr2, d)
}
func getDistanceValueOfFirstArrayToSecondArray(firstArr, secondArr []int, d int) int {
distanceValue := 0
sort.Ints(secondArr)
for i := 0; i < len(firstArr); i++ {
indexOfLastLessOrEqual := getIndexOfLastLessOrEqual(secondArr, firstArr[i])
if indexOfLastLessOrEqual != -1 && getDistance(firstArr[i], secondArr[indexOfLastLessOrEqual]) <= d {
continue
}
indexOfFirstGreaterOrEqual := getIndexOfFirstGreaterOrEqual(secondArr, firstArr[i])
if indexOfFirstGreaterOrEqual != len(secondArr) && getDistance(firstArr[i], secondArr[indexOfFirstGreaterOrEqual]) <= d {
continue
}
distanceValue++
}
return distanceValue
}
func getDistance(a, b int) int {
return abs(a - b)
}
func getIndexOfLastLessOrEqual(arr []int, ref int) int {
return getIndexOfFirstGreater(arr, ref) - 1
}
func getIndexOfFirstGreaterOrEqual(arr []int, ref int) int {
left, right := 0, len(arr)-1
for left <= right {
mid := left + (right-left)/2
if arr[mid] >= ref {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
func getIndexOfFirstGreater(arr []int, ref int) int {
left, right := 0, len(arr)-1
for left <= right {
mid := left + (right-left)/2
if arr[mid] > ref {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
/*
题目链接: https://leetcode-cn.com/problems/find-the-distance-value-between-two-arrays/submissions/
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.