text
stringlengths 11
4.05M
|
|---|
package api
import (
"fmt"
"github.com/johanhenriksson/edetalj-backend/views"
)
type ViewService struct {
}
type UserViewService struct {
ViewService
Template *views.Template
}
func (srv ViewService) Path() string {
return "/{name}"
}
func (srv ViewService) Routes() Routes {
return Routes {
Route {
Name: "Get",
Method: "GET",
Pattern: "",
Handler: srv.Route,
},
}
}
func (srv ViewService) Route(p RouteArgs) {
fmt.Println("View name:", p.Vars["name"])
}
|
package mempool
import (
"testing"
"github.com/meshplus/bitxhub-kit/types"
"github.com/meshplus/bitxhub-model/pb"
"github.com/stretchr/testify/assert"
)
func TestStorage(t *testing.T) {
ast := assert.New(t)
mempool, _ := mockMempoolImpl()
defer cleanTestData()
txList := make([]*pb.Transaction, 0)
txHashList := make([]types.Hash, 0)
txHash1 := newHash("txHash1")
tx1 := &pb.Transaction{Nonce: uint64(1), TransactionHash: txHash1}
txHash2 := newHash("txHash2")
tx2 := &pb.Transaction{Nonce: uint64(1), TransactionHash: txHash2}
txList = append(txList, tx1, tx2)
txHashList = append(txHashList, *txHash1, *txHash1)
mempool.batchStore(txList)
tx, ok := mempool.load(txHash1.Bytes())
ast.Equal(true, ok)
ast.Equal(uint64(1), tx.Nonce)
mempool.batchDelete(txHashList)
tx, ok = mempool.load(txHash1.Bytes())
ast.Equal(false, ok)
ast.Nil(tx)
}
|
// +build !test
package util
func init() {
loadConfig()
}
|
package ch1
import (
"bytes"
"testing"
)
func TestEchoOSArgs(t *testing.T) {
buf := bytes.NewBuffer(nil)
if err := EchoOSArgs(buf, "\n"); err != nil {
t.Error(err)
}
t.Logf("success,os.Args is\n%s", buf.String())
}
|
package main
import "gopkg.in/mgo.v2/bson"
type Task struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Name string `json:"name"`
IsCompleted bool `json:"is_completed"`
}
type Tasks []Task
|
package actions
import (
"crypto/md5"
"encoding/hex"
"errors"
"strings"
"time"
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/factories"
"github.com/barrydev/api-3h-shop/src/helpers"
"github.com/barrydev/api-3h-shop/src/model"
"github.com/dgrijalva/jwt-go"
)
func AuthenticateAdmin(body *model.BodyUser) (*factories.ResponseAccessToken, error) {
queryString := ""
var args []interface{}
var where []string
if body.Email == nil {
return nil, errors.New("user's email is required")
} else {
where = append(where, " email=?")
args = append(args, body.Email)
}
if body.Password == nil {
return nil, errors.New("user's password is required")
}
if len(where) > 0 {
queryString += "WHERE" + strings.Join(where, " AND") + "\n"
} else {
return nil, errors.New("invalid body")
}
foundUser, err := factories.FindOneUser(&connect.QueryMySQL{
QueryString: queryString,
Args: args,
})
if err != nil {
return nil, err
}
if foundUser == nil {
return nil, errors.New("user not found")
}
if *foundUser.Role == 11 {
return nil, errors.New("you cannot access this resource")
}
hashPassword := md5.Sum([]byte(*body.Password))
if hex.EncodeToString(hashPassword[:]) != *foundUser.RawPassword {
return nil, errors.New("wrong password")
}
claims := factories.AccessTokenClaims{
*foundUser.Id,
*foundUser.Role,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 24 * 7).Unix(),
},
}
accessToken, err := helpers.GenerateJwtToken(claims)
if err != nil {
return nil, err
}
return &factories.ResponseAccessToken{
User: foundUser,
AccessToken: &accessToken,
}, nil
}
|
package websocket_service
import (
"ms/sun_old/base"
"ms/sun/shared/helper"
"ms/sun/servises/chat_service"
"ms/sun/shared/x"
"time"
)
var syncChatPipePusher = make(chan *x.ChatSync, 100000)
var lastSyncLoaded = helper.NextRowsSeqId()
func syncChaFetcher() {
defer helper.JustRecover()
for {
time.Sleep(time.Millisecond * 50)
syncs, err := x.NewChatSync_Selector().SyncId_GE(lastSyncLoaded).OrderBy_SyncId_Asc().GetRows(base.DB)
if err == nil || len(syncs) == 0 {
continue
}
lastSyncLoaded = syncs[0].SyncId
for _, sync := range syncs {
syncChatPipePusher <- sync
}
}
}
//can causes panic
func syncChatPusherToDevicesFramer() {
defer helper.JustRecover()
const siz = 100000
arr := make([]*x.ChatSync, 0, siz)
cnt := 0
ticker := time.NewTicker(10 * time.Millisecond)
for {
select {
case m := <-syncChatPipePusher:
arr = append(arr, m)
case <-ticker.C:
if len(arr) > 0 {
cnt++
logChatSync.Printf("batch of syncChatPusherToDevicesFramer - cnt:%d - len:%d \n", cnt, len(arr))
pre := arr
arr = make([]*x.ChatSync, 0, siz)
go func(syncs []*x.ChatSync) {
defer helper.JustRecover()
mp := make(map[int][]*x.ChatSync)
for _, sync := range syncs {
mp[sync.ToUserId] = append(mp[sync.ToUserId], sync)
}
for uid, syncs2 := range mp {
if AllPipesMap.IsPipeOpen(uid) {
up := chat_service.ToUpdates(uid, syncs2)
cmd := newPB_CommandToClient_WithData("Updates", up)
AllPipesMap.SendToUser(uid, cmd)
}
}
}(pre)
}
}
}
}
|
package main
import (
"context"
"crypto/sha512"
"encoding/hex"
"errors"
"flag"
"fmt"
"github.com/milaniez/teleportselftest/protojob"
"github.com/milaniez/teleportselftest/util/mytls"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/reflection"
"log"
"math/rand"
"net"
"time"
)
type WorkerServer struct {
protojob.UnimplementedWorkerServer
}
func GetCertFPFromCtx(ctx context.Context) *[]string {
ret := make([]string, 0, 0)
p, ok := peer.FromContext(ctx)
if !ok {
return &ret
}
tlsInfo := p.AuthInfo.(credentials.TLSInfo)
ret = make([]string, 0, len(tlsInfo.State.VerifiedChains))
for _, chain := range tlsInfo.State.VerifiedChains {
sha512Val := sha512.Sum512(chain[0].Raw)
ret = append(ret, hex.EncodeToString(sha512Val[:]))
}
return &ret
}
func (w WorkerServer) Start(ctx context.Context, cmd *protojob.Cmd) (*protojob.JobID, error) {
// TODO replace with the real implementation
fp := GetCertFPFromCtx(ctx)
fmt.Printf("(%v), Got Start request: name = %v, args = %v\n", *fp, cmd.Name, cmd.Args)
return &protojob.JobID{Id: rand.Uint64()}, nil
}
func (w WorkerServer) GetStatus(ctx context.Context, id *protojob.JobID) (*protojob.Status, error) {
// TODO: replace with the real implementation
fp := GetCertFPFromCtx(ctx)
fmt.Printf("(%v), Got GetStatus request: id = %v\n", *fp, id.Id)
return &protojob.Status{RunStatus: protojob.Status_RUN_STATUS_FINISHED, ExitStatus: protojob.Status_EXIT_STATUS_OK}, nil
}
func (w WorkerServer) GetJobIDs(ctx context.Context, _ *protojob.Empty) (*protojob.JobIDList, error) {
// TODO: replace with the real implementation
fp := GetCertFPFromCtx(ctx)
fmt.Printf("(%v), Got GetJobIDs request\n", *fp)
jobIDCnt := rand.Intn(10) + 3
ret := protojob.JobIDList{
Id: make([]uint64, jobIDCnt, jobIDCnt),
}
for i := range ret.Id {
ret.Id[i] = rand.Uint64()
}
return &ret, nil
}
func (w WorkerServer) GetResult(ctx context.Context, id *protojob.JobID) (*protojob.Result, error) {
// TODO: replace with the real implementation
fp := GetCertFPFromCtx(ctx)
fmt.Printf("(%v), Got GetResult request: id = %v\n", *fp, id.Id)
return &protojob.Result{Finished: true, Output: "Done!!"}, nil
}
func (w WorkerServer) StreamOutput(id *protojob.JobID, stream protojob.Worker_StreamOutputServer) error {
// TODO: replace with the real implementation
fp := GetCertFPFromCtx(stream.Context())
fmt.Printf("(%v), Got StreamOutput request: id = %v\n", *fp, id.Id)
outputCnt := rand.Intn(20)
for i := 0; i < outputCnt; i++ {
if err := stream.Send(&protojob.Output{Output: "Something is done!"}); err == nil {
return errors.New("issue in sending to stream")
}
}
return nil
}
func WorkerServerNew() WorkerServer {
return WorkerServer{}
}
func Intercept(
ctx context.Context,
req interface{},
_ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
fmt.Println("called")
if p, ok := peer.FromContext(ctx); ok {
if tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo); ok {
for _, item := range tlsInfo.State.PeerCertificates {
fmt.Println("request certificate subject:", item.Subject)
}
}
}
return handler(ctx, req)
}
func main() {
var (
certFile = flag.String(
"cert",
"/home/mehdi/mzzcerts/localcerts/server.crt",
"Server certificate public key file",
)
keyFile = flag.String(
"key",
"/home/mehdi/mzzcerts/localkeys/server.key",
"Server certificate secret key file",
)
caDir = flag.String(
"cadir",
"/home/mehdi/mzzcerts/cacerts/",
"Certificate Authority directory",
)
addr = flag.String(
"address",
"localhost:8443",
"Server address",
)
)
flag.Parse()
log.SetFlags(log.Llongfile | log.LstdFlags)
rand.Seed(time.Now().UTC().UnixNano())
listener, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
creds, err := mytls.GetTLSCreds(*certFile, *keyFile, *caDir, true)
if err != nil {
log.Fatalf("issue getting creds: %v", err)
}
serverOpt := grpc.Creds(creds)
grpcServer := grpc.NewServer(serverOpt, grpc.UnaryInterceptor(Intercept))
protojob.RegisterWorkerServer(grpcServer, WorkerServerNew())
reflection.Register(grpcServer)
log.Fatal(grpcServer.Serve(listener))
}
|
package pie
import (
"golang.org/x/exp/constraints"
"math/rand"
)
// Random returns a random element by your rand.Source, or zero.
func Random[T constraints.Integer | constraints.Float](ss []T, source rand.Source) T {
n := len(ss)
// Avoid the extra allocation.
if n < 1 {
return 0
}
if n < 2 {
return ss[0]
}
rnd := rand.New(source)
i := rnd.Intn(n)
return ss[i]
}
|
package trident
import (
pf "trident.li/pitchfork/lib"
)
type TriGroupMember interface {
pf.PfGroupMember
GetVouchesFor() int
GetVouchesBy() int
GetVouchesForMe() int
GetVouchesByMe() int
}
type TriGroupMemberS struct {
pf.PfGroupMember
VouchesFor int
VouchesBy int
VouchesForMe int
VouchesByMe int
}
func (o *TriGroupMemberS) GetVouchesFor() int {
return o.VouchesFor
}
func (o *TriGroupMemberS) GetVouchesBy() int {
return o.VouchesBy
}
func (o *TriGroupMemberS) GetVouchesForMe() int {
return o.VouchesForMe
}
func (o *TriGroupMemberS) GetVouchesByMe() int {
return o.VouchesByMe
}
func NewTriGroupMember() TriGroupMember {
pfg := pf.NewPfGroupMember()
return &TriGroupMemberS{PfGroupMember: pfg}
}
|
package cli
import (
"context"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/google/uuid"
"github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb"
"github.com/moby/buildkit/solver/pb"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
log "github.com/sirupsen/logrus"
spdxjson "github.com/spdx/tools-golang/json"
spdxcommon "github.com/spdx/tools-golang/spdx/common"
spdx "github.com/spdx/tools-golang/spdx/v2_3"
spdxtv "github.com/spdx/tools-golang/tvsaver"
"github.com/spf13/cobra"
)
const (
defaultNamespace = "https://github.com/lf-edge/eve/spdx"
creator = "https://github.com/lf-edge/eve/tools/dockerfile-add-scanner"
)
func scanCmd() *cobra.Command {
var (
outputFormat string
namespace string
arch string
)
cmd := &cobra.Command{
Use: "scan",
Short: "Scan Dockerfiles for ADD commands",
Long: `Scan Dockerfiles for ADD commands and print the URLs to stdout.
Can scan multiple at once. Output can be in list, spdx or spdx-json formats.
`,
Example: `dockerfile-add-scanner scan <dockerfile1> <dockerfile2> ... <dockerfileN>`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var allUrls []*url.URL
for _, dockerfile := range args {
log.Debugf("Processing %s", dockerfile)
urls, err := scan(dockerfile, arch)
if err != nil {
log.Fatalf("Error scanning %s: %v", dockerfile, err)
}
allUrls = append(allUrls, urls...)
}
switch outputFormat {
case "list":
for _, u := range allUrls {
fmt.Println(u.String())
}
case "spdx":
sbom, err := buildSbom(allUrls, namespace, creator)
if err != nil {
return err
}
return spdxtv.Save2_3(sbom, os.Stdout)
case "spdx-json":
sbom, err := buildSbom(allUrls, namespace, creator)
if err != nil {
return err
}
return spdxjson.Save2_3(sbom, os.Stdout)
default:
return fmt.Errorf("unknown output format %s", outputFormat)
}
return nil
},
}
cmd.Flags().StringVar(&outputFormat, "format", "list", "Output format: list, spdx, spdx-json")
cmd.Flags().StringVar(&namespace, "namespace", defaultNamespace, "document namespace to use for spdx output formats, will have a UUID appended")
cmd.Flags().StringVar(&arch, "arch", runtime.GOARCH, "architecture for which it would be built, defaults to current platform")
return cmd
}
func scan(dockerfile, arch string) ([]*url.URL, error) {
var urls []*url.URL
f, err := os.Open(dockerfile)
if err != nil {
return nil, fmt.Errorf("error opening dockerfile %s: %v", dockerfile, err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("error reading dockerfile at %s: %v", dockerfile, err)
}
ctx := context.TODO()
state, _, _, err := dockerfile2llb.Dockerfile2LLB(ctx, data, dockerfile2llb.ConvertOpt{
TargetPlatform: &ocispecs.Platform{Architecture: arch, OS: "linux"},
})
if err != nil {
return nil, err
}
def, err := state.Marshal(ctx)
if err != nil {
return nil, err
}
for _, d := range def.Def {
var op pb.Op
if err := op.Unmarshal(d); err != nil {
return nil, err
}
src := op.GetSource()
if src == nil {
continue
}
identifier := src.GetIdentifier()
if identifier == "" {
continue
}
parsed, err := url.Parse(identifier)
if err != nil {
return nil, fmt.Errorf("unable to parse url %s: %v", identifier, err)
}
switch parsed.Scheme {
case "http", "https", "ftp", "ftps", "git":
urls = append(urls, parsed)
}
}
return urls, nil
}
func buildSbom(urls []*url.URL, namespace, creator string) (*spdx.Document, error) {
var packages []*spdx.Package
for _, u := range urls {
name := filepath.Base(u.Path)
pkg := &spdx.Package{
PackageName: name,
PackageSPDXIdentifier: spdxcommon.MakeDocElementID("Package", name).ElementRefID,
PackageDownloadLocation: u.String(),
}
// could we get a version from the URL?
if (u.Scheme == "git" || strings.HasSuffix(name, ".git")) && u.Fragment != "" {
pkg.PackageVersion = u.Fragment
}
packages = append(packages, pkg)
}
return &spdx.Document{
SPDXVersion: "SPDX-2.3",
DataLicense: "CC0-1.0",
SPDXIdentifier: "DOCUMENT",
DocumentName: "dockerfile",
DocumentNamespace: fmt.Sprintf("%s-%s", namespace, uuid.New()),
CreationInfo: &spdx.CreationInfo{
Created: time.Now().UTC().Format(time.RFC3339),
Creators: []spdxcommon.Creator{
{Creator: creator, CreatorType: "Tool"},
},
},
Packages: packages,
}, nil
}
|
package grammar
import (
// "fmt"
"strings"
// "golang.org/x/tour/wc"
)
// func main() {
// var str string = "I am in baidu am am"
// var re map[string]int = WordCount(str)
// fmt.Println(re)
// }
func WordCount(s string) map[string]int {
var strs []string = strings.Fields(s)
var result map[string]int = make(map[string]int)
for _, v := range strs {
_, ok := result[v]
if ok == true {
result[v]++
} else {
result[v] = 1
}
}
return result
}
|
package gotoml
import (
"fmt"
"testing"
"time"
)
func TestStripLineComment(c *testing.T) {
out := StripLineComment("should remain # should strip")
expected := "should remain "
if out != expected {
fmt.Println(out)
c.Error("should strip from # to end of string")
}
out = StripLineComment("key = \"\\\"contains\\\" # and \\\" should remain\" # should strip")
expected = "key = \"\\\"contains\\\" # and \\\" should remain\" "
if out != expected {
fmt.Println(out)
c.Error("should not strip # from within strings")
}
}
func TestParseKeyValue(c *testing.T) {
tomlMap := TOMLMap{"foo": "bar"}
ParseKeyValue("stringkey = \"string value\"", tomlMap)
if val, err := tomlMap.GetString("stringkey"); val != "string value" || err != nil {
c.Error("should parse string values")
}
ParseKeyValue("boolkey = true", tomlMap)
if val, err := tomlMap.GetBool("boolkey"); val != true || err != nil {
c.Error("should parse bool values")
}
ParseKeyValue("intkey = 123456", tomlMap)
if val, err := tomlMap.GetInt64("intkey"); val != 123456 || err != nil {
c.Error("should parse int values")
}
ParseKeyValue("floatkey = 12.34", tomlMap)
if val, err := tomlMap.GetFloat64("floatkey"); val != 12.34 || err != nil {
c.Error("should parse float values")
}
ParseKeyValue("datekey = 1979-05-27T07:32:00Z", tomlMap)
expectedDate := time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC)
if val, err := tomlMap.GetTime("datekey"); val != expectedDate || err != nil {
c.Error("should parse ISO8601 dates")
}
}
func TestSimpleTOML(c *testing.T) {
out, err := OpenTOML("test-data/simple.toml")
if err != nil {
c.Error("error parsing test-data/simple.toml")
}
if out["title"] != "Simple TOML" {
c.Error("expected title as Simple TOML")
}
}
func TestExampleTOML(c *testing.T) {
out, err := OpenTOML("test-data/example.toml")
if err != nil {
c.Error("error parsing test-data/example.toml")
}
if out["title"] != "TOML Example" {
c.Error("expecting title as TOML Example")
}
if out["owner.name"] != "Tom Preston-Werner" {
c.Error("expecting owner.name as Tom Preston-Werner")
}
expectedDate := time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC)
if val, err := out.GetTime("owner.dob"); val != expectedDate || err != nil {
c.Error("should parse ISO8601 dates")
}
if out["servers.alpha.ip"] != "10.0.0.1" {
c.Error("should parse nested tags")
}
}
func TestExampleHardTOML(c *testing.T) {
out, err := OpenTOML("test-data/hard-example.toml")
if err != nil {
c.Error("error parsing test-data/hard-example.toml")
}
if out["the.test_string"] != "You'll hate me after this - #" {
c.Error("should handle # within strings")
}
}
|
package router
import (
"github.com/google/uuid"
"io/ioutil"
"log"
"mime"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
const (
CONNECT = "CONNECT"
DELETE = "DELETE"
GET = "GET"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
PATCH = "PATCH"
POST = "POST"
PUT = "PUT"
TRACE = "TRACE"
ANY = "*"
)
const (
DEFAULT = "DEFAULT"
)
const (
BIND = "BIND"
ROOT = "ROOT"
INDEX = "INDEX"
)
type Handler func(http.ResponseWriter, *http.Request, *Context)
type Interceptor interface {
PreHandleFunc(http.ResponseWriter, *http.Request, *Context) bool
PostHandleFunc(http.ResponseWriter, *http.Request, *Context)
}
type Context struct {
Data map[string]interface{}
}
type Resolver func(http.ResponseWriter, *http.Request, error)
type PathPattern struct {
path string
regex *regexp.Regexp
params map[int]string
}
type HandlerAdapter struct {
pathPattern *PathPattern
method string
handler Handler
bind interface{}
}
type InterceptorAdapter struct {
pathPattern *PathPattern
ignorePatterns []*PathPattern
interceptor Interceptor
}
type ResolverAdapter struct {
error string
resolver Resolver
}
type Router struct {
addr string
tag string
listener net.Listener
logger *log.Logger
handlerAdapters []*HandlerAdapter
interceptorAdapters []*InterceptorAdapter
resolverAdapters map[string]*ResolverAdapter
}
func NewRouter() *Router {
return &Router{
addr: ":8888",
tag: "varconf",
logger: log.New(os.Stdout, "", log.Ldate|log.Ltime),
handlerAdapters: make([]*HandlerAdapter, 0),
interceptorAdapters: make([]*InterceptorAdapter, 0),
resolverAdapters: make(map[string]*ResolverAdapter),
}
}
func (_self *Router) Run() error {
listener, err := net.Listen("tcp", _self.addr)
if err != nil {
_self.logger.Fatal("Listen: ", err)
return err
}
_self.listener = listener
_self.logger.Println("Listening on http://" + _self.addr)
err = http.Serve(_self.listener, _self)
if err != nil {
_self.logger.Fatal("ListenAndServe: ", err)
}
return err
}
func (_self *Router) RunTLS(certFile, keyFile string) error {
listener, err := net.Listen("tcp", _self.addr)
if err != nil {
_self.logger.Fatal("Listen: ", err)
return err
}
_self.listener = listener
_self.logger.Println("Listening on https://" + _self.addr)
err = http.ServeTLS(_self.listener, _self, certFile, keyFile)
if err != nil {
_self.logger.Fatal("ListenAndServe: ", err)
}
return err
}
func (_self *Router) Stop() error {
if _self.listener != nil {
return _self.listener.Close()
}
return nil
}
func (_self *Router) SetAddress(args ...interface{}) {
host := "0.0.0.0"
port := "8888"
if len(args) == 1 {
switch arg := args[0].(type) {
case string:
arrays := strings.Split(args[0].(string), ":")
if len(arrays) == 1 {
host = arrays[0]
} else if len(arrays) >= 2 {
port = arrays[1]
}
case int:
port = strconv.Itoa(arg)
}
} else if len(args) >= 2 {
if arg, ok := args[0].(string); ok {
host = arg
}
if arg, ok := args[1].(int); ok {
port = strconv.Itoa(arg)
}
}
_self.addr = host + ":" + port
}
func (_self *Router) SetTag(tag string) {
_self.tag = tag
}
func (_self *Router) SetLogger(logger *log.Logger) {
_self.logger = logger
}
func (_self *Router) Connect(path string, handlerFunc Handler) {
_self.AddRoute(CONNECT, path, handlerFunc)
}
func (_self *Router) Delete(path string, handlerFunc Handler) {
_self.AddRoute(DELETE, path, handlerFunc)
}
func (_self *Router) Get(path string, handlerFunc Handler) {
_self.AddRoute(GET, path, handlerFunc)
}
func (_self *Router) Head(path string, handlerFunc Handler) {
_self.AddRoute(HEAD, path, handlerFunc)
}
func (_self *Router) Options(path string, handlerFunc Handler) {
_self.AddRoute(OPTIONS, path, handlerFunc)
}
func (_self *Router) Patch(path string, handlerFunc Handler) {
_self.AddRoute(PATCH, path, handlerFunc)
}
func (_self *Router) Post(path string, handlerFunc Handler) {
_self.AddRoute(POST, path, handlerFunc)
}
func (_self *Router) Put(path string, handlerFunc Handler) {
_self.AddRoute(PUT, path, handlerFunc)
}
func (_self *Router) Trace(path string, handlerFunc Handler) {
_self.AddRoute(TRACE, path, handlerFunc)
}
func (_self *Router) Any(path string, handlerFunc Handler) {
_self.AddRoute(ANY, path, handlerFunc)
}
func (_self *Router) Static(path, root, index string) {
// parse to absolute path
if strings.HasPrefix(root, "./") || strings.HasPrefix(root, "../") {
ep, err := os.Executable()
if err != nil {
panic(err)
}
root = filepath.Join(filepath.Dir(ep), root)
}
// init bind data
bind := make(map[string]interface{})
bind[ROOT] = root
bind[INDEX] = index
// parse pathPattern
pathPattern, err := _self.parsePattern(path)
if err != nil {
return
}
// add route
adapter := &HandlerAdapter{}
adapter.pathPattern = pathPattern
adapter.method = GET
adapter.handler = _self.serveFile
adapter.bind = bind
_self.handlerAdapters = append(_self.handlerAdapters, adapter)
}
func (_self *Router) AddRoute(method, path string, handlerFunc Handler) {
// parse pathPattern
pathPattern, err := _self.parsePattern(path)
if err != nil {
return
}
// add route
adapter := &HandlerAdapter{}
adapter.pathPattern = pathPattern
adapter.method = method
adapter.handler = handlerFunc
adapter.bind = nil
_self.handlerAdapters = append(_self.handlerAdapters, adapter)
}
func (_self *Router) AddFilter(path string, ignores []string, interceptor Interceptor) {
// parse pathPattern
pathPattern, err := _self.parsePattern(path)
if err != nil {
return
}
// parse ignores
ignorePatterns := make([]*PathPattern, 0)
for _, ignore := range ignores {
ignorePattern, err := _self.parsePattern(ignore)
if err != nil {
return
}
ignorePatterns = append(ignorePatterns, ignorePattern)
}
adapter := &InterceptorAdapter{}
adapter.interceptor = interceptor
adapter.pathPattern = pathPattern
adapter.ignorePatterns = ignorePatterns
_self.interceptorAdapters = append(_self.interceptorAdapters, adapter)
}
func (_self *Router) AddResolver(err error, resolver Resolver) {
// add route
adapter := &ResolverAdapter{}
adapter.resolver = resolver
if err == nil {
adapter.error = DEFAULT
} else {
adapter.error = reflect.TypeOf(err).String()
}
_self.resolverAdapters[adapter.error] = adapter
}
func (_self *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
requestId := r.Header.Get("Request-Id")
if requestId == "" {
requestId = uuid.New().String()
}
w.Header().Set("Request-Id", requestId)
w.Header().Set("Server", _self.tag)
w.Header().Set("Date", _self.formatTime(time.Now().UTC()))
// parse match adapter
interceptorAdapters := make([]*InterceptorAdapter, 0)
for _, interceptor := range _self.interceptorAdapters {
if _self.matchPattern(r, interceptor.pathPattern) {
isIgnore := false
for _, ignorePattern := range interceptor.ignorePatterns {
if _self.matchPattern(r, ignorePattern) {
isIgnore = true
break
}
}
if !isIgnore {
interceptorAdapters = append(interceptorAdapters, interceptor)
}
}
}
// pre handle the request
c := &Context{Data: make(map[string]interface{})}
for _, adapter := range interceptorAdapters {
if adapter.interceptor != nil {
if !adapter.interceptor.PreHandleFunc(w, r, c) {
return
}
}
}
isFound := false
// serve the request
for _, adapter := range _self.handlerAdapters {
// match the adapter
if adapter.method == ANY || adapter.method == r.Method {
if _self.matchPattern(r, adapter.pathPattern) {
_self.serveRequest(w, r, adapter, c)
isFound = true
break
}
}
}
// not found
if !isFound {
http.NotFound(w, r)
return
}
// post handle the the request
for _, interceptor := range interceptorAdapters {
if interceptor.interceptor != nil {
interceptor.interceptor.PostHandleFunc(w, r, c)
}
}
}
func (_self *Router) parsePattern(path string) (*PathPattern, error) {
// split the url into sections
parts := strings.Split(path, "/")
// find params that start with ":"
// replace with regular expressions
j := 0
params := make(map[int]string)
for i, part := range parts {
if strings.HasPrefix(part, ":") {
expr := "([^/]+)"
if n := strings.Index(part, "("); n != -1 {
expr = part[n:]
part = part[:n]
}
params[j] = part
parts[i] = expr
j++
}
}
// re create the url path, with parameters replaced
path = strings.Join(parts, "/")
// check the pathPattern
regex, err := regexp.Compile(path)
if err != nil {
panic(err)
return nil, err
}
return &PathPattern{path: path, regex: regex, params: params}, nil
}
func (_self *Router) matchPattern(r *http.Request, p *PathPattern) bool {
// path match
regex := p.regex
requestPath := r.URL.Path
if !regex.MatchString(requestPath) {
return false
}
matches := regex.FindStringSubmatch(requestPath)
if len(matches[0]) != len(requestPath) {
return false
}
// match params
params := p.params
values := r.URL.Query()
if len(params) > 0 {
for i, match := range matches[1:] {
values.Add(params[i], match)
}
// add to raw query
r.URL.RawQuery = url.Values(values).Encode()
}
return true
}
func (_self *Router) serveRequest(w http.ResponseWriter, r *http.Request, a *HandlerAdapter, c *Context) {
_self.logger.Println(r.Method, r.RequestURI)
defer func() {
if err := recover(); err != nil {
_self.logger.Println(err)
resolverAdapter := _self.resolverAdapters[reflect.TypeOf(err).String()]
if resolverAdapter == nil {
resolverAdapter = _self.resolverAdapters[DEFAULT]
if resolverAdapter != nil {
e, ok := err.(error)
if ok {
resolverAdapter.resolver(w, r, e)
}
}
}
}
}()
if a.bind != nil {
c.Data[BIND] = a.bind
}
// handle the request
a.handler(w, r, c)
}
func (_self *Router) serveFile(w http.ResponseWriter, r *http.Request, c *Context) {
// check the bind data and type
bind := c.Data[BIND]
if bind == nil {
http.NotFound(w, r)
return
}
bindData, ok := bind.(map[string]interface{})
if !ok {
http.NotFound(w, r)
return
}
root := bindData[ROOT]
rootData, ok := root.(string)
if !ok {
http.NotFound(w, r)
return
}
index := bindData[INDEX]
indexData, ok := index.(string)
if !ok {
http.NotFound(w, r)
return
}
// deal the file path
filePath := _self.joinPath(rootData, r.URL.Path)
if _self.isDirExists(filePath) {
filePath = _self.joinPath(filePath, indexData)
}
// check the file
if !_self.isFileExists(filePath) {
http.NotFound(w, r)
return
}
// serve the file
content, suffix, err := _self.readFile(filePath)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", mime.TypeByExtension(suffix))
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
//w.Header().Set("Cache-Control", "private, immutable, max-age=60")
w.Write(content)
}
func (_self *Router) formatTime(t time.Time) string {
webTime := t.Format(time.RFC1123)
if strings.HasSuffix(webTime, "UTC") {
webTime = webTime[0:len(webTime)-3] + "GMT"
}
return webTime
}
func (_self *Router) joinPath(elem ...string) string {
return filepath.Join(elem...)
}
func (_self *Router) readFile(filePath string) ([]byte, string, error) {
// serve the file
file, err := os.Open(filePath)
if err != nil {
return nil, "", err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, "", err
}
ext := path.Ext(filePath)
return data, ext, nil
}
func (_self *Router) isDirExists(dirPath string) bool {
info, err := os.Stat(dirPath)
if err != nil {
return false
}
return info.IsDir()
}
func (_self *Router) isFileExists(filePath string) bool {
info, err := os.Stat(filePath)
if err != nil {
return false
}
return !info.IsDir()
}
|
// Copyright (c) 2017 mgIT GmbH. All rights reserved.
// Distributed under the Apache License. See LICENSE for details.
package mqv
import (
"crypto/elliptic"
"io"
"math/big"
"github.com/pkg/errors"
)
var genMask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
// GenerateKey returns a public / private key pair. The private key is
// generated using the given reader, which must return random data.
func GenerateKey(params *elliptic.CurveParams, rand io.Reader) ([]byte, error) {
numBits := params.N.BitLen()
numBytes := (numBits + 7) >> 3
constN := make(SubtleInt, SubtleIntSize(numBits))
constN.SetBytes(params.N.Bytes())
priv := make([]byte, numBytes)
tmp := make(SubtleInt, len(constN))
defer tmp.SetZero()
for {
_, err := io.ReadFull(rand, priv)
if err != nil {
return nil, errors.Wrap(err, "failed to generate random data")
}
// We have to mask off any excess bits in the case that the size of the
// underlying field is not a whole number of bytes.
priv[0] &= genMask[numBits%8]
// This is because, in tests, rand will return all zeros and we don't
// want to get the point at infinity and loop forever.
priv[1] ^= 0x42
tmp.SetBytes(priv)
if tmp.Less(constN) == 1 {
return priv, nil
}
}
}
// BlindKey blinds the original private key (p) with a random blind key (b)
// and returns (p+b, -b) mod n.
func BlindKey(priv []byte, params *elliptic.CurveParams, rand io.Reader) ([]byte, []byte, error) {
numBytes := ((params.N.BitLen() + 7) >> 3)
n := make(SubtleInt, SubtleIntSize(8*numBytes))
n.SetBytes(params.N.Bytes())
if len(priv) > numBytes {
return nil, nil, errors.New("invalid private key")
}
privConst := make(SubtleInt, len(n))
privConst.SetBytes(priv)
blindBytes, err := GenerateKey(params, rand)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to generate blind key")
}
defer WipeBytes(blindBytes)
blind := make(SubtleInt, len(n))
defer blind.SetZero()
blind.SetBytes(blindBytes)
privNew := make(SubtleInt, len(n))
defer privNew.SetZero()
privNew.SetBytes(priv)
privNew.AddMod(privNew, blind, n)
blind.Sub(n, blind)
return privNew.Bytes()[:numBytes], blind.Bytes()[:numBytes], nil
}
// ScalarMultBlind is similar to to the elliptic.ScalarMult function, but it
// does two scalar multiplications with the blinded keys instead and adds the
// afterwards.
func ScalarMultBlind(x *big.Int, y *big.Int, priv []byte, curve elliptic.Curve, rand io.Reader) (*big.Int, *big.Int, error) {
privBlind, privBlindInv, err := BlindKey(priv, curve.Params(), rand)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to blind key")
}
x1, y1 := curve.ScalarMult(x, y, privBlind)
x2, y2 := curve.ScalarMult(x, y, privBlindInv)
x3, y3 := curve.Add(x1, y1, x2, y2)
return x3, y3, nil
}
// WipeInt overrides the internal array of a big.Int with zeros.
func WipeInt(x *big.Int) {
words := x.Bits()
for i := range words {
words[i] = 0
}
}
// WipeBytes overrides the internal byte array with zeros.
func WipeBytes(b []byte) {
for i := range b {
b[i] = 0
}
}
|
/*
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:
a0 + 1/(a1 + 1/(a2 + 1/(a3 + ...)))
Or they can be represented as a list of values: [a0;a1,a2,…,an]
The challenge:
take a base number: a0 and a list of denominator values: [a1,a2,…,an] and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.
Examples:
1–√9: [4;2,1,3,1,2]: 170/39
e: [1;0,1,1,2,1,1]: 19/7
π: [3;7,15,1,292,1]: 104348/33215
ϕ: [1;1,1,1,1,1]: 13/8
Example implementation: (python)
def foo(base, sequence):
numerator = 1
denominator = sequence[-1]
for d in sequence[-2::-1]:
temp = denominator
denominator = d * denominator + numerator
numerator = temp
return numerator + base * denominator, denominator
Winning:
shortest code in bytes: --no builtins that do the entire problem allowed--
*/
package main
import "fmt"
func main() {
test(4, []int{2, 1, 3, 1, 2}, 170, 39)
test(1, []int{0, 1, 1, 2, 1, 1}, 19, 7)
test(3, []int{7, 15, 1, 292, 1}, 104348, 33215)
test(1, []int{1, 1, 1, 1, 1}, 13, 8)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(b int, s []int, rn, rd int) {
n, d := simplify(b, s)
fmt.Println(n, d)
assert(n == rn)
assert(d == rd)
}
func simplify(b int, s []int) (int, int) {
l := len(s)
if l == 0 {
return 0, 0
}
n := 1
d := s[l-1]
for i := l - 2; i >= 0; i-- {
n, d = d, s[i]*d+n
}
return n + b*d, d
}
|
// Copyright 2017 The go-darwin 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 hdiutil
import "strconv"
func boolFlag(name string, b bool) []string {
if b {
return []string{"-" + name}
}
return nil
}
func boolNoFlag(name string, b bool) []string {
if b {
return []string{"-" + name}
}
return []string{"-no" + name}
}
func stringFlag(name, s string) []string {
return []string{"-" + name, s}
}
func stringSliceFlag(name string, s []string) []string {
a := []string{"-" + name}
a = append(a, s...)
return a
}
func intFlag(name string, i int) []string {
return []string{"-" + name, strconv.Itoa(i)}
}
|
package upstream
import (
"encoding/json"
"errors"
"fmt"
"github.com/tal-tech/go-zero/core/logx"
"strings"
"tpay_backend/utils"
)
const (
TopPayQuickSignUrl = "/quickSign"
// 订单是否已支付
TopPayUnpaid = "成功" // 成功
TopPayPaid = "失败" // 失败
TopPayRefund = "已退款" // 已退款
)
type TopPay struct {
upMerchantNo string // 上游账号id
config TopPayConfig
payUrl string
payOrderQueryUrl string
transferUrl string
transferOrderQueryUrl string
queryBalanceUrl string
quickSignUrl string
quickSignConfirmUrl string
quickSignQueryUrl string
quickPayUrl string
quickPayConfirmUrl string
ServiceId string // 接口服务ID
AppId string // appid
}
type TopPayResponse struct {
Code int64 `json:"code"` // 请求返回代码,值见数据字典
Msg string `json:"msg"` // 出错消息,请求处理失败才会出现
Data string `json:"data"` // 业务数据
Sign string `json:"sign"` // 签名
}
func (o *TopPay) Pay(request *PayRequest) (*PayResponse, error) {
return &PayResponse{
PayUrl: o.config.CashierHost + "/1?o=" + request.OrderNo,
}, nil
}
func (o *TopPay) PayOrderQuery(request *PayOrderQueryRequest) (*PayOrderQueryResponse, error) {
panic("implement me")
}
func (o *TopPay) Transfer(req *TransferRequest) (*TransferResponse, error) {
// 1.拼接参数
reqParam := make(map[string]interface{})
reqParam["transactionamount"] = req.Amount / 100.0 // 订单金额
reqParam["businessnumber"] = req.OrderNo // 商户系统内部的订单号
reqParam["backurl"] = req.NotifyUrl // 异步通知地址
reqParam["subject"] = "商品" // 原样返回字段
reqParam["bankname"] = req.BankName // 收款银行名称
reqParam["bankcardname"] = req.BankCardHolderName // 银行卡持卡人姓名
reqParam["bankcardnumber"] = req.BankCardNo // 银行卡号
reqParam["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(reqParam)
if jErr != nil {
logx.Errorf("map转json失败, err=%v", jErr)
return nil, jErr
}
// 2.发送请求 //调用java sdk
funcName := utils.RunFuncName()
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.transferUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal([]byte(body), &resp); err != nil {
return nil, errors.New("response body is empty")
}
resp2 := map[string]interface{}{}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp2); err != nil {
return nil, errors.New("response body is empty")
}
// 4.验证业务是否成功
if resp2["data"] == nil || resp2["data"] == "" {
return nil, errors.New("response body is empty")
}
//var dataMap map[string]interface{}
//if err := json.Unmarshal([]byte(resp2["data"]), &dataMap); err != nil {
// return nil, errors.New("response body is empty")
//}
logx.Infof("status=%v", resp2["result"])
var orderStatus int64
switch resp2["result"] {
case "success":
orderStatus = PayPaying // 支付中
default:
orderStatus = PayFail // 支付失败
}
return &TransferResponse{
UpstreamOrderNo: utils.ToStringNoPoint(resp2["businessrecordnumber"]),
OrderStatus: orderStatus,
}, nil
}
func (o *TopPay) TransferOrderQuery(request *TransferOrderQueryRequest) (*TransferOrderQueryResponse, error) {
panic("implement me")
}
func (o *TopPay) QueryBalance() (*QueryBalanceResponse, error) {
panic("implement me")
}
func (o *TopPay) GenerateSign(data map[string]interface{}) string {
panic("implement me")
}
func (o *TopPay) CheckSign(data map[string]interface{}) error {
panic("implement me")
}
//
//type BankCardInfo struct {
// BankCardNo string // 银行卡号
// BankCardName string // 持卡人名
// BankCardIdNo string // 持卡人身份证号
// BankCardPhone string // 持卡人手机
// // 信用卡必传
// BankCardCvv2 string // cvv2
// // 信用卡必传
// BankCardExpireDate string // 银行卡有效期
//
// ClientIp string // 请求ip
// IsCreditCard bool // 是否信用卡
//}
type TopPayConfig struct {
Host string `json:"Host"` // 请求的地址
PayNotifyPath string `json:"PayNotifyPath"` // 请求的地址
TransferNotifyPath string `json:"TransferNotifyPath"` // 请求的地址
AppId string `json:"AppId"` // 请求的地址
CashierHost string `json:"CashierHost"` // 请求的地址
}
func CheckTopPayConfig(conf TopPayConfig) error {
if strings.TrimSpace(conf.Host) == "" {
return errors.New("TopPay.Host配置不能为空")
}
// 更多判断...
return nil
}
func NewTopPay(upMerchantNo string, jsonStrConfig string) (Upstream, error) {
c := TopPayConfig{}
// 解析配置
if err := json.Unmarshal([]byte(jsonStrConfig), &c); err != nil {
return nil, err
}
// 检查配置
if err := CheckTopPayConfig(c); err != nil {
return nil, err
}
o := &TopPay{}
o.config = c
o.upMerchantNo = upMerchantNo
o.quickSignUrl = strings.TrimRight(c.Host, "/") + TopPayQuickSignUrl
o.quickSignQueryUrl = strings.TrimRight(c.Host, "/") + "/signQuery"
o.quickPayUrl = strings.TrimRight(c.Host, "/") + "/quickPay"
o.quickPayConfirmUrl = strings.TrimRight(c.Host, "/") + "/quickPayConfirm"
o.quickSignConfirmUrl = strings.TrimRight(c.Host, "/") + "/quickSignConfirm"
o.transferUrl = strings.TrimRight(c.Host, "/") + "/transfer"
return o, nil
}
// 获取上游配置
func (o *TopPay) GetUpstreamConfig() *ConfigResponse {
return &ConfigResponse{
Host: o.config.Host,
PayNotifyPath: o.config.PayNotifyPath,
TransferNotifyPath: o.config.TransferNotifyPath,
SecretKey: "",
AppId: o.config.AppId,
}
}
func (o *TopPay) QPaySignConfirm(req *QPaySignConfirmRequest) (*QPaySignConfirmResponse, error) {
// 1.拼接参数
params := make(map[string]interface{})
params["businessrecordnumber"] = req.Businessrecordnumber
params["verifycode"] = req.Verifycode // String M 异步通知回调地址
params["clientip"] = utils.GetFakeIp() // String M 异步通知回调地址
params["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(params)
if jErr != nil {
return nil, jErr
}
funcName := utils.RunFuncName()
// 2.发送请求
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.quickSignConfirmUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
// 4.验证业务是否成功
if resp["data"] == nil {
return nil, errors.New(fmt.Sprintf("response code failed,msg:%v", resp))
}
//data := resp["data"].(map[string]interface{})
var dataMap map[string]interface{}
if err := json.Unmarshal([]byte(resp["data"].(string)), &dataMap); err != nil {
return &QPaySignConfirmResponse{
ErrMsg: fmt.Sprintf("%v|%v", resp["msg"], resp["biz_msg"]),
}, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if _, ok := dataMap["businessrecordnumber"]; !ok {
dataMap["businessrecordnumber"] = ""
}
if _, ok := dataMap["businessnumber"]; !ok {
dataMap["businessnumber"] = ""
}
// 5.返回结果
return &QPaySignConfirmResponse{
Businessnumber: dataMap["businessnumber"].(string),
Businessrecordnumber: dataMap["businessrecordnumber"].(string),
}, nil
}
func (o *TopPay) QPaySignSms(req *QPaySignSmsRequest) (*QPaySignSmsResponse, error) {
// 1.拼接参数
params := make(map[string]interface{})
params["businessnumber"] = req.OrderNo
params["bankcardnumber"] = req.BankCardInfo.BankCardNo // String M 异步通知回调地址
params["bankcardname"] = req.BankCardInfo.BankCardName // String M 异步通知回调地址
params["certificatenumber"] = req.BankCardInfo.BankCardIdNo // String M 异步通知回调地址
params["bankmobilenumber"] = req.BankCardInfo.BankCardPhone // String M 异步通知回调地址
params["backUrl"] = req.NotifyUrl // String M 异步通知回调地址
params["clientip"] = utils.GetFakeIp() // String M 异步通知回调地址
params["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(params)
if jErr != nil {
return nil, jErr
}
funcName := utils.RunFuncName()
// 2.发送请求
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.quickSignUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
// 4.验证业务是否成功
if resp["data"] == nil {
return nil, errors.New(fmt.Sprintf("response code failed,msg:%v", resp))
}
//data := resp["data"].(map[string]interface{})
var dataMap map[string]interface{}
if err := json.Unmarshal([]byte(resp["data"].(string)), &dataMap); err != nil {
return &QPaySignSmsResponse{
ErrMsg: fmt.Sprintf("%v|%v", resp["msg"], resp["biz_msg"]),
}, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if _, ok := dataMap["businessrecordnumber"]; !ok {
dataMap["businessrecordnumber"] = ""
}
if _, ok := dataMap["businessnumber"]; !ok {
dataMap["businessnumber"] = ""
}
if _, ok := dataMap["certcode"]; !ok {
dataMap["certcode"] = ""
}
fmt.Printf("businessrecordnumber=%v", dataMap["businessrecordnumber"].(string))
// 5.返回结果
return &QPaySignSmsResponse{
Businessnumber: utils.ToStringNoPoint(dataMap["businessnumber"]),
Businessrecordnumber: utils.ToStringNoPoint(dataMap["businessrecordnumber"]),
Certcode: utils.ToStringNoPoint(dataMap["certcode"]),
ErrMsg: fmt.Sprintf("%v|%v", resp["msg"], resp["biz_msg"]),
}, nil
}
// 查询是否已经签约
func (o *TopPay) QPaySignQuery(req *QPaySignQueryRequest) (*QPaySignQueryResponse, error) {
// 1.拼接参数
params := make(map[string]interface{})
params["businessnumber"] = req.BankCardNo
params["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(params)
if jErr != nil {
return nil, jErr
}
funcName := utils.RunFuncName()
// 2.发送请求
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.quickSignQueryUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
// 4.验证业务是否成功
if resp["data"] == nil {
return nil, errors.New(fmt.Sprintf("response code failed,msg:%v", resp))
}
//data := resp["data"].(map[string]interface{})
var dataMap map[string]interface{}
if err := json.Unmarshal([]byte(resp["data"].(string)), &dataMap); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if _, ok := dataMap["businessrecordnumber"]; !ok {
dataMap["businessrecordnumber"] = ""
}
if _, ok := dataMap["businessnumber"]; !ok {
dataMap["businessnumber"] = ""
}
if _, ok := dataMap["certcode"]; !ok {
dataMap["certcode"] = ""
}
// 5.返回结果
return &QPaySignQueryResponse{
IsSigned: dataMap["certcode"].(string) != "",
Businessnumber: dataMap["businessnumber"].(string),
Businessrecordnumber: dataMap["businessrecordnumber"].(string),
Certcode: dataMap["certcode"].(string),
}, nil
}
// 下单
func (o *TopPay) QPay(req *QPayRequest) (*QPayResponse, error) {
// 1.拼接参数
params := make(map[string]interface{})
params["backurl"] = req.Backurl
params["subject"] = req.Subject
params["businesstype"] = req.Businesstype
params["kind"] = req.Kind
params["description"] = req.Description
params["businessnumber"] = req.Businessnumber
params["billamount"] = req.Billamount
params["toaccountnumber"] = req.Toaccountnumber
params["certcode"] = req.Certcode
params["clientip"] = utils.GetFakeIp()
params["merchantuserid"] = req.Merchantuserid
params["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(params)
if jErr != nil {
return nil, jErr
}
funcName := utils.RunFuncName()
// 2.发送请求
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.quickPayUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
// 4.验证业务是否成功
if resp["data"] == nil {
return nil, errors.New(fmt.Sprintf("response code failed,msg:%v", resp))
}
//data := resp["data"].(map[string]interface{})
var dataMap map[string]interface{}
if err := json.Unmarshal([]byte(resp["data"].(string)), &dataMap); err != nil {
return &QPayResponse{
ErrMsg: fmt.Sprintf("%v|%v", resp["msg"], resp["biz_msg"]),
}, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if _, ok := dataMap["businessrecordnumber"]; !ok {
dataMap["businessrecordnumber"] = ""
}
if _, ok := dataMap["businessnumber"]; !ok {
dataMap["businessnumber"] = ""
}
// 5.返回结果
return &QPayResponse{
Businessnumber: dataMap["businessnumber"].(string),
Businessrecordnumber: dataMap["businessrecordnumber"].(string),
}, nil
}
// 下单确认支付
func (o *TopPay) QPayConfirm(req *QPayConfirmRequest) (*QPayConfirmResponse, error) {
// 1.拼接参数
params := make(map[string]interface{})
params["businessrecordnumber"] = req.Businessrecordnumber
params["verifycode"] = req.Verifycode
params["clientip"] = utils.GetFakeIp()
params["appid"] = o.config.AppId
dataByte, jErr := json.Marshal(params)
if jErr != nil {
return nil, jErr
}
funcName := utils.RunFuncName()
// 2.发送请求
logx.Infof(funcName+":request:%v", string(dataByte))
//return nil, nil
body, err := utils.PostJson(o.quickPayConfirmUrl, dataByte)
logx.Infof(funcName+":response:%v", string(body))
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, errors.New("response body is empty")
}
// 3.解析返回结果
resp := map[string]interface{}{}
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if err := json.Unmarshal([]byte(resp["resp"].(string)), &resp); err != nil {
return nil, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
// 4.验证业务是否成功
if resp["data"] == nil {
return nil, errors.New(fmt.Sprintf("response code failed,msg:%v", resp))
}
//data := resp["data"].(map[string]interface{})
var dataMap map[string]interface{}
if err := json.Unmarshal([]byte(resp["data"].(string)), &dataMap); err != nil {
return &QPayConfirmResponse{
ErrMsg: fmt.Sprintf("%v|%v", resp["msg"], resp["biz_msg"]),
}, errors.New(fmt.Sprintf("parse json body failed, err:%v, body:%v", err, string(body)))
}
if _, ok := dataMap["businessrecordnumber"]; !ok {
dataMap["businessrecordnumber"] = ""
}
if _, ok := dataMap["businessnumber"]; !ok {
dataMap["businessnumber"] = ""
}
// 5.返回结果
return &QPayConfirmResponse{
Businessnumber: dataMap["businessnumber"].(string),
Businessrecordnumber: dataMap["businessrecordnumber"].(string),
}, nil
}
|
package html
import (
"github.com/elliotchance/gedcom"
"github.com/elliotchance/gedcom/html/core"
"io"
)
type PlaceStatistics struct {
document *gedcom.Document
placesMap map[string]*place
}
func newPlaceStatistics(document *gedcom.Document, placesMap map[string]*place) *PlaceStatistics {
return &PlaceStatistics{
document: document,
placesMap: placesMap,
}
}
func (c *PlaceStatistics) WriteHTMLTo(w io.Writer) (int64, error) {
total := core.NewNumber(len(c.placesMap))
s := core.NewComponents(
core.NewKeyedTableRow("Total", total, true),
)
return core.NewCard(core.NewText("Places"), core.CardNoBadgeCount,
core.NewTable("", s)).WriteHTMLTo(w)
}
|
package bosh_test
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/cloudfoundry/bosh-bootloader/bosh"
"github.com/cloudfoundry/bosh-bootloader/fakes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Executor", func() {
Describe("JumpboxCreateEnvArgs", func() {
var (
cmd *fakes.BOSHCommand
stateDir string
relativeDeploymentDir string
relativeVarsDir string
executor bosh.Executor
interpolateInput bosh.InterpolateInput
)
BeforeEach(func() {
cmd = &fakes.BOSHCommand{}
cmd.RunStub = func(stdout io.Writer, workingDirectory string, args []string) error {
stdout.Write([]byte("some-manifest"))
return nil
}
cmd.GetBOSHPathCall.Returns.Path = "bosh-path"
var err error
stateDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
deploymentDir := filepath.Join(stateDir, "deployment")
err = os.Mkdir(deploymentDir, os.ModePerm)
Expect(err).NotTo(HaveOccurred())
varsDir := filepath.Join(stateDir, "vars")
err = os.Mkdir(varsDir, os.ModePerm)
Expect(err).NotTo(HaveOccurred())
relativeDeploymentDir = "${BBL_STATE_DIR}/deployment"
relativeVarsDir = "${BBL_STATE_DIR}/vars"
interpolateInput = bosh.InterpolateInput{
IAAS: "aws",
DeploymentDir: deploymentDir,
VarsDir: varsDir,
StateDir: stateDir,
BOSHState: map[string]interface{}{
"key": "value",
},
Variables: "key: value",
OpsFile: "some-ops-file",
}
executor = bosh.NewExecutor(cmd, ioutil.ReadFile, json.Unmarshal, json.Marshal, ioutil.WriteFile)
})
It("generates create-env args for jumpbox", func() {
interpolateInput.DeploymentVars = "internal_cidr: 10.0.0.0/24"
interpolateInput.OpsFile = ""
err := executor.JumpboxCreateEnvArgs(interpolateInput)
Expect(err).NotTo(HaveOccurred())
expectedArgs := []string{
fmt.Sprintf("%s/jumpbox.yml", relativeDeploymentDir),
"--state", fmt.Sprintf("%s/jumpbox-state.json", relativeVarsDir),
"--vars-store", fmt.Sprintf("%s/jumpbox-variables.yml", relativeVarsDir),
"--vars-file", fmt.Sprintf("%s/jumpbox-deployment-vars.yml", relativeVarsDir),
"-o", fmt.Sprintf("%s/cpi.yml", relativeDeploymentDir),
}
By("writing the create-env args to a shell script", func() {
expectedScript := formatScript("create-env", stateDir, expectedArgs)
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/create-jumpbox.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(expectedScript))
})
By("writing the delete-env args to a shell script", func() {
expectedScript := formatScript("delete-env", stateDir, expectedArgs)
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/delete-jumpbox.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(expectedScript))
})
})
Context("when a create-env script already exists", func() {
var (
createEnvPath string
createEnvContents string
)
BeforeEach(func() {
createEnvPath = filepath.Join(stateDir, "create-jumpbox.sh")
createEnvContents = "#!/bin/bash\necho 'I already exist'\n"
ioutil.WriteFile(createEnvPath, []byte(createEnvContents), os.ModePerm)
})
It("does not override the existing script", func() {
err := executor.JumpboxCreateEnvArgs(interpolateInput)
Expect(err).NotTo(HaveOccurred())
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/create-jumpbox.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(createEnvContents))
})
})
Context("when a delete-env script already exists", func() {
var (
deleteEnvPath string
deleteEnvContents string
)
BeforeEach(func() {
deleteEnvPath = filepath.Join(stateDir, "delete-jumpbox.sh")
deleteEnvContents = "#!/bin/bash\necho 'I already exist'\n"
ioutil.WriteFile(deleteEnvPath, []byte(deleteEnvContents), os.ModePerm)
})
It("does not override the existing script", func() {
err := executor.JumpboxCreateEnvArgs(interpolateInput)
Expect(err).NotTo(HaveOccurred())
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/delete-jumpbox.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(deleteEnvContents))
})
})
})
Describe("DirectorCreateEnvArgs", func() {
var (
cmd *fakes.BOSHCommand
stateDir string
relativeDeploymentDir string
relativeVarsDir string
executor bosh.Executor
interpolateInput bosh.InterpolateInput
)
BeforeEach(func() {
cmd = &fakes.BOSHCommand{}
cmd.GetBOSHPathCall.Returns.Path = "bosh-path"
var err error
stateDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
deploymentDir := filepath.Join(stateDir, "deployment")
err = os.Mkdir(deploymentDir, os.ModePerm)
Expect(err).NotTo(HaveOccurred())
varsDir := filepath.Join(stateDir, "vars")
err = os.Mkdir(varsDir, os.ModePerm)
Expect(err).NotTo(HaveOccurred())
relativeDeploymentDir = "${BBL_STATE_DIR}/deployment"
relativeVarsDir = "${BBL_STATE_DIR}/vars"
interpolateInput = bosh.InterpolateInput{
DeploymentDir: deploymentDir,
StateDir: stateDir,
VarsDir: varsDir,
DeploymentVars: "internal_cidr: 10.0.0.0/24",
BOSHState: map[string]interface{}{
"key": "value",
},
Variables: "key: value",
OpsFile: "some-ops-file",
}
executor = bosh.NewExecutor(cmd, ioutil.ReadFile, json.Unmarshal, json.Marshal, ioutil.WriteFile)
})
Context("azure", func() {
var azureInterpolateInput bosh.InterpolateInput
BeforeEach(func() {
azureInterpolateInput = interpolateInput
azureInterpolateInput.IAAS = "azure"
})
It("generates a bosh manifest", func() {
cmd.RunStub = func(stdout io.Writer, workingDirectory string, args []string) error {
stdout.Write([]byte("some-manifest"))
return nil
}
err := executor.DirectorCreateEnvArgs(azureInterpolateInput)
Expect(err).NotTo(HaveOccurred())
Expect(cmd.RunCallCount()).To(Equal(0))
expectedArgs := []string{
fmt.Sprintf("%s/bosh.yml", relativeDeploymentDir),
"--state", fmt.Sprintf("%s/bosh-state.json", relativeVarsDir),
"--vars-store", fmt.Sprintf("%s/director-variables.yml", relativeVarsDir),
"--vars-file", fmt.Sprintf("%s/director-deployment-vars.yml", relativeVarsDir),
"-o", fmt.Sprintf("%s/cpi.yml", relativeDeploymentDir),
"-o", fmt.Sprintf("%s/jumpbox-user.yml", relativeDeploymentDir),
"-o", fmt.Sprintf("%s/uaa.yml", relativeDeploymentDir),
"-o", fmt.Sprintf("%s/credhub.yml", relativeDeploymentDir),
"-o", fmt.Sprintf("%s/user-ops-file.yml", relativeVarsDir),
}
By("writing the create-env args to a shell script", func() {
expectedScript := formatScript("create-env", stateDir, expectedArgs)
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/create-director.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(expectedScript))
})
By("writing the delete-env args to a shell script", func() {
expectedScript := formatScript("delete-env", stateDir, expectedArgs)
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/delete-director.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(expectedScript))
})
})
})
Context("gcp", func() {
var gcpInterpolateInput bosh.InterpolateInput
BeforeEach(func() {
gcpInterpolateInput = interpolateInput
gcpInterpolateInput.IAAS = "gcp"
cmd.RunStub = func(stdout io.Writer, workingDirectory string, args []string) error {
stdout.Write([]byte("some-manifest"))
return nil
}
})
Context("when a create-env script already exists", func() {
var (
createEnvPath string
createEnvContents string
)
BeforeEach(func() {
createEnvPath = filepath.Join(stateDir, "create-director.sh")
createEnvContents = "#!/bin/bash\necho 'I already exist'\n"
ioutil.WriteFile(createEnvPath, []byte(createEnvContents), os.ModePerm)
})
It("does not override the existing script", func() {
err := executor.DirectorCreateEnvArgs(gcpInterpolateInput)
Expect(err).NotTo(HaveOccurred())
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/create-director.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(createEnvContents))
})
})
Context("when a delete-env script already exists", func() {
var (
deleteEnvPath string
deleteEnvContents string
)
BeforeEach(func() {
deleteEnvPath = filepath.Join(stateDir, "delete-director.sh")
deleteEnvContents = "#!/bin/bash\necho 'I already exist'\n"
ioutil.WriteFile(deleteEnvPath, []byte(deleteEnvContents), os.ModePerm)
})
It("does not override the existing script", func() {
err := executor.DirectorCreateEnvArgs(gcpInterpolateInput)
Expect(err).NotTo(HaveOccurred())
shellScript, err := ioutil.ReadFile(fmt.Sprintf("%s/delete-director.sh", stateDir))
Expect(err).NotTo(HaveOccurred())
Expect(string(shellScript)).To(Equal(deleteEnvContents))
})
})
})
})
Describe("CreateEnv", func() {
var (
cmd *fakes.BOSHCommand
executor bosh.Executor
createEnvPath string
varsDir string
stateDir string
createEnvInput bosh.CreateEnvInput
)
BeforeEach(func() {
var err error
cmd = &fakes.BOSHCommand{}
varsDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
stateDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
executor = bosh.NewExecutor(cmd, ioutil.ReadFile, json.Unmarshal, json.Marshal, ioutil.WriteFile)
createEnvInput = bosh.CreateEnvInput{
Deployment: "some-deployment",
StateDir: stateDir,
VarsDir: varsDir,
}
createEnvPath = filepath.Join(stateDir, "create-some-deployment.sh")
createEnvContents := fmt.Sprintf("#!/bin/bash\necho 'some-vars-store-contents' > %s/some-deployment-variables.yml\n", varsDir)
ioutil.WriteFile(createEnvPath, []byte(createEnvContents), os.ModePerm)
})
AfterEach(func() {
os.Remove(filepath.Join(varsDir, "some-deployment-variables.yml"))
os.Remove(filepath.Join(stateDir, "create-some-deployment.sh"))
os.Unsetenv("BBL_STATE_DIR")
})
It("runs the create-env script and returns the resulting vars-store contents", func() {
vars, err := executor.CreateEnv(createEnvInput)
Expect(err).NotTo(HaveOccurred())
Expect(cmd.RunCallCount()).To(Equal(0))
Expect(vars).To(ContainSubstring("some-vars-store-contents"))
By("setting BBL_STATE_DIR environment variable", func() {
bblStateDirEnv := os.Getenv("BBL_STATE_DIR")
Expect(bblStateDirEnv).To(Equal(stateDir))
})
})
Context("when the create-env script returns an error", func() {
BeforeEach(func() {
createEnvContents := "#!/bin/bash\nexit 1\n"
ioutil.WriteFile(createEnvPath, []byte(createEnvContents), os.ModePerm)
})
It("returns an error", func() {
vars, err := executor.CreateEnv(createEnvInput)
Expect(err).To(MatchError("Run bosh create-env: exit status 1"))
Expect(vars).To(Equal(""))
})
})
})
Describe("DeleteEnv", func() {
var (
cmd *fakes.BOSHCommand
executor bosh.Executor
deleteEnvPath string
varsDir string
stateDir string
deleteEnvInput bosh.DeleteEnvInput
)
BeforeEach(func() {
var err error
cmd = &fakes.BOSHCommand{}
varsDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
stateDir, err = ioutil.TempDir("", "")
Expect(err).NotTo(HaveOccurred())
executor = bosh.NewExecutor(cmd, ioutil.ReadFile, json.Unmarshal, json.Marshal, ioutil.WriteFile)
deleteEnvInput = bosh.DeleteEnvInput{
Deployment: "some-deployment",
VarsDir: varsDir,
StateDir: stateDir,
}
deleteEnvPath = filepath.Join(stateDir, "delete-some-deployment.sh")
deleteEnvContents := "#!/bin/bash\necho delete-env > /dev/null\n"
ioutil.WriteFile(deleteEnvPath, []byte(deleteEnvContents), os.ModePerm)
})
AfterEach(func() {
os.Unsetenv("BBL_STATE_DIR")
os.Remove(filepath.Join(stateDir, "delete-some-deployment.sh"))
})
It("deletes a bosh environment with the delete-env script", func() {
err := executor.DeleteEnv(deleteEnvInput)
Expect(err).NotTo(HaveOccurred())
Expect(cmd.RunCallCount()).To(Equal(0))
By("setting BBL_STATE_DIR environment variable", func() {
bblStateDirEnv := os.Getenv("BBL_STATE_DIR")
Expect(bblStateDirEnv).To(Equal(stateDir))
})
})
Context("when the create-env script returns an error", func() {
BeforeEach(func() {
deleteEnvContents := "#!/bin/bash\nexit 1\n"
ioutil.WriteFile(deleteEnvPath, []byte(deleteEnvContents), os.ModePerm)
})
It("returns an error", func() {
err := executor.DeleteEnv(deleteEnvInput)
Expect(err).To(MatchError("Run bosh delete-env: exit status 1"))
})
})
})
Describe("Version", func() {
var (
cmd *fakes.BOSHCommand
executor bosh.Executor
)
BeforeEach(func() {
cmd = &fakes.BOSHCommand{}
cmd.RunStub = func(stdout io.Writer, workingDirectory string, args []string) error {
stdout.Write([]byte("some-text version 2.0.24 some-other-text"))
return nil
}
executor = bosh.NewExecutor(cmd, ioutil.ReadFile, json.Unmarshal, json.Marshal, ioutil.WriteFile)
})
It("passes the correct args and dir to run command", func() {
_, err := executor.Version()
Expect(err).NotTo(HaveOccurred())
_, _, args := cmd.RunArgsForCall(0)
Expect(args).To(Equal([]string{"-v"}))
})
It("returns the correctly trimmed version", func() {
version, err := executor.Version()
Expect(err).NotTo(HaveOccurred())
Expect(version).To(Equal("2.0.24"))
})
Context("failure cases", func() {
Context("when the run cmd fails", func() {
BeforeEach(func() {
cmd.RunReturns(errors.New("failed to run cmd"))
})
It("returns an error", func() {
_, err := executor.Version()
Expect(err).To(MatchError("failed to run cmd"))
})
})
Context("when the version cannot be parsed", func() {
var expectedError error
BeforeEach(func() {
expectedError = bosh.NewBOSHVersionError(errors.New("BOSH version could not be parsed"))
cmd.RunStub = func(stdout io.Writer, workingDirectory string, args []string) error {
stdout.Write([]byte(""))
return nil
}
})
It("returns a bosh version error", func() {
_, err := executor.Version()
Expect(err).To(Equal(expectedError))
})
})
})
})
})
func formatScript(command string, stateDir string, args []string) string {
script := fmt.Sprintf("#!/bin/sh\nbosh-path %s \\\n", command)
for _, arg := range args {
if arg[0] == '-' {
script = fmt.Sprintf("%s %s", script, arg)
} else {
script = fmt.Sprintf("%s %s \\\n", script, arg)
}
}
return fmt.Sprintf("%s\n", script[:len(script)-2])
}
|
package controllers
import (
"github.com/astaxie/beego"
"nepliteApi/comm"
"github.com/astaxie/beego/logs"
"encoding/json"
"nepliteApi/models"
)
type GroupController struct {
beego.Controller
}
func (group *GroupController) Add() {
result := comm.Result{Ret: map[string]interface{}{"err": "", "num": 0, "result": ""}}
logs.Info("result : == ", result.Ret)
var _l_group models.Group
logs.Info("请求数据是 :%s ", group.Ctx.Input.RequestBody)
if err := json.Unmarshal(group.Ctx.Input.RequestBody, &_l_group); err != nil {
result.SetValue("-1", 0, err)
group.Data["json"] = result.Get()
group.ServeJSON()
}
logs.Warn("asdasd %s", _l_group)
if _l_group, err := models.GetGroupByUserID(_l_group.GroupMasterID); err == nil {
result.SetValue("-2", 0, "已经添加过了, 请不要重复添加店名")
group.Data["json"] = result.Get()
group.ServeJSON()
logs.Warn("_l_group == %s; %s", _l_group, err)
}
logs.Warn("dasdasdasdasdsadsad")
if id, err := models.AddGroup(_l_group); err != nil {
result.SetValue("-2", 0, err)
group.Data["json"] = result.Get()
group.ServeJSON()
} else {
result.SetValue("0", 0 , id)
}
group.Data["json"] = result.Get()
group.ServeJSON()
}
func (group *GroupController) GetByUserId() {
result := comm.Result{Ret: map[string]interface{}{"err": "", "num": 0, "result": ""}}
logs.Info("result : == ", result.Ret)
//var _l_group models.Group
var user_id string
if user_id = group.GetString("user_id"); user_id == "" {
result.SetValue("-1", 0, user_id)
group.Data["json"] = result.Get()
group.ServeJSON()
}
if _l_group, err := models.GetGroupByUserID(user_id); err != nil {
result.SetValue("-2", 0, _l_group)
group.Data["json"] = result.Get()
group.ServeJSON()
} else {
result.SetValue("0", 0, _l_group)
}
group.Data["json"] = result.Get()
group.ServeJSON()
}
|
// Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package importer
import (
"context"
"io"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/br/pkg/lightning/backend/encode"
"github.com/pingcap/tidb/br/pkg/lightning/backend/kv"
"github.com/pingcap/tidb/br/pkg/lightning/common"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/mysql" //nolint: goimports
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
)
type kvEncoder interface {
Encode(row []types.Datum, rowID int64) (*kv.Pairs, error)
// GetColumnSize returns the size of each column in the current encoder.
GetColumnSize() map[int64]int64
io.Closer
}
// tableKVEncoder encodes a row of data into a KV pair.
type tableKVEncoder struct {
*kv.BaseKVEncoder
// see import.go
columnAssignments []expression.Expression
columnsAndUserVars []*ast.ColumnNameOrUserVar
fieldMappings []*FieldMapping
insertColumns []*table.Column
}
var _ kvEncoder = &tableKVEncoder{}
func newTableKVEncoder(
config *encode.EncodingConfig,
ti *TableImporter,
) (*tableKVEncoder, error) {
baseKVEncoder, err := kv.NewBaseKVEncoder(config)
if err != nil {
return nil, err
}
// we need a non-nil TxnCtx to avoid panic when evaluating set clause
baseKVEncoder.SessionCtx.Vars.TxnCtx = new(variable.TransactionContext)
colAssignExprs, _, err := ti.CreateColAssignExprs(baseKVEncoder.SessionCtx)
if err != nil {
return nil, err
}
return &tableKVEncoder{
BaseKVEncoder: baseKVEncoder,
columnAssignments: colAssignExprs,
columnsAndUserVars: ti.ColumnsAndUserVars,
fieldMappings: ti.FieldMappings,
insertColumns: ti.InsertColumns,
}, nil
}
// Encode implements the kvEncoder interface.
func (en *tableKVEncoder) Encode(row []types.Datum, rowID int64) (*kv.Pairs, error) {
// we ignore warnings when encoding rows now, but warnings uses the same memory as parser, since the input
// row []types.Datum share the same underlying buf, and when doing CastValue, we're using hack.String/hack.Slice.
// when generating error such as mysql.ErrDataOutOfRange, the data will be part of the error, causing the buf
// unable to release. So we truncate the warnings here.
defer en.TruncateWarns()
record, err := en.parserData2TableData(row, rowID)
if err != nil {
return nil, err
}
return en.Record2KV(record, row, rowID)
}
func (en *tableKVEncoder) GetColumnSize() map[int64]int64 {
sessionVars := en.SessionCtx.GetSessionVars()
sessionVars.TxnCtxMu.Lock()
defer sessionVars.TxnCtxMu.Unlock()
return sessionVars.TxnCtx.TableDeltaMap[en.Table.Meta().ID].ColSize
}
// todo merge with code in load_data.go
func (en *tableKVEncoder) parserData2TableData(parserData []types.Datum, rowID int64) ([]types.Datum, error) {
row := make([]types.Datum, 0, len(en.insertColumns))
sessionVars := en.SessionCtx.GetSessionVars()
setVar := func(name string, col *types.Datum) {
// User variable names are not case-sensitive
// https://dev.mysql.com/doc/refman/8.0/en/user-variables.html
name = strings.ToLower(name)
if col == nil || col.IsNull() {
sessionVars.UnsetUserVar(name)
} else {
sessionVars.SetUserVarVal(name, *col)
}
}
for i := 0; i < len(en.fieldMappings); i++ {
if i >= len(parserData) {
if en.fieldMappings[i].Column == nil {
setVar(en.fieldMappings[i].UserVar.Name, nil)
continue
}
// If some columns is missing and their type is time and has not null flag, they should be set as current time.
if types.IsTypeTime(en.fieldMappings[i].Column.GetType()) && mysql.HasNotNullFlag(en.fieldMappings[i].Column.GetFlag()) {
row = append(row, types.NewTimeDatum(types.CurrentTime(en.fieldMappings[i].Column.GetType())))
continue
}
row = append(row, types.NewDatum(nil))
continue
}
if en.fieldMappings[i].Column == nil {
setVar(en.fieldMappings[i].UserVar.Name, &parserData[i])
continue
}
row = append(row, parserData[i])
}
for i := 0; i < len(en.columnAssignments); i++ {
// eval expression of `SET` clause
d, err := en.columnAssignments[i].Eval(chunk.Row{})
if err != nil {
return nil, err
}
row = append(row, d)
}
// a new row buffer will be allocated in getRow
newRow, err := en.getRow(row, rowID)
if err != nil {
return nil, err
}
return newRow, nil
}
// getRow gets the row which from `insert into select from` or `load data`.
// The input values from these two statements are datums instead of
// expressions which are used in `insert into set x=y`.
// copied from InsertValues
func (en *tableKVEncoder) getRow(vals []types.Datum, rowID int64) ([]types.Datum, error) {
row := make([]types.Datum, len(en.Columns))
hasValue := make([]bool, len(en.Columns))
for i := 0; i < len(en.insertColumns); i++ {
casted, err := table.CastValue(en.SessionCtx, vals[i], en.insertColumns[i].ToInfo(), false, false)
if err != nil {
return nil, err
}
offset := en.insertColumns[i].Offset
row[offset] = casted
hasValue[offset] = true
}
return en.fillRow(row, hasValue, rowID)
}
func (en *tableKVEncoder) fillRow(row []types.Datum, hasValue []bool, rowID int64) ([]types.Datum, error) {
var value types.Datum
var err error
record := en.GetOrCreateRecord()
for i, col := range en.Columns {
var theDatum *types.Datum
if hasValue[i] {
theDatum = &row[i]
}
value, err = en.ProcessColDatum(col, rowID, theDatum)
if err != nil {
return nil, en.LogKVConvertFailed(row, i, col.ToInfo(), err)
}
record = append(record, value)
}
if common.TableHasAutoRowID(en.Table.Meta()) {
// todo: we assume there's no such column in input data, will handle it later
rowValue := rowID
newRowID := en.AutoIDFn(rowID)
value = types.NewIntDatum(newRowID)
record = append(record, value)
alloc := en.Table.Allocators(en.SessionCtx).Get(autoid.RowIDAllocType)
if err := alloc.Rebase(context.Background(), rowValue, false); err != nil {
return nil, errors.Trace(err)
}
}
if len(en.GenCols) > 0 {
if errCol, err := en.EvalGeneratedColumns(record, en.Columns); err != nil {
return nil, en.LogEvalGenExprFailed(row, errCol, err)
}
}
return record, nil
}
func (en *tableKVEncoder) Close() error {
en.SessionCtx.Close()
return nil
}
|
// Package flags provides frequently used kingpin flags for command-line tools
// that connect to Consul.
package flags
import (
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"time"
"github.com/square/p2/pkg/labels"
"github.com/square/p2/pkg/store/consul"
netutil "github.com/square/p2/pkg/util/net"
"gopkg.in/alecthomas/kingpin.v2"
)
func ParseWithConsulOptions() (string, consul.Options, labels.ApplicatorWithoutWatches) {
consulURL := kingpin.Flag("consul", "The hostname and port of a consul agent in the p2 cluster. Defaults to 0.0.0.0:8500.").String()
httpApplicatorURL := kingpin.Flag("http-applicator-url", "The URL of an labels.httpApplicator target, including the protocol and port. For example, https://consul-server.io:9999").URL()
token := kingpin.Flag("token", "The consul ACL token to use. Empty by default.").String()
tokenFile := kingpin.Flag("token-file", "The file containing the Consul ACL token").ExistingFile()
headers := kingpin.Flag("header", "An HTTP header to add to requests, in KEY=VALUE form. Can be specified multiple times.").StringMap()
https := kingpin.Flag("https", "Use HTTPS").Bool()
wait := kingpin.Flag("wait", "Maximum duration for Consul watches, before resetting and starting again.").Default("30s").Duration()
caFile := kingpin.Flag("tls-ca-file", "File containing the x509 PEM-encoded CA ").ExistingFile()
keyFile := kingpin.Flag("tls-key-file", "File containing the x509 PEM-encoded private key").ExistingFile()
certFile := kingpin.Flag("tls-cert-file", "File containing the x509 PEM-encoded public key certificate").ExistingFile()
cmd := kingpin.Parse()
if *tokenFile != "" {
tokenBytes, err := ioutil.ReadFile(*tokenFile)
if err != nil {
log.Fatalln(err)
}
*token = strings.TrimSpace(string(tokenBytes))
}
var transport http.RoundTripper
if *caFile != "" || *keyFile != "" || *certFile != "" {
tlsConfig, err := netutil.GetTLSConfig(*certFile, *keyFile, *caFile)
if err != nil {
log.Fatalln(err)
}
transport = &http.Transport{
TLSClientConfig: tlsConfig,
// same dialer as http.DefaultTransport
Dial: (&net.Dialer{
Timeout: http.DefaultClient.Timeout,
KeepAlive: http.DefaultClient.Timeout,
}).Dial,
}
} else {
transport = http.DefaultTransport
}
httpClient := netutil.NewHeaderClient(*headers, transport)
consulOpts := consul.Options{
Address: *consulURL,
Token: *token,
Client: httpClient,
HTTPS: *https,
WaitTime: *wait,
}
var applicator labels.ApplicatorWithoutWatches
var err error
if *httpApplicatorURL != nil {
applicator, err = labels.NewHTTPApplicator(httpClient, *httpApplicatorURL)
if err != nil {
log.Fatalln(err)
}
} else {
jitterWindow := 0 * time.Second // we don't initiate watches in CLIs so this doesn't matter
applicator = labels.NewConsulApplicator(consul.NewConsulClient(consulOpts), 0, jitterWindow)
}
return cmd, consulOpts, applicator
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//598. Range Addition II
//Given an m * n matrix M initialized with all 0's and several update operations.
//Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.
//You need to count and return the number of maximum integers in the matrix after performing all the operations.
//Example 1:
//Input:
//m = 3, n = 3
//operations = [[2,2],[3,3]]
//Output: 4
//Explanation:
//Initially, M =
//[[0, 0, 0],
// [0, 0, 0],
// [0, 0, 0]]
//After performing [2,2], M =
//[[1, 1, 0],
// [1, 1, 0],
// [0, 0, 0]]
//After performing [3,3], M =
//[[2, 2, 1],
// [2, 2, 1],
// [1, 1, 1]]
//So the maximum integer in M is 2, and there are four of it in M. So return 4.
//Note:
//The range of m and n is [1,40000].
//The range of a is [1,m], and the range of b is [1,n].
//The range of operations size won't exceed 10,000.
//func maxCount(m int, n int, ops [][]int) int {
//}
// Time Is Money
|
package main
import (
"strings"
"fmt"
"strconv"
)
//strings strconv基本用法
func main() {
str := " hello world abc "
result := strings.Replace(str, "world", "you", 1)
fmt.Println("replace:", result)
count := strings.Count(str, "l")
fmt.Println("count:", count)
result = strings.Repeat(str, 3)
fmt.Println("repeat:", result)
result = strings.ToLower(str)
fmt.Println("tolower:", result)
result = strings.ToUpper(str)
fmt.Println("toUpper", result)
result = strings.TrimSpace(str)
fmt.Println("trimspace", result)
result = strings.Trim(str, " \n\r")
fmt.Println("trim:", result)
result = strings.TrimLeft(str, " \n\r")
fmt.Println("trimLeft:", result)
result = strings.TrimRight(str, " ab")
fmt.Println("trimRight:", result)
splitResult := strings.Fields(str)
for i := 0; i < len(splitResult); i++ {
fmt.Println("fields:", splitResult[i])
}
splitResult = strings.Split(str, "l")
for i := 0; i < len(splitResult); i++ {
fmt.Println("split:", splitResult[i])
}
str2 := strings.Join(splitResult, "l")
fmt.Println("join:", str2)
str2 = strconv.Itoa(1000)
fmt.Println("itoa:", str2)
number, err := strconv.Atoi(str2)
if err != nil {
fmt.Println("cannot convert to int", err)
return
}
fmt.Println("atoi:", number)
}
|
package stellar
import (
"net/http"
"time"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/keypair"
"github.com/stellar/go/services/bifrost/common"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
)
// NewAccountXLMBalance is amount of lumens sent to new accounts
const NewAccountXLMBalance = "41"
func (ac *AccountConfigurator) Start() error {
ac.log = common.CreateLogger("StellarAccountConfigurator")
ac.log.Info("StellarAccountConfigurator starting")
kp, err := keypair.Parse(ac.IssuerPublicKey)
if err != nil || (err == nil && ac.IssuerPublicKey[0] != 'G') {
err = errors.Wrap(err, "Invalid IssuerPublicKey")
ac.log.Error(err)
return err
}
kp, err = keypair.Parse(ac.SignerSecretKey)
if err != nil || (err == nil && ac.SignerSecretKey[0] != 'S') {
err = errors.Wrap(err, "Invalid SignerSecretKey")
ac.log.Error(err)
return err
}
ac.signerPublicKey = kp.Address()
root, err := ac.Horizon.Root()
if err != nil {
err = errors.Wrap(err, "Error loading Horizon root")
ac.log.Error(err)
return err
}
if root.NetworkPassphrase != ac.NetworkPassphrase {
return errors.Errorf("Invalid network passphrase (have=%s, want=%s)", root.NetworkPassphrase, ac.NetworkPassphrase)
}
err = ac.updateSequence()
if err != nil {
err = errors.Wrap(err, "Error loading issuer sequence number")
ac.log.Error(err)
return err
}
go ac.logStats()
return nil
}
func (ac *AccountConfigurator) logStats() {
for {
ac.log.WithField("currently_processing", ac.processingCount).Info("Stats")
time.Sleep(15 * time.Second)
}
}
// ConfigureAccount configures a new account that participated in ICO.
// * First it creates a new account.
// * Once a trusline exists, it credits it with received number of ETH or BTC.
func (ac *AccountConfigurator) ConfigureAccount(destination, assetCode, amount string) {
localLog := ac.log.WithFields(log.F{
"destination": destination,
"assetCode": assetCode,
"amount": amount,
})
localLog.Info("Configuring Stellar account")
ac.processingCountMutex.Lock()
ac.processingCount++
ac.processingCountMutex.Unlock()
defer func() {
ac.processingCountMutex.Lock()
ac.processingCount--
ac.processingCountMutex.Unlock()
}()
// Check if account exists. If it is, skip creating it.
for {
_, exists, err := ac.getAccount(destination)
if err != nil {
localLog.WithField("err", err).Error("Error loading account from Horizon")
time.Sleep(2 * time.Second)
continue
}
if exists {
break
}
localLog.WithField("destination", destination).Info("Creating Stellar account")
err = ac.createAccount(destination)
if err != nil {
localLog.WithField("err", err).Error("Error creating Stellar account")
time.Sleep(2 * time.Second)
continue
}
break
}
if ac.OnAccountCreated != nil {
ac.OnAccountCreated(destination)
}
// Wait for trust line to be created...
for {
account, err := ac.Horizon.LoadAccount(destination)
if err != nil {
localLog.WithField("err", err).Error("Error loading account to check trustline")
time.Sleep(2 * time.Second)
continue
}
if ac.trustlineExists(account, assetCode) {
break
}
time.Sleep(2 * time.Second)
}
localLog.Info("Trust line found")
// When trustline found check if needs to authorize, then send token
if ac.NeedsAuthorize {
localLog.Info("Authorizing trust line")
err := ac.allowTrust(destination, assetCode, ac.TokenAssetCode)
if err != nil {
localLog.WithField("err", err).Error("Error authorizing trust line")
}
}
localLog.Info("Sending token")
err := ac.sendToken(destination, assetCode, amount)
if err != nil {
localLog.WithField("err", err).Error("Error sending asset to account")
return
}
if ac.OnAccountCredited != nil {
ac.OnAccountCredited(destination, assetCode, amount)
}
localLog.Info("Account successully configured")
}
func (ac *AccountConfigurator) getAccount(account string) (horizon.Account, bool, error) {
var hAccount horizon.Account
hAccount, err := ac.Horizon.LoadAccount(account)
if err != nil {
if err, ok := err.(*horizon.Error); ok && err.Response.StatusCode == http.StatusNotFound {
return hAccount, false, nil
}
return hAccount, false, err
}
return hAccount, true, nil
}
func (ac *AccountConfigurator) trustlineExists(account horizon.Account, assetCode string) bool {
for _, balance := range account.Balances {
if balance.Asset.Issuer == ac.IssuerPublicKey && balance.Asset.Code == assetCode {
return true
}
}
return false
}
|
package main
import (
"flag"
"fmt"
"time"
"github.com/qixin1991/grpc-go-service-discover/sdk"
"strconv"
"github.com/qixin1991/grpc-go-service-discover/rpc"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
var (
serv = flag.String("service", "hello_service", "service name")
reg = flag.String("reg", "http://172.20.9.101:2379,http://172.20.9.103:2379,http://172.20.9.105:2379", "register etcd address")
)
var prefix = "etcd3_naming"
func main() {
flag.Parse()
r := sdk.NewResolver(prefix, *serv)
b := grpc.RoundRobin(r)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
conn, err := grpc.DialContext(ctx, *reg, grpc.WithInsecure(), grpc.WithBalancer(b))
if err != nil {
panic(err)
}
ticker := time.NewTicker(1 * time.Second)
for t := range ticker.C {
client := rpc.NewGreeterClient(conn)
resp, err := client.SayHello(context.Background(), &rpc.HelloRequest{Name: "world " + strconv.Itoa(t.Second())})
if err == nil {
fmt.Printf("%v: Reply is %s\n", t, resp.Message)
}
resp2, err2 := client.SayHelloAgain(context.Background(), &rpc.HelloRequest{Name: "world " + strconv.Itoa(t.Second())})
if err2 == nil {
fmt.Printf("%v: Reply Again is %s\n", t, resp2.Message)
} else {
fmt.Println(err2)
}
}
}
|
package model
import (
"fmt"
"time"
"github.com/rodrigo-brito/ninjabot/pkg/series"
)
type SideType string
type OrderType string
type OrderStatusType string
var (
SideTypeBuy SideType = "BUY"
SideTypeSell SideType = "SELL"
OrderTypeLimit OrderType = "LIMIT"
OrderTypeMarket OrderType = "MARKET"
OrderTypeLimitMaker OrderType = "LIMIT_MAKER"
OrderTypeStopLoss OrderType = "STOP_LOSS"
OrderTypeStopLossLimit OrderType = "STOP_LOSS_LIMIT"
OrderTypeTakeProfit OrderType = "TAKE_PROFIT"
OrderTypeTakeProfitLimit OrderType = "TAKE_PROFIT_LIMIT"
OrderStatusTypeNew OrderStatusType = "NEW"
OrderStatusTypePartiallyFilled OrderStatusType = "PARTIALLY_FILLED"
OrderStatusTypeFilled OrderStatusType = "FILLED"
OrderStatusTypeCanceled OrderStatusType = "CANCELED"
OrderStatusTypePendingCancel OrderStatusType = "PENDING_CANCEL"
OrderStatusTypeRejected OrderStatusType = "REJECTED"
OrderStatusTypeExpired OrderStatusType = "EXPIRED"
)
type Settings struct {
Pairs []string
}
type Balance struct {
Tick string
Free float64
Lock float64
}
type Dataframe struct {
Pair string
Close series.Series
Open series.Series
High series.Series
Low series.Series
Volume series.Series
Time []time.Time
LastUpdate time.Time
// Custom user metadata
Metadata map[string]series.Series
}
type Candle struct {
Symbol string
Time time.Time
Open float64
Close float64
Low float64
High float64
Volume float64
Trades int64
Complete bool
}
func (c Candle) ToSlice() []string {
return []string{
fmt.Sprintf("%d", c.Time.Unix()),
fmt.Sprintf("%f", c.Open),
fmt.Sprintf("%f", c.Close),
fmt.Sprintf("%f", c.Low),
fmt.Sprintf("%f", c.High),
fmt.Sprintf("%.1f", c.Volume),
fmt.Sprintf("%d", c.Trades),
}
}
type Order struct {
ID int64
ExchangeID int64
Date time.Time
Symbol string
Side SideType
Type OrderType
Status OrderStatusType
Price float64
Quantity float64
// OCO Orders only
Stop *float64
GroupID *int64
// Internal use (Plot)
Profit float64
}
func (o Order) String() string {
return fmt.Sprintf("%s %s | ID: %d, Type: %s - %f x $%f (%s)",
o.Side, o.Symbol, o.ID, o.Type, o.Quantity, o.Price, o.Status)
}
type Account struct {
Balances []Balance
}
func (a Account) Balance(tick string) Balance {
for _, balance := range a.Balances {
if balance.Tick == tick {
return balance
}
}
return Balance{}
}
|
package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type SampleResource struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec SampleResourceSpec `json:"spec"`
}
type SampleResourceSpec struct {
Time string `json:"time"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type SampleResourceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []SampleResource `json:"items"`
}
|
package paperswithcode_go
import (
"net/http"
"regexp"
"strings"
"time"
"github.com/codingpot/paperswithcode-go/v2/internal/transport"
)
const (
BaseURL = "https://paperswithcode.com/api/v1"
)
var whiteSpaceRegexp = regexp.MustCompile(`\s+`)
// ClientOption can be used to swap the default http client or swap the API key
type ClientOption func(*Client)
// WithAPIToken sets the client API token.
func WithAPIToken(apiToken string) ClientOption {
return func(client *Client) {
client.apiToken = apiToken
client.httpClient.Transport = transport.NewTransportWithAuthHeader(apiToken)
}
}
// NewClient creates a Client object.
func NewClient(opts ...ClientOption) *Client {
defaultClient := &Client{
baseURL: BaseURL,
httpClient: &http.Client{
Timeout: time.Minute,
},
}
for _, opt := range opts {
opt(defaultClient)
}
return defaultClient
}
type Client struct {
baseURL string
httpClient *http.Client
apiToken string
}
// GetPaperIDFromPaperTitle generates a paper ID from paper title.
// WARNING: This function does not cover all cases.
func GetPaperIDFromPaperTitle(paperTitle string) string {
return strings.ToLower(whiteSpaceRegexp.ReplaceAllString(paperTitle, "-"))
}
|
package harness
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"syscall"
"time"
)
const (
sdCfgDir = "sd_configs"
)
type Harness struct {
testDirectory string
}
func (h *Harness) GetSdCfgDir() string {
return filepath.Join(h.testDirectory, sdCfgDir)
}
func NewHarness(testDirectory string, rmIfPresent bool, scrapeInterval time.Duration, benchListenAddr, promListenAddr string) *Harness {
SetupTestDir(testDirectory, rmIfPresent)
h := &Harness{testDirectory}
h.setupPrometheusConfig(scrapeInterval, benchListenAddr, promListenAddr)
return h
}
func SetupTestDir(dir string, rm bool) {
_, err := os.Open(dir)
if os.IsNotExist(err) {
} else if err != nil {
log.Fatalf("error opening test dir '%s': %v", dir, err)
} else if rm {
rmcmd := exec.Command("rm", "-rf", dir)
if err := rmcmd.Run(); err != nil {
log.Fatalf("error deleting test dir '%s': %v", dir, err)
}
} else {
log.Fatalf("error: test dir '%s' exists but I wasn't asked to delete it", dir)
}
if err := os.Mkdir(dir, 0700); err != nil {
log.Fatalf("error creating test dir '%s': %v", dir, err)
}
}
func (h *Harness) setupPrometheusConfig(scrapeInterval time.Duration, benchListenAddr, promListenAddr string) {
cfgstr := fmt.Sprintf(`global:
scrape_configs:
- job_name: 'prometheus'
scrape_interval: '1s'
static_configs:
- targets: [%q]
- job_name: 'prombench'
scrape_interval: '1s'
static_configs:
- targets: [%q]
- job_name: 'test'
scrape_interval: '%s'
file_sd_configs:
- files:
- '%s/*.json'`, promListenAddr, benchListenAddr, scrapeInterval, sdCfgDir)
cfgfilename := filepath.Join(h.testDirectory, "prometheus.yml")
if err := ioutil.WriteFile(cfgfilename, []byte(cfgstr), 0600); err != nil {
log.Fatalf("unable to write config file '%s': %v", cfgfilename, err)
}
if err := os.Mkdir(h.GetSdCfgDir(), 0700); err != nil && !os.IsExist(err) {
log.Fatalf("unable to create sd_config dir '%s': %v", h.GetSdCfgDir(), err)
}
// TODO clean out sd_config dir
}
func (h *Harness) StartPrometheus(ctx context.Context, prompath string, promargs []string) context.CancelFunc {
vercmd := exec.Command(prompath, "-version")
output, err := vercmd.Output()
if err != nil {
log.Fatalf("Prometheus returned %v", err)
}
log.Printf("Prometheus -version output: %s", string(output))
myctx, cancel := context.WithCancel(ctx)
cmd := exec.CommandContext(myctx, prompath, promargs...)
cmd.Dir = h.testDirectory
done := make(chan struct{})
promlog := filepath.Join(h.testDirectory, "prometheus.log")
logfile, err := os.Create(promlog)
if err != nil {
log.Fatalf("unable to open log file '%s' for writing: %v", promlog, err)
}
cmd.Stdout = logfile
cmd.Stderr = logfile
go func() {
log.Printf("running Prometheus in dir %q: %s %v", cmd.Dir, prompath, promargs)
if err := cmd.Run(); err != nil {
log.Printf("Prometheus returned %v, see log %q", err, promlog)
} else {
log.Printf("Prometheus exited, see log %q", promlog)
}
done <- struct{}{}
}()
return func() {
cmd.Process.Signal(syscall.SIGTERM)
timer := time.NewTimer(30 * time.Second)
select {
case <-timer.C:
cancel()
<-done
case <-done:
}
}
}
|
package controllers
import (
"net/http"
"strconv"
"github.com/insisthzr/echo-test/cookbook/twitter/models"
"github.com/insisthzr/echo-test/cookbook/twitter/utils"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"gopkg.in/mgo.v2/bson"
)
func CreatePost(c echo.Context) error {
userID := utils.UserIDFromToken(c.Get("user").(*jwt.Token))
post := new(models.Post)
err := c.Bind(post)
if err != nil {
return err
}
post.ID = bson.NewObjectId()
post.From = userID
if post.To == "" || post.Message == "" {
return c.String(http.StatusBadRequest, "invalid to or message")
}
err = post.AddPost()
if err != nil {
return err
}
return c.JSON(http.StatusCreated, post)
}
func FetchPost(c echo.Context) error {
to := utils.UserIDFromToken(c.Get("user").(*jwt.Token))
var err error
pageStr := c.QueryParam("page")
limitStr := c.QueryParam("limit")
page := 0
limit := 100 //max limit
if len(pageStr) > 0 {
page, err = strconv.Atoi(pageStr)
if err != nil {
return c.String(http.StatusBadRequest, err.Error())
}
}
if len(limitStr) > 0 {
limit, err = strconv.Atoi(limitStr)
if err != nil {
return c.String(http.StatusBadRequest, err.Error())
}
}
if page < 0 {
page = 0
}
if limit < 0 {
limit = 100
}
posts, err := models.FindPosts(to, page, limit)
if err != nil {
return err
}
return c.JSON(http.StatusOK, posts)
}
|
package main
import (
"os"
"anime/controllers"
"strconv"
"fmt"
"net/http"
"github.com/go-martini/martini"
"bufio"
)
func main() {
m := martini.Classic()
canWork := false
reader := bufio.NewReader(os.Stdin)
fmt.Println("ALLOW ACESS? [y/n]")
//ДА да, именно так в го пишется while(true)
flag := true
for flag {
char, _, err := reader.ReadRune()
if err != nil {
}
switch char {
case 'y':
fmt.Println("ACESS ALLOWED")
canWork = true
flag = false
break
case 'n':
fmt.Println("ACESS DENIED")
canWork = false
flag = false
break
}
}
//Переключение режима работы
m.Get("/switch", func(res http.ResponseWriter, req *http.Request) string {
requrl := req.URL.Query()
pass := requrl.Get("pass")
if pass == "kek" {
canWork = !canWork
if canWork {
fmt.Println("__________________________________________")
fmt.Println("SERVER IS ONLINE NOW")
fmt.Println("__________________________________________")
return "SWITCHED ONLINE"
} else {
fmt.Println("__________________________________________")
fmt.Println("SERVER IS OFFLINE NOW")
fmt.Println("__________________________________________")
return "SWITCHED OFFLINE"
}
} else {
return "INCORRECT PASSWORD"
}
})
//Обращение к табличке с результатами
m.Get("/table", func(res http.ResponseWriter) string {
if canWork {
res.WriteHeader(200)
return controllers.ShowUsersTable()
} else {
res.WriteHeader(1488)
return "SERVER OFFLINE"
}
})
//Увеличение счетчика у пользователя
m.Get("/update", func(res http.ResponseWriter, req *http.Request) string {
if canWork {
requrl := req.URL.Query()
userid := requrl.Get("id")
count, err := strconv.Atoi(requrl.Get("count"))
if err != nil {
fmt.Println(err)
}
controllers.Update(userid, count)
res.WriteHeader(200)
fmt.Println("__________________________________________")
fmt.Println("UPDATED id:", userid, " count:", count)
fmt.Println("__________________________________________")
return "UPDATED:" + userid
} else {
res.WriteHeader(1488)
fmt.Println("__________________________________________")
fmt.Println("ACESS DENIED")
fmt.Println("__________________________________________")
return "SERVER OFFLINE"
}
})
//Удаление пользователя
m.Get("/delete", func(res http.ResponseWriter, req *http.Request) string {
if canWork {
requrl := req.URL.Query()
userid := requrl.Get("id")
controllers.Delete(userid)
res.WriteHeader(200)
fmt.Println("__________________________________________")
fmt.Println("DELETED id:", userid)
fmt.Println("__________________________________________")
return "DELETED:" + userid
} else {
res.WriteHeader(1488)
fmt.Println("__________________________________________")
fmt.Println("ACESS DENIED")
fmt.Println("__________________________________________")
return "SERVER OFFLINE"
}
})
m.Run()
}
|
package helpers
import (
"fmt"
"os"
"strconv"
gomail "gopkg.in/gomail.v2"
)
// MailConfig to hold mail data
type MailConfig struct {
To string
Subject string
Body string
}
// SendHTMLMail to someone
func (mc *MailConfig) SendHTMLMail() {
port, _ := strconv.Atoi(os.Getenv("MAIL_PORT"))
m := gomail.NewMessage()
m.SetHeader("From", os.Getenv("MAIL_FROM"))
m.SetHeader("To", mc.To)
m.SetHeader("Subject", mc.Subject)
m.SetBody("text/html", mc.Body)
d := gomail.NewDialer(os.Getenv("MAIL_SMTP"), port, os.Getenv("MAIL_USERNAME"), os.Getenv("MAIL_PASSWORD"))
if err := d.DialAndSend(m); err != nil {
panic(err)
}
fmt.Println("Email sent to " + mc.To)
}
|
package deposits
import (
context "context"
"time"
)
type Usecase struct {
Repo DomainRepository
ContextTimeout time.Duration
}
func NewUsecase(repo DomainRepository, timeout time.Duration) *Usecase {
return &Usecase{
Repo: repo,
ContextTimeout: timeout,
}
}
func (u *Usecase) GetAll(ctx context.Context) ([]Domain, error) {
ctx, cancel := context.WithTimeout(ctx, u.ContextTimeout)
defer cancel()
return u.Repo.GetAll(ctx)
}
func (u *Usecase) GetByUserId(ctx context.Context, userId uint) (Domain, error) {
ctx, cancel := context.WithTimeout(ctx, u.ContextTimeout)
defer cancel()
return u.Repo.GetByUserId(ctx, userId)
}
func (u *Usecase) Create(ctx context.Context, d Domain) (Domain, error) {
ctx, cancel := context.WithTimeout(ctx, u.ContextTimeout)
defer cancel()
return u.Repo.Create(ctx, d)
}
func (u *Usecase) Update(ctx context.Context, userId uint, amount uint, usedAmount uint) (Domain, error) {
ctx, cancel := context.WithTimeout(ctx, u.ContextTimeout)
defer cancel()
return u.Repo.Update(ctx, userId, amount, usedAmount)
}
func (u *Usecase) TopUp(ctx context.Context, userId uint, amount uint) (Domain, error) {
ctx, cancel := context.WithTimeout(ctx, u.ContextTimeout)
defer cancel()
return u.Repo.TopUp(ctx, userId, amount)
}
|
package phrasecounter
import (
"reflect"
"testing"
)
func TestCountPhraseFrequency(t *testing.T) {
scenarios := []struct {
content string
expected map[string]int
}{
{"", map[string]int{}},
{"abc", map[string]int{}},
{"abc def ghi", map[string]int{"abc def ghi": 1}},
{"abc def ghi hij", map[string]int{"abc def ghi": 1, "def ghi hij": 1}},
{"abc def.ghi hij", map[string]int{}},
{"abc def ghi. abc def ghi.", map[string]int{"abc def ghi": 2}},
}
for _, s := range scenarios {
got := CountThreeWordPhraseFrequency(s.content)
if !reflect.DeepEqual(got, s.expected) {
t.Errorf("Did not get expected result for content '%v'. Expected %v, got %v\n",
s.content, s.expected, got)
}
}
}
|
package models
import (
"errors"
"mall/utils"
"strconv"
"github.com/astaxie/beego/orm"
)
// Comment 定义结构体
type Comment struct {
Id int `json:"id"`
Comment string `description:"描述" json:"comment"`
User *User `orm:"rel(fk)" json:"user"`
Monitor *Monitor `orm:"rel(fk)" json:"monitor"`
}
// TableName 自定义表名
func (c *Comment) TableName() string {
return "comments"
}
// AddComment 新增评论
func AddComment(c Comment) (id int64, err error) {
// 创建 ormer 实例
o := orm.NewOrm()
// 创建 comment 对象
comment := Comment{
Comment: c.Comment,
}
// 创建 profile 对象
profile := Profile{Id: c.User.Id}
// 创建 user 对象
user := User{Id: c.User.Id, Profile: c.User.Profile}
// 创建 monitor 对象
monitor := Monitor{Id: c.Monitor.Id}
if o.Read(&user) == nil {
user.Profile = &profile
comment.User = &user
}
if o.Read(&monitor) == nil {
comment.Monitor = &monitor
}
// 开启事务
o.Begin()
// 插入评论
id, err = o.Insert((&comment))
if err != nil {
// 回滚事务
err = o.Rollback()
}
// 提交事务
err = o.Commit()
return id, err
}
// UpdateComment 更新评论
func UpdateComment(uid int, uu *Comment) (a *Comment, err error) {
// 创建 ormer 实例
o := orm.NewOrm()
// 创建 comment 对象
comment := Comment{}
// 创建 user 对象
user := User{Id: uu.User.Id}
// 创建 monitor 对象
monitor := Monitor{Id: uu.Monitor.Id}
if o.Read(&user) == nil {
if o.Read(&monitor) == nil {
if uu.Comment != "" {
comment = Comment{Id: uid, Comment: uu.Comment, User: &user, Monitor: &monitor}
}
// 开启事务
err = o.Begin()
if _, err := o.Update(&comment); err != nil {
return nil, errors.New("修改失败")
}
if err != nil {
// 事务回退
err = o.Rollback()
} else {
// 提交事务
err = o.Commit()
}
return &comment, nil
}
}
return nil, err
}
// GetComment 查询单个评论
func GetComment(uid int) (c *Comment, err error) {
o := orm.NewOrm()
comment := &Comment{Id: uid}
err = o.Read(comment)
if comment.User != nil {
err = o.Read(comment.User)
}
if comment.Monitor != nil {
err = o.Read(comment.Monitor)
}
return comment, err
}
// GetAllComments 分页查询评论
func GetAllComments(p int, size int) (u utils.Page, err error) {
o := orm.NewOrm()
comment := new(Comment)
var comments []Comment
qs := o.QueryTable(comment)
count, _ := qs.Limit(-1).Count()
_, err = qs.RelatedSel().Limit(size).Offset((p - 1) * size).All(&comments)
for _, u := range comments {
if u.User != nil {
err = o.Read(u.User)
}
if u.Monitor != nil {
err = o.Read(u.Monitor)
}
}
c, _ := strconv.Atoi(strconv.FormatInt(count, 10))
return utils.Pagination(c, p, size, comments), err
}
// DeleteComment 删除指定评论
func DeleteComment(uid int) (b bool, err error) {
// 创建 oremer 实例
o := orm.NewOrm()
// 开启事务
err = o.Begin()
// 删除表
comment := Comment{Id: uid}
_, err = o.Delete(&comment)
if err != nil {
// 回滚事务
err = o.Rollback()
}
// 提交事务
err = o.Commit()
return b, err
}
// 注册 model
func init() {
orm.RegisterModel(new(Comment))
}
|
package routing
import "github.com/valyala/fasthttp"
func SetHeader(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json")
next(ctx)
})
}
|
/*
Create a function that will build a staircase using the underscore _ and hash # symbols. A positive value denotes the staircase's upward direction and downwards for a negative value.
Examples
staircase(3) ➞ "__#\n_##\n###"
__#
_##
###
staircase(7) ➞ "______#\n_____##\n____###\n___####\n__#####\n_######\n#######"
______#
_____##
____###
___####
__#####
_######
#######
staircase(2) ➞ "_#\n##"
_#
##
staircase(-8) ➞ "########\n_#######\n__######\n___#####\n____####\n_____###\n______##\n_______#"
########
_#######
__######
___#####
____####
_____###
______##
_______#
Notes
All inputs are either positive or negative values.
The string to be returned should be adjoined with the newline character \n.
You're expected to solve this challenge using a recursive approach.
You can read more on recursion (see Resources tab) if you aren't familiar with it or haven't fully understood the concept before taking this challenge.
If you think recursion is fun, you can find a collection of those challenges here.
A non-recursive version of this challenge can be found here.
*/
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
test(3, "__#\n_##\n###")
test(7, "______#\n_____##\n____###\n___####\n__#####\n_######\n#######")
test(2, "_#\n##")
test(-8, "########\n_#######\n__######\n___#####\n____####\n_____###\n______##\n_______#")
test(4, "___#\n__##\n_###\n####")
test(-12, "############\n_###########\n__##########\n___#########\n____########\n_____#######\n______######\n_______#####\n________####\n_________###\n__________##\n___________#")
test(11, "__________#\n_________##\n________###\n_______####\n______#####\n_____######\n____#######\n___########\n__#########\n_##########\n###########")
test(-6, "######\n_#####\n__####\n___###\n____##\n_____#")
test(0, "")
test(1, "_")
test(-1, "#")
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(n int, t string) {
s := staircase(n)
fmt.Printf("staircase=%d\n%s\n\n", n, s)
assert(s == t)
}
func staircase(n int) string {
w := new(bytes.Buffer)
switch {
case n == 1:
fmt.Fprintf(w, "_\n")
case n >= 0:
staircaser(w, n-1, 1, -1, 1)
default:
staircaser(w, 0, -n, 1, -1)
}
s := w.String()
if len(s) > 0 {
s = s[:len(s)-1]
}
return s
}
func staircaser(w io.Writer, u, h, du, dh int) {
if u < 0 || h <= 0 {
return
}
for i := 0; i < u; i++ {
fmt.Fprintf(w, "_")
}
for i := 0; i < h; i++ {
fmt.Fprintf(w, "#")
}
fmt.Fprintf(w, "\n")
staircaser(w, u+du, h+dh, du, dh)
}
|
package handlers
import (
"net/http"
"net/http/httptest"
"syscall"
"testing"
)
func TestShutdownHandler(t *testing.T) {
req, err := http.NewRequest("PUT", "/shutdown", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(ShutdownHandler)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
s := <-ShutdownChannel
if s != syscall.SIGTERM {
t.Fatalf("Shtudown Handler did not send SIGTERM")
}
}
|
package main
import (
"fmt"
"strconv"
)
func main() {
var n, k, x int
g := []int{1, 3, 4, 6, 4, 32, 4, 5, 40}
fmt.Scan(&n, &k)
fmt.Println(Potenza(n, k))
fmt.Println(Max(g))
fmt.Scan(&x)
fmt.Println(Taglio(x))
for i, v := range Occo(x) {
fmt.Println("numero", i, "è apparso", v, "volte")
}
//fmt.Println(Occo(x))
//Prova2()
}
func Potenza(n, k int) int {
if k == 0 {
return 1
} else {
for i := 1; i < k; i++ {
n *= n
}
return n
}
}
func Max(g []int) int {
var massimo int
minimo := 1000000
for i := 0; i < len(g); i++ {
if g[i] >= massimo {
massimo = g[i]
}
if g[i] <= minimo {
minimo = g[i]
}
}
fmt.Println(minimo)
return massimo
}
/*func Prova() {
var n int = 4
var a [n]int
for i := 0; i < n; i++ {
a[i] = i
}
fmt.Println(a)
}*/
func Prova2() {
var a [6]int
for _, v := range a {
v *= 2
}
fmt.Println(a)
}
func Taglio(n int) int {
var convtagliato, convtagliato2 string
conv := strconv.Itoa(n)
convtagliato = conv[1 : len(conv)-1]
convtagliato2 = conv[:1] + conv[len(conv)-1:len(conv)]
tagliato, _ := strconv.Atoi(convtagliato)
tagliato2, _ := strconv.Atoi(convtagliato2)
fmt.Println(tagliato2)
return tagliato
}
func Occo(n int) map[string]int {
oc := make(map[string]int)
conv := strconv.Itoa(n)
for _, v := range conv {
oc[string(v)]++
}
return oc
}
|
package backend
import (
"github.com/shirou/gopsutil/mem"
)
// MemoryUsage = Struct of Memory Usages
type MemoryUsage struct {
Virtual *mem.VirtualMemoryStat `json:"virtual"`
Swap *mem.SwapMemoryStat `json:"swap"`
}
// GetMemoryUsage = Get Memory Usage
func (s *Stats) GetMemoryUsage() *MemoryUsage {
MU := new(MemoryUsage)
var err error
// Virtual
MU.Virtual, err = mem.VirtualMemory()
if err != nil {
s.log.Errorf("Get Memory Virtual Failed! Error : %s", err.Error())
return nil
}
// Swap
MU.Swap, err = mem.SwapMemory()
if err != nil {
s.log.Errorf("Get Memory Swap Failed! Error : %s", err.Error())
return nil
}
return MU
}
|
package dorisloader
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
)
var (
Version = "1.0.0"
)
type Client struct {
c Doer // e.g. a net/*http.Client to use for requests
mu sync.RWMutex // guards the next block
feUrl string // fe node url info http://fehost:feport/
basicAuth bool // indicates whether to send HTTP Basic Auth credentials
basicAuthUsername string // username for HTTP Basic Auth
basicAuthPassword string // password for HTTP Basic Auth
headers http.Header // a list of default headers to add to each request
decoder Decoder
debug bool
}
func NewClient(feUrl string, options ...ClientOptionFunc) (*Client, error) {
// Set up the client
c := &Client{
c: http.DefaultClient,
feUrl: feUrl,
decoder: &DefaultDecoder{},
}
// Run the options on it
for _, option := range options {
if err := option(c); err != nil {
return nil, err
}
}
return c, nil
}
// Doer is an interface to perform HTTP requests.
// It can be used for mocking.
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
// ClientOptionFunc is a function that configures a Client.
// It is used in NewClient.
type ClientOptionFunc func(*Client) error
// SetHttpClient can be used to specify the http.Client to use when making
func SetHttpClient(httpClient Doer) ClientOptionFunc {
return func(c *Client) error {
if httpClient != nil {
c.c = httpClient
} else {
c.c = http.DefaultClient
}
return nil
}
}
// SetHttpClient can be used to specify the http.Client to use when making
func SetDebug(debug bool) ClientOptionFunc {
return func(c *Client) error {
c.debug = debug
return nil
}
}
// SetBasicAuth can be used to specify the HTTP Basic Auth credentials to
func SetBasicAuth(username, password string) ClientOptionFunc {
return func(c *Client) error {
c.basicAuthUsername = username
c.basicAuthPassword = password
c.basicAuth = c.basicAuthUsername != "" || c.basicAuthPassword != ""
return nil
}
}
// SetHeaders adds a list of default HTTP headers that will be added to
// each requests executed by PerformRequest.
func SetHeaders(headers http.Header) ClientOptionFunc {
return func(c *Client) error {
c.headers = headers
return nil
}
}
// PerformRequestOptions must be passed into PerformRequest.
type PerformRequestOptions struct {
Method string
Path string
Params url.Values
Body interface{}
ContentType string
IgnoreErrors []int
//Retrier Retrier
Headers http.Header
MaxResponseSize int64
}
// PerformRequest does a HTTP request.
// It returns a response (which might be nil) and an error on failure.
//
// Optionally, a list of HTTP error codes to ignore can be passed.
// This is necessary for services that expect e.g. HTTP status 404 as a
// valid outcome (Exists, IndicesExists, IndicesTypeExists).
func (c *Client) PerformRequest(ctx context.Context, opt PerformRequestOptions) (*Response, error) {
c.mu.RLock()
basicAuth := c.basicAuth
basicAuthUsername := c.basicAuthUsername
basicAuthPassword := c.basicAuthPassword
defaultHeaders := c.headers
c.mu.RUnlock()
var err error
var req *Request
var resp *Response
pathWithParams := opt.Path
bodyReader, err := handleGetBodyReader(opt.Headers, opt.Body, false)
if err != nil {
return nil, err
}
req, err = NewRequest(opt.Method, c.feUrl+pathWithParams, bodyReader)
if err != nil {
return nil, err
}
if basicAuth {
req.SetBasicAuth(basicAuthUsername, basicAuthPassword)
}
if opt.ContentType != "" {
req.Header.Set("Content-Type", opt.ContentType)
}
if len(opt.Headers) > 0 {
for key, value := range opt.Headers {
for _, v := range value {
req.Header.Add(key, v)
}
}
}
if len(defaultHeaders) > 0 {
for key, value := range defaultHeaders {
for _, v := range value {
req.Header.Add(key, v)
}
}
}
// Tracing
c.dumpRequest((*http.Request)(req))
// Get response
res, err := c.c.Do((*http.Request)(req).WithContext(ctx))
if res != nil && res.Body != nil {
defer res.Body.Close()
}
if IsContextErr(err) {
// Proceed, but don't mark the node as dead
return nil, err
}
if err != nil {
return nil, err
}
resp, err = c.newResponse(res)
if err != nil {
return nil, err
}
return resp, nil
}
// IsContextErr returns true if the error is from a context that was canceled or deadline exceeded
func IsContextErr(err error) bool {
if err == context.Canceled || err == context.DeadlineExceeded {
return true
}
// This happens e.g. on redirect errors, see https://golang.org/src/net/http/client_test.go#L329
if ue, ok := err.(*url.Error); ok {
if ue.Temporary() {
return true
}
// Use of an AWS Signing Transport can result in a wrapped url.Error
return IsContextErr(ue.Err)
}
return false
}
// newResponse creates a new response from the HTTP response.
func (c *Client) newResponse(res *http.Response) (*Response, error) {
r := &Response{
StatusCode: res.StatusCode,
Header: res.Header,
DeprecationWarnings: res.Header["Warning"],
}
if res.Body != nil {
body := io.Reader(res.Body)
slurp, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
// HEAD requests return a body but no content
if len(slurp) > 0 {
r.Body = json.RawMessage(slurp)
}
}
return r, nil
}
// dumpRequest dumps the given HTTP request to the trace log.
func (c *Client) dumpRequest(r *http.Request) {
if !c.debug {
return
}
out, err := httputil.DumpRequestOut(r, true)
if err == nil {
log.Println(string(out))
}
}
|
package validator
import (
"crypto/elliptic"
"crypto/rsa"
"testing"
"github.com/stretchr/testify/assert"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/oidc"
)
func TestIsCookieDomainValid(t *testing.T) {
testCases := []struct {
domain string
expected bool
}{
{"example.com", false},
{".example.com", false},
{"*.example.com", false},
{"authelia.com", false},
{"duckdns.org", true},
{".duckdns.org", true},
{"example.duckdns.org", false},
{"192.168.2.1", false},
{"localhost", true},
{"com", true},
{"randomnada", true},
}
for _, tc := range testCases {
name := "ShouldFail"
if tc.expected {
name = "ShouldPass"
}
t.Run(tc.domain, func(t *testing.T) {
t.Run(name, func(t *testing.T) {
assert.Equal(t, tc.expected, isCookieDomainAPublicSuffix(tc.domain))
})
})
}
}
func TestBuildStringFuncsMissingTests(t *testing.T) {
assert.Equal(t, "", buildJoinedString(".", ":", "'", nil))
assert.Equal(t, "'abc', '123'", strJoinComma("", []string{"abc", "123"}))
}
func TestSchemaJWKGetPropertiesMissingTests(t *testing.T) {
props, err := schemaJWKGetProperties(schema.JWK{Key: keyECDSAP224})
assert.NoError(t, err)
assert.Equal(t, oidc.KeyUseSignature, props.Use)
assert.Equal(t, "", props.Algorithm)
assert.Equal(t, elliptic.P224(), props.Curve)
assert.Equal(t, -1, props.Bits)
props, err = schemaJWKGetProperties(schema.JWK{Key: keyECDSAP224.Public()})
assert.NoError(t, err)
assert.Equal(t, oidc.KeyUseSignature, props.Use)
assert.Equal(t, "", props.Algorithm)
assert.Equal(t, elliptic.P224(), props.Curve)
assert.Equal(t, -1, props.Bits)
rsa := &rsa.PrivateKey{}
*rsa = *keyRSA2048
rsa.PublicKey.N = nil
props, err = schemaJWKGetProperties(schema.JWK{Key: rsa})
assert.NoError(t, err)
assert.Equal(t, oidc.KeyUseSignature, props.Use)
assert.Equal(t, oidc.SigningAlgRSAUsingSHA256, props.Algorithm)
assert.Equal(t, nil, props.Curve)
assert.Equal(t, 0, props.Bits)
}
func TestGetResponseObjectAlgFromKID(t *testing.T) {
c := &schema.IdentityProvidersOpenIDConnect{
IssuerPrivateKeys: []schema.JWK{
{KeyID: "abc", Algorithm: "EX256"},
{KeyID: "123", Algorithm: "EX512"},
},
}
assert.Equal(t, "EX256", getResponseObjectAlgFromKID(c, "abc", "not"))
assert.Equal(t, "EX512", getResponseObjectAlgFromKID(c, "123", "not"))
assert.Equal(t, "not", getResponseObjectAlgFromKID(c, "111111", "not"))
}
|
package util
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"cloud.google.com/go/compute/metadata"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"google.golang.org/api/googleapi"
"google.golang.org/api/run/v1"
secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)
var (
httpClient HTTPClient
serviceCallClient ServiceCallClient
)
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type ServiceCallClient interface {
Do(opts ...googleapi.CallOption) (*run.Service, error)
}
func init() {
httpClient = http.DefaultClient
}
func FetchURLByServiceName(ctx context.Context, name, region, projectID string) (string, error) {
c, err := run.NewService(ctx)
if err != nil {
return "", err
}
c.BasePath = fmt.Sprintf("https://%s-run.googleapis.com/", region)
return fetchServiceURL(
c.Namespaces.Services.Get(fmt.Sprintf("namespaces/%s/services/%s", projectID, name)))
}
func fetchServiceURL(serviceCallClient ServiceCallClient) (string, error) {
service, err := serviceCallClient.Do()
if err != nil {
return "", err
}
return service.Status.Url, nil
}
// check first env value of GOOGLE_CLOUD_PROJECT for local debug
func FetchProjectID() (string, error) {
projectID, isSet := os.LookupEnv("GOOGLE_CLOUD_PROJECT")
if isSet {
return projectID, nil
}
req, err := http.NewRequest(http.MethodGet,
"http://metadata.google.internal/computeMetadata/v1/project/project-id", nil)
if err != nil {
return "", err
}
req.Header.Add("Metadata-Flavor", "Google")
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}
func IsCloudRun() bool {
// There is no obvious way to detect whether the app is running on Clodu Run,
// so we speculate from env var which is automatically added by Cloud Run.
// ref. https://cloud.google.com/run/docs/reference/container-contract#env-vars
// Note: we can't use K_SERVICE or K_REVISION since both are also used in Cloud Functions.
return os.Getenv("K_CONFIGURATION") != ""
}
func GetIDToken(addr string) (string, error) {
serviceURL := fmt.Sprintf("https://%s", strings.Split(addr, ":")[0])
tokenURL := fmt.Sprintf("/instance/service-accounts/default/identity?audience=%s", serviceURL)
return metadata.Get(tokenURL)
}
func FetchSecretLatestVersion(ctx context.Context, name, projectID string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
client, err := secretmanager.NewClient(ctx)
if err != nil {
return "", fmt.Errorf("failed to create secretmanager client: %v", err)
}
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/latest", projectID, name),
}
resp, err := client.AccessSecretVersion(ctx, req)
if err != nil {
return "", fmt.Errorf("failed to access secret version: %v", err)
}
return string(resp.Payload.Data), nil
}
|
// Package hashdir contains methods for generating hashes of directories
package hashdir
import (
"crypto/md5"
"io"
"os"
"path/filepath"
"github.com/gobwas/glob"
)
// GenerateString creates a new hash for a given path. The path is walked and a hash is
// created based on all files found in the path. If a file matches one specified in
// the 'excludes' parameter it is not used to generate the hash.
func Generate(location string, excludes ...string) ([]byte, error) {
hash := md5.New()
globs := make(map[string]glob.Glob)
err := filepath.Walk(location, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
for _, exclude := range excludes {
gl, ok := globs[exclude]
if !ok {
gl, err = glob.Compile(exclude, os.PathSeparator)
if err != nil {
return err
}
globs[exclude] = gl
}
if gl.Match(info.Name()) || gl.Match(path) {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(hash, file); err != nil {
return err
}
return file.Close()
})
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
|
package main
import (
"fmt"
)
type movie struct {
name string
release int
}
func main() {
dark := movie{
name: "Dark",
release: 2017,
}
fmt.Println(dark)
}
|
/*
Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 cloudify
import (
rest "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify/rest"
)
// Tenant - information about cloudify tenant
type Tenant struct {
Name string `json:"name"`
Users int `json:"users"`
Groups int `json:"groups"`
}
// Tenants - cloudify response with tenants list
type Tenants struct {
rest.BaseMessage
Metadata rest.Metadata `json:"metadata"`
Items []Tenant `json:"items"`
}
// GetTenants - get tenants list filtered by params
func (cl *Client) GetTenants(params map[string]string) (*Tenants, error) {
var tenants Tenants
values := cl.stringMapToURLValue(params)
err := cl.Get("tenants?"+values.Encode(), &tenants)
if err != nil {
return nil, err
}
return &tenants, nil
}
|
/*
This file run server web server app.
Author: Igor Kuznetsov
Email: me@swe-notes.ru
(c) Copyright by Igor Kuznetsov.
*/
package main
import (
"github.com/gorilla/websocket"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/streadway/amqp"
"net/http"
"os"
"simple-tracking/backend/handlers"
"simple-tracking/backend/models"
)
var (
config Config
)
func main() {
var (
err error
)
e := echo.New()
e.Use(middleware.Logger())
e.Pre(middleware.RemoveTrailingSlash())
e.Use(middleware.CORS())
if len(os.Args) == 2 {
if err := config.Load(os.Args[1]); err != nil {
e.Logger.Fatal(err)
}
} else {
e.Logger.Fatal("Не задан файл конфигурации")
}
e.Logger.SetLevel(config.GetLogLever())
h := handlers.Handler{
BrokerCfg: config.Broker,
Upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
}
h.BrokerConn, err = amqp.Dial(config.Broker.Conn)
if err != nil {
e.Logger.Fatalf("Ошибка соединения с RabbitMQ: %v", err)
}
defer h.BrokerConn.Close()
h.ErrChan = h.BrokerConn.NotifyClose(make(chan *amqp.Error))
if h.DB, err = models.NewDataStore(config.DbConn); err != nil {
e.Logger.Fatal(err)
}
e.GET("/ws", h.GeoWebsocket)
api := e.Group("/api")
api.GET("/last-positions", h.LastPosition)
api.GET("/tracks/:client", h.Track)
api.GET("/geo-objects", h.GeoObjects)
api.POST("/geo-objects", h.AddObject)
api.GET("/vehicle-dict", h.GetVehicles)
api.POST("/vehicle-dict", h.AddVehicle)
report := api.Group("/report")
report.GET("/object-dist/:client", h.ReportObjectDist)
e.Logger.Fatal(e.Start(config.Addr))
}
|
package download
import (
"context"
"fmt"
"io"
"net/http"
)
type (
Option struct {
Headers map[string]string
}
)
func Download(
ctx context.Context, client *http.Client, uri string, option Option,
) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, "GET", uri, nil)
if err != nil {
return nil, err
}
header := http.Header{}
for k, v := range option.Headers {
header.Add(k, v)
}
req.Header = header
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
resp.Body.Close()
return nil, fmt.Errorf("status code = %d >= 400", resp.StatusCode)
}
return resp.Body, nil
}
|
package model
type InstallationData struct {
Email string `json:"email"`
Name string `json:"name"`
EventList []EventList `json:"events"`
}
|
package form
import (
"bytes"
"github.com/astaxie/beego/logs"
"strings"
"text/template"
)
type SwitchInput struct {
Name string
Label string
SwitchText string //属性lay-text可自定义开关两种状态的文本: ON|OFF 开|关
Option SelectOption
}
func (c *SwitchInput) String() string {
html := `<input type="checkbox" name="{{.Name}}" value="{{.Option.Value}}"`
html += `title="{{.Option.Title}}" {{if .Option.Checked}}checked=""{{end}}`
html += `{{if .Option.Disabled}}disabled=""{{end}} lay-skin="switch" {{if .SwitchText}}lay-text="{{.SwitchText}}"{{else}}lay-text="ON|OFF"{{end}}>`
var buf bytes.Buffer
tpl, err := template.New("checkbox").Parse(html)
if err != nil {
logs.Error(err)
return buf.String()
}
err = tpl.Execute(&buf, c)
if err != nil {
logs.Error(err)
}
return buf.String()
}
func (c *SwitchInput) ReadFromOptions(options ...string) {
for _, option := range options {
if option != "" {
t := strings.SplitN(option, ":", 2)
if t[0] == "text" && len(t) == 2 {
c.SwitchText = t[1]
}
}
}
if c.Name == "" {
c.Name = "Undefined"
}
}
|
package main
func main() {
var a string = "string"
var b []int
b = append(b, 0)
var c [5]int
var r int
r = len(c)
}
|
package worker
import (
"github.com/bearname/videohost/internal/common/caching"
"github.com/bearname/videohost/internal/common/db"
"github.com/bearname/videohost/internal/thumbgenerator/app/provider"
"github.com/bearname/videohost/internal/thumbgenerator/app/subscriber"
"github.com/bearname/videohost/internal/thumbgenerator/domain/model"
log "github.com/sirupsen/logrus"
"sync"
)
const WorkersCount = 3
func PoolOfWorker(stopChan chan struct{}, db db.Connector, cache caching.Cache) *sync.WaitGroup {
var waitGroup sync.WaitGroup
tasksChan := provider.RunTaskProvider(stopChan, db)
for i := 0; i < WorkersCount; i++ {
waitGroup.Add(1)
go func(i int) {
worker(tasksChan, db, cache, i)
waitGroup.Done()
}(i)
}
return &waitGroup
}
func worker(tasksChan <-chan *model.Task, db db.Connector, cache caching.Cache, name int) {
log.Printf("start worker %v\n", name)
for task := range tasksChan {
log.Printf("start processing video with id %v on worker %v\n", task.Id, name)
subscriber.HandleTask(task, db, cache)
log.Printf("end processing video with id %v on worker %v\n", task.Id, name)
}
log.Printf("stop worker %v\n", name)
}
|
package service
import "time"
type MessageStatus struct {
Message Message
Error error
}
type Message struct {
ID string
Account Account
Application Application
CreatedAt time.Time
Content string
Emojis []Emoji
InReplyToID string
IsReblog bool
Tags []Tag
Visibility string
}
type Account struct {
ID string
Acct string
DisplayName string
Username string
}
type Application struct {
ID string
}
type Emoji struct {
Shortcode string
}
type Tag struct {
Name string
}
|
package main_test
import (
. "github.com/dcarley/swt-wifi-login"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"net/http"
"testing"
"github.com/onsi/gomega/ghttp"
)
func TestSwtWifiLogin(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SwtWifiLogin Suite")
}
var _ = Describe("SwtWifiLogin", func() {
const (
Username = "myuser"
Password = "mypass"
PasswordHash = "e727d1464ae12436e899a726da5b2f11d8381b26" // `echo -n "<Password>" | shasum -a1`
BaseURL = "http://localhost/cws"
)
Describe("LoginRequest", func() {
var req *http.Request
BeforeEach(func() {
var err error
req, err = LoginRequest(Username, Password, BaseURL)
Expect(err).ToNot(HaveOccurred())
})
It("has correct base URL", func() {
Expect(req.URL.String()).To(HavePrefix(BaseURL))
})
It("has a GET method", func() {
Expect(req.Method).To(Equal("GET"))
})
It("sets rq query param", func() {
Expect(req.URL.Query().Get("rq")).To(Equal("login"))
})
It("sets username query param", func() {
Expect(req.URL.Query().Get("username")).To(Equal(Username))
})
It("sets password query param as hash", func() {
Expect(req.URL.Query().Get("password")).To(Equal(PasswordHash))
})
})
Describe("Login", func() {
var (
client *http.Client
server *ghttp.Server
request *http.Request
responseCode int
responseBody string
)
BeforeEach(func() {
client = &http.Client{}
server = ghttp.NewServer()
var err error
request, err = LoginRequest(Username, Password, server.URL()+"/")
Expect(err).ToNot(HaveOccurred())
headers := http.Header{}
headers.Set("Content-type", "application/json")
server.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", request.URL.Path),
ghttp.RespondWithPtr(&responseCode, &responseBody, headers),
),
)
})
AfterEach(func() {
server.Close()
})
Context("200 status code and 0 errorcode", func() {
BeforeEach(func() {
responseCode = http.StatusOK
responseBody = `{"errorcode": 0}`
})
It("returns no errors", func() {
Expect(Login(request, client)).To(Succeed())
})
})
Context("200 status code and non-0 errorcode", func() {
BeforeEach(func() {
responseCode = http.StatusOK
responseBody = `{"errorcode": 101}`
})
It("returns an error with status code and response body", func() {
Expect(
Login(request, client),
).To(
MatchError(LoginError{responseCode, responseBody}),
)
})
})
Context("non-200 status code and unparseable response body", func() {
BeforeEach(func() {
responseCode = http.StatusServiceUnavailable
responseBody = `there was a problem`
})
It("returns an error with status code and response body", func() {
Expect(
Login(request, client),
).To(
MatchError(LoginError{responseCode, responseBody}),
)
})
})
Context("200 status code and unparseable response body", func() {
BeforeEach(func() {
responseCode = http.StatusOK
responseBody = `there was a problem`
})
It("returns an error with JSON decoder details", func() {
Expect(
Login(request, client),
).To(
MatchError(ContainSubstring("invalid character")),
)
})
})
})
})
|
package mod_test
import (
"net/http"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/prometheus/common/expfmt"
"github.com/robustirc/bridge/robustsession"
"github.com/robustirc/internal/health"
"github.com/robustirc/robustirc/internal/localnet"
"github.com/robustirc/robustirc/internal/robust"
)
func TestMessageOfDeath(t *testing.T) {
tempdir := t.TempDir()
l, err := localnet.NewLocalnet(-1, tempdir)
if err != nil {
t.Fatalf("Could not start local RobustIRC network: %v", err)
}
defer l.Kill(true)
l.EnablePanicCommand = "1"
// For each of the nodes, start a goroutine that verifies that the node crashes, then start it again
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
cmd, tempdir, addr := l.StartIRCServer(i == 0)
wg.Add(1)
go func(cmd *exec.Cmd, tempdir string, addr string) {
defer wg.Done()
terminated := make(chan error)
skipped := make(chan bool)
go func() {
terminated <- cmd.Wait()
}()
go func() {
// Poll messages of death counter.
parser := &expfmt.TextParser{}
for {
time.Sleep(50 * time.Millisecond)
req, err := http.NewRequest("GET", addr+"metrics", nil)
if err != nil {
continue
}
resp, err := l.Httpclient.Do(req)
if err != nil {
continue
}
if resp.StatusCode != http.StatusOK {
continue
}
metrics, err := parser.TextToMetricFamilies(resp.Body)
if err != nil {
continue
}
applied, ok := metrics["applied_messages"]
if !ok {
continue
}
for _, m := range applied.GetMetric() {
for _, labelpair := range m.GetLabel() {
if labelpair.GetName() == "type" &&
labelpair.GetValue() == robust.Type(robust.MessageOfDeath).String() {
if m.GetCounter().GetValue() > 0 {
skipped <- true
}
}
}
}
}
}()
// Wait for the server to either crash or skip a message of death.
select {
case <-terminated:
t.Logf("Node %s terminated (as expected)", addr)
case <-skipped:
t.Logf("Node %s skipped message of death", addr)
}
// Run restart.sh for that node.
rcmd := exec.Command(filepath.Join(tempdir, "restart.sh"))
if err := rcmd.Start(); err != nil {
t.Errorf("Cannot restart node: %v", err)
return
}
l.RecordResource("pid", strconv.Itoa(rcmd.Process.Pid))
// Ensure the node comes back up.
started := time.Now()
const timeout = 20 * time.Second
for time.Since(started) < timeout {
if _, err := health.GetServerStatus(addr, l.NetworkPassword); err != nil {
t.Logf("Node %s unhealthy: %v", addr, err)
time.Sleep(1 * time.Second)
continue
}
t.Logf("Node %s became healthy", addr)
return
}
t.Errorf("Node %s did not become healthy within %v", addr, timeout)
}(cmd, tempdir, addr)
}
// All servers are running. Wait for the network to become healthy, i.e. all
// servers agreeing on the election status.
healthy := false
for try := 0; try < 10; try++ {
if l.Healthy() {
healthy = true
break
}
time.Sleep(1 * time.Second)
}
if !healthy {
t.Fatalf("Expected healthy network, but not all nodes are healthy")
}
// Connect and send the PANIC message.
session, err := robustsession.Create(strings.Join(l.Servers(), ","), filepath.Join(tempdir, "cert.pem"))
if err != nil {
t.Fatalf("Could not create robustsession: %v", err)
}
var (
mu sync.Mutex
state = "no-join-yet"
)
foundjoin := make(chan bool)
go func() {
for msg := range session.Messages {
if !strings.HasPrefix(msg, ":mod!1@") ||
!strings.HasSuffix(msg, " JOIN #mod") {
continue
}
mu.Lock()
if state == "no-join-yet" {
t.Errorf("Found JOIN too early")
}
foundjoin <- true
mu.Unlock()
}
}()
go func() {
for err := range session.Errors {
t.Errorf("RobustSession error: %v", err)
}
}()
session.PostMessage("NICK mod")
session.PostMessage("USER 1 2 3 4")
session.PostMessage("PANIC")
t.Logf("Message of death sent")
wg.Wait()
healthy = false
for try := 0; try < 10; try++ {
if l.Healthy() {
healthy = true
break
}
time.Sleep(1 * time.Second)
}
if !healthy {
t.Fatalf("Expected recovery, but not all nodes are healthy")
}
// Verify sending a JOIN now results in an output message.
mu.Lock()
state = "expect-join"
mu.Unlock()
session.PostMessage("JOIN #mod")
select {
case <-foundjoin:
t.Logf("JOIN reply received, network progressing")
case <-time.After(10 * time.Second):
t.Errorf("Timeout waiting for JOIN message")
}
}
|
package rest
import "github.com/gin-gonic/gin"
var (
router = gin.Default()
)
// SetRoutes ...
func SetRoutes() {
router.GET("/refresh", refresh)
router.GET("/create", create)
router.GET("/verify", verify)
router.GET("/revoke", revoke)
router.Run(":8080")
}
|
package downloader
import (
"fmt"
"os"
"os/exec"
"github.com/andygrunwald/perseus/dependency"
)
// Git represents an Updater and Downloader for the git protocol
type Git struct {
// workerCount is the number of worker that will be started
workerCount int
// Directory where to download the data into
dir string
// queue is the queue channel where all jobs are stored that needs to be processed by the worker
queue chan *dependency.Package
// results is the channel where all resolved dependencies will be streamed
results chan *Result
}
// Result reflects a result of a concurrent download process.
type Result struct {
Package *dependency.Package
Error error
}
// NewGitDownloader creates a new downloader based on the git protocol.
// numOfWorker initiates the number of workers we should spawn to work concurrent.
// dir is the base directory where the downloads will be mirrored, too.
func NewGitDownloader(numOfWorker int, dir string) (Downloader, error) {
if numOfWorker == 0 {
return nil, fmt.Errorf("Starting a concurrent git downloader with zero worker is not possible")
}
c := &Git{
workerCount: numOfWorker,
dir: dir,
queue: make(chan *dependency.Package, (numOfWorker + 1)),
results: make(chan *Result),
}
return c, nil
}
// GetResultStream will return the results stream.
// During the process of downloading git repositories, this channel will be filled
// with the results.
func (d *Git) GetResultStream() <-chan *Result {
return d.results
}
// Close will close the process
func (d *Git) Close() error {
close(d.results)
return nil
}
// Download will start the concurrent download process
func (d *Git) Download(packages []*dependency.Package) {
// Start the worker
for w := 1; w <= d.workerCount; w++ {
go d.worker(w, d.queue, d.results)
}
// Queue the downloads
for _, p := range packages {
d.queue <- p
}
close(d.queue)
}
// worker is a single worker routine. This worker will be launched multiple times to work on
// the queue as efficient as possible.
// id the a id per worker (only for logging/debugging purpose).
// jobs is the jobs channel (the worker needs to be able to read the jobs).
// results is the channel where all results will be stored once they are resolved.
func (d *Git) worker(id int, jobs <-chan *dependency.Package, results chan<- *Result) {
for j := range jobs {
targetDir := fmt.Sprintf("%s/%s.git", d.dir, j.Name)
// Check if directory already exists
_, err := os.Stat(targetDir)
if err == nil {
// Directory exists
r := &Result{
Package: j,
Error: os.ErrExist,
}
results <- r
continue
}
// Initial clone
err = d.clone(j.Repository.String(), targetDir)
if err != nil {
r := &Result{
Package: j,
Error: err,
}
results <- r
continue
}
err = d.updateServerInfo(targetDir)
if err != nil {
r := &Result{
Package: j,
Error: err,
}
results <- r
continue
}
err = d.fsck(targetDir)
if err != nil {
r := &Result{
Package: j,
Error: err,
}
results <- r
continue
}
// Everything successful downloaded
r := &Result{
Package: j,
Error: nil,
}
results <- r
}
}
func (d *Git) clone(repository, target string) error {
cmd := exec.Command("git", "clone", "--mirror", repository, target)
stdOut, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Error during cmd \"%+v\". Process state: %s. stdOut: %s. stdErr: %s", cmd.Args, ee.String(), stdOut, ee.Stderr)
}
return fmt.Errorf("Error during cmd \"%+v\". stdOut: %s", cmd.Args, stdOut)
}
return nil
}
func (d *Git) fsck(target string) error {
// Firing a git file system check.
// This was originally introduced, because on of the KDE git mirrors has problems.
// See https://github.com/instaclick/medusa/issues/6
cmd := exec.Command("git", "fsck")
cmd.Dir = target
stdOut, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Error during cmd \"%+v\". Process state: %s. stdOut: %s. stdErr: %s", cmd.Args, ee.String(), stdOut, ee.Stderr)
}
return fmt.Errorf("Error during cmd \"%+v\". stdOut: %s", cmd.Args, stdOut)
}
return nil
}
func (d *Git) updateServerInfo(target string) error {
// Lets be save and fire a update-server-info
// This is useful if the remote server don`t support on-the-fly pack generations.
// See `git help update-server-info`
// See https://github.com/instaclick/medusa/commit/ff4270f56afacf0a788b8b192e76180fbe32452e#diff-74b630cd9501803fdde532d1e2128e2f
cmd := exec.Command("git", "update-server-info", "-f")
cmd.Dir = target
stdOut, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Error during cmd \"%+v\". Process state: %s. stdOut: %s. stdErr: %s", cmd.Args, ee.String(), stdOut, ee.Stderr)
}
return fmt.Errorf("Error during cmd \"%+v\". stdOut: %s", cmd.Args, stdOut)
}
return nil
}
// NewGitUpdater created a new updater based on the git protocol.
//
// TODO Make me concurrent
func NewGitUpdater() (Updater, error) {
client := &Git{}
return client, nil
}
// Update updates target with a simple `git fetch`.
func (d *Git) Update(target string) error {
err := d.fetch(target)
if err != nil {
return err
}
err = d.updateServerInfo(target)
if err != nil {
return err
}
return nil
}
func (d *Git) fetch(target string) error {
cmd := exec.Command("git", "fetch", "--prune")
cmd.Dir = target
stdOut, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Error during cmd \"%+v\". Process state: %s. stdOut: %s. stdErr: %s", cmd.Args, ee.String(), stdOut, ee.Stderr)
}
return fmt.Errorf("Error during cmd \"%+v\". stdOut: %s", cmd.Args, stdOut)
}
return nil
}
|
package internal
import "github.com/sirupsen/logrus"
// Reload will reload any configuration changes without restarting the server
func Reload() {
logrus.Info("Reloading configurations (not implemented)")
}
|
package graph
import (
"fmt"
"sync"
"bldy.build/build"
"bldy.build/build/label"
)
// NewNode takes a label and a rule and returns it as a Graph Node
func NewNode(l label.Label, t build.Rule) Node {
return Node{
Target: t,
Type: fmt.Sprintf("%T", t)[1:],
Children: make(map[string]*Node),
Parents: make(map[string]*Node),
Once: sync.Once{},
WG: sync.WaitGroup{},
Status: build.Pending,
Label: l,
PriorityCount: -1,
}
}
// Node encapsulates a target and represents a node in the build graph.
type Node struct {
IsRoot bool `json:"-"`
Target build.Rule `json:"-"`
Type string
Parents map[string]*Node `json:"-"`
Label label.Label
Worker string
PriorityCount int
WG sync.WaitGroup
Status build.Status
Cached bool
Start, End int64
Hash string
Output string `json:"-"`
Once sync.Once
sync.Mutex
Children map[string]*Node
hash []byte
}
// Priority counts how many nodes directly and indirectly depend on
// this node
func (n *Node) Priority() int {
if n.PriorityCount < 0 {
p := 0
for _, c := range n.Parents {
p += c.Priority() + 1
}
n.PriorityCount = p
}
return n.PriorityCount
}
|
package server
import (
"context"
"fmt"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos"
"github.com/batchcorp/plumber-schemas/build/go/protos/common"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/actions"
"github.com/batchcorp/plumber/bus"
"github.com/batchcorp/plumber/config"
"github.com/batchcorp/plumber/validate"
)
type Server struct {
Actions actions.IActions
AuthToken string
PersistentConfig *config.Config
Bus bus.IBus
Log *logrus.Entry
CLIOptions *opts.CLIOptions
}
func (s *Server) GetServerOptions(_ context.Context, req *protos.GetServerOptionsRequest) (*protos.GetServerOptionsResponse, error) {
if err := s.validateAuth(req.Auth); err != nil {
return nil, CustomError(common.Code_UNAUTHENTICATED, fmt.Sprintf("invalid auth: %s", err))
}
return &protos.GetServerOptionsResponse{
ServerOptions: &opts.ServerOptions{
NodeId: s.CLIOptions.Server.NodeId,
ClusterId: s.CLIOptions.Server.ClusterId,
GrpcListenAddress: s.CLIOptions.Server.GrpcListenAddress,
AuthToken: s.CLIOptions.Server.AuthToken,
},
}, nil
}
type ErrorWrapper struct {
Status *common.Status
}
func (e *ErrorWrapper) Error() string {
return e.Status.Message
}
func CustomError(c common.Code, msg string) error {
return &ErrorWrapper{
Status: &common.Status{
Code: c,
Message: msg,
RequestId: uuid.NewV4().String(),
},
}
}
func (s *Server) validateAuth(auth *common.Auth) error {
if auth == nil {
return validate.ErrMissingAuth
}
if auth.Token != s.AuthToken {
return validate.ErrInvalidToken
}
return nil
}
|
package model
import (
"time"
)
type AddTaskRQ struct {
StudyUID string `json:"studyUID"`
StudyName string `json:"studyName"`
ContainerName string `json:"containerName"`
SOPObjects []SOPObject `json:"sopObjects"`
Steps []string `json:"steps"`
File string `json:"file"`
ShareRQ *ShareRQ `json:"shareRQ, omitempty"`
TransferRQ *TransferRQ `json:"transferRQ, omitempty"`
MagicLinkRQ *PublicURLRQ `json:"magicLinkRQ, omitempty"`
}
type SOPObject struct {
StudyUID string `json:"studyUID"`
SeriesInstanceUID string `json:"seriesInstanceUID"`
SOPInstanceUID string `json:"sopInstanceUID"`
}
type TaskRS struct {
UUID string `json:"uuid"`
StudyUID string `json:"studyUID"`
Steps StepRS `json:"steps"`
AditionalFields string `json:"aditionalFields"`
Status string `json:"status"`
Error error `json:"error"`
CreatedAt time.Time `json:"createdAt"`
ContainerID uint32 `json:"containerID"`
StudyID string `json:"studyID"`
IsReported bool `json:"isReported"`
}
type TasksRS []*TaskRS
type StepRS struct {
CurrentStepID string `json:"currentStepId"`
CurrentStep uint32 `json:"currentStep"`
TotalSteps uint32 `json:"totalSteps"`
}
|
package ratelimit
import (
"errors"
"fmt"
"math"
"sync"
"sync/atomic"
"time"
)
// todo timer 需要 stop
type localCounterLimiter struct {
limit Limit
limitCount int32 // 内部使用,对 limit.count 做了 <0 时的转换
ticker *time.Ticker
quit chan bool
lock sync.Mutex
newTerm *sync.Cond
count int32
}
func (lim *localCounterLimiter) init() {
lim.newTerm = sync.NewCond(&lim.lock)
lim.limitCount = lim.limit.Count()
if lim.limitCount < 0 {
lim.limitCount = math.MaxInt32 // count 永远不会大于 limitCount,后面的写法保证溢出也没问题
} else if lim.limitCount == 0 {
// 禁止访问, 会无限阻塞
} else {
lim.ticker = time.NewTicker(lim.limit.Period())
lim.quit = make(chan bool, 1)
go func() {
for {
select {
case <- lim.ticker.C:
fmt.Println("ticker .")
atomic.StoreInt32(&lim.count, 0)
lim.newTerm.Broadcast()
//lim.newTerm.L.Unlock()
case <- lim.quit:
fmt.Println("work well .")
lim.ticker.Stop()
return
}
}
}()
}
}
// todo 需要机制来防止无限阻塞, 不超时也应该有个极限时间
func (lim *localCounterLimiter) Acquire() error {
if lim.limitCount == 0 {
return errors.New("rate limit is 0, infinity wait")
}
lim.newTerm.L.Lock()
for lim.count >= lim.limitCount {
// block instead of spinning
lim.newTerm.Wait()
//fmt.Println(count, lim.limitCount)
}
lim.count++
lim.newTerm.L.Unlock()
return nil
}
func (lim *localCounterLimiter) TryAcquire() bool {
count := atomic.AddInt32(&lim.count, 1)
if count > lim.limitCount {
return false
} else {
return true
}
}
|
package vcli
import "fmt"
// CsvDataLoad - Load Funds, Voteplans and Proposals information into a SQLite3 ready file DB.
//
// vit-servicing-station-cli csv-data load
// --db-url <db-url> URL of the vit-servicing-station database to interact with
// --funds <funds> Path to the csv containing funds information
// --proposals <proposals> Path to the csv containing proposals information
// --challenges <challenges> Path to the csv containing challenges information
// --voteplans <voteplans> Path to the csv containing voteplans information
func CsvDataLoad(
dbURL string,
funds string,
proposals string,
challenges string,
voteplans string,
) ([]byte, error) {
if dbURL == "" {
return nil, fmt.Errorf("parameter missing : %s", "dbURL")
}
if funds == "" {
return nil, fmt.Errorf("parameter missing : %s", "funds")
}
if proposals == "" {
return nil, fmt.Errorf("parameter missing : %s", "proposals")
}
if challenges == "" {
return nil, fmt.Errorf("parameter missing : %s", "challenges")
}
if voteplans == "" {
return nil, fmt.Errorf("parameter missing : %s", "voteplans")
}
arg := []string{"csv-data", "load",
"--db-url", dbURL,
"--funds", funds,
"--proposals", proposals,
"--challenges", challenges,
"--voteplans", voteplans,
}
return vcli(nil, arg...)
}
|
package module
type ChatMgr struct {
moduleMgr *ModuleMgr //! 模块管理器指针
}
//! 注册消息
func (self *ChatMgr) registerMsg() {
}
//! 初始化管理器
func (self *ChatMgr) Init(moduleMgr *ModuleMgr) {
G_Dispatch.AddMsgRegistryToMap(new(Msg_Chat_Private)) //! 用户私聊消息
}
//! 生成聊天管理器
func NewChatMgr(moduleMgr *ModuleMgr) *ChatMgr {
chat := new(ChatMgr)
chat.Init(moduleMgr)
return chat
}
|
package _45_Jump_Game_2
func jump(nums []int) int {
if len(nums) <= 1 {
return 0
}
var (
distance = len(nums) - 1
step = 0
max = 0
i, idx = 0, 0
)
for i < len(nums) {
if i+nums[i] >= distance {
step++
return step
}
max = 0
idx = i + 1
for j := i + 1; j-i <= nums[i]; j++ {
if max < nums[j]+j-i {
max = nums[j] + j - i
idx = j
}
}
i = idx
step++
}
return step
}
|
package Voucher
import (
"encoding/json"
"fmt"
"github.com/Shopify/sarama"
"github.com/labstack/echo"
"github.com/radyatamaa/loyalti-go-echo/src/api/host/Config"
"github.com/radyatamaa/loyalti-go-echo/src/domain/model"
"log"
)
func PublishUpdateVoucher(c echo.Context) error {
//var data model.Merchant
data := new(model.Voucher)
err := json.NewDecoder(c.Request().Body).Decode(&data)
//err := c.Bind(data)
if err != nil {
panic(err)
}
fmt.Println(data)
//if len(data.MerchantEmail) == 0 && len(data.MerchantName) == 0 {
// return c.String(http.StatusBadRequest, "Nama dan Email kosong")
//} else if len(data.MerchantEmail) == 0 {
// return c.String(http.StatusBadRequest, "Email tidak boleh kosong")
//} else if len(data.MerchantName) == 0 {
// return c.String(http.StatusBadRequest, "Name tidak boleh kosong")
//}
kafkaConfig := Config.GetKafkaConfig("", "")
producer, err := sarama.NewSyncProducer([]string{"11.11.5.146:9092"}, kafkaConfig)
if err != nil {
panic(err)
}
defer func() {
if err := producer.Close(); err != nil {
panic(err)
}
}()
var newTopic = "update-voucher-topic"
message, _ := json.Marshal(data)
//message := `{
// "merchant_name":`+data.MerchantName+`,
// "merchant_email":"contact@jco.com"
//}`
msg := &sarama.ProducerMessage{
Topic: newTopic,
Value: sarama.StringEncoder(string(message)),
}
partition, offset, err := producer.SendMessage(msg)
if err != nil {
log.Println(err)
}
fmt.Printf("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", newTopic, partition, offset)
return nil
}
|
package google
import (
"math/rand"
"runtime"
"time"
"gitgud.io/softashell/comfy-translator/translator"
"github.com/hashicorp/go-retryablehttp"
log "github.com/sirupsen/logrus"
)
type inputChannel chan inputObject
type outputChannel chan returnObject
type BatchTranslator struct {
inCh inputChannel
// Delay between requests
batchDelay time.Duration
// Last time batch was sent
lastBatch time.Time
// Max characters in request
maxLength int
// http client
client *retryablehttp.Client
}
type inputObject struct {
req *translator.Request
outChan outputChannel
}
type returnObject struct {
text string
err error
}
func NewBatchTranslator(length int, delay time.Duration) *BatchTranslator {
q := &BatchTranslator{
inCh: make(inputChannel, runtime.NumCPU()),
maxLength: length,
batchDelay: delay,
lastBatch: time.Now(),
client: buildClient(),
}
go q.worker()
return q
}
func (q *BatchTranslator) worker() {
var timePassed time.Duration
for {
var items []inputObject
var totalLength int
var totalCount int
delay := q.batchDelay + time.Duration(rand.Intn(3000))*time.Millisecond
ReadChannel:
for (timePassed < delay || totalCount == 0) && totalLength < q.maxLength {
timePassed = time.Since(q.lastBatch)
select {
case item := <-q.inCh:
items = append(items, item)
totalLength += len([]rune(item.req.Text))
totalCount++
case <-time.After(delay):
timePassed = time.Since(q.lastBatch)
break ReadChannel
}
}
if timePassed < delay {
sleep := q.batchDelay - timePassed
log.Debugf("Throttling batch processing for %.1f seconds, Requests: %d Total request length: %d", sleep.Seconds(), len(items), totalLength)
time.Sleep(sleep)
}
q.translateBatch(items)
}
}
func (q *BatchTranslator) Join(req *translator.Request) (string, error) {
outCh := make(outputChannel)
i := inputObject{
req: req,
outChan: outCh,
}
// Add request to queue
q.inCh <- i
out := <-outCh
close(outCh)
// Wait for response
return out.text, out.err
}
|
package service
import "github.com/henglory/Demo_Golang_v0.0.1/spec"
type aRequestFn func(req spec.AReq) (spec.ARes, error)
type bRequestFn func(req spec.BReq) (spec.BRes, error)
|
package librke
import (
"context"
"github.com/docker/docker/api/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rke/cluster"
"github.com/rancher/rke/hosts"
"github.com/rancher/rke/k8s"
"github.com/rancher/rke/pki"
"github.com/rancher/types/apis/management.cattle.io/v3"
)
type rke struct {
}
func (*rke) GenerateRKENodeCerts(ctx context.Context, rkeConfig v3.RancherKubernetesEngineConfig, nodeAddress string, certBundle map[string]pki.CertificatePKI) map[string]pki.CertificatePKI {
return pki.GenerateRKENodeCerts(ctx, rkeConfig, nodeAddress, certBundle)
}
func (*rke) GenerateCerts(config *v3.RancherKubernetesEngineConfig) (map[string]pki.CertificatePKI, error) {
return pki.GenerateRKECerts(context.Background(), *config, "", "")
}
func (*rke) RegenerateEtcdCertificate(crtMap map[string]pki.CertificatePKI, etcdHost *hosts.Host, cluster *cluster.Cluster) (map[string]pki.CertificatePKI, error) {
return pki.RegenerateEtcdCertificate(context.Background(),
crtMap,
etcdHost,
cluster.EtcdHosts,
cluster.ClusterDomain,
cluster.KubernetesServiceIP)
}
func (*rke) ParseCluster(clusterName string, config *v3.RancherKubernetesEngineConfig,
dockerDialerFactory,
localConnDialerFactory hosts.DialerFactory,
k8sWrapTransport k8s.WrapTransport) (*cluster.Cluster, error) {
clusterFilePath := clusterName + "-cluster.yaml"
if clusterName == "local" {
clusterFilePath = ""
}
return cluster.ParseCluster(context.Background(),
config, clusterFilePath, "",
dockerDialerFactory,
localConnDialerFactory,
k8sWrapTransport)
}
func (*rke) GeneratePlan(ctx context.Context, rkeConfig *v3.RancherKubernetesEngineConfig, dockerInfo map[string]types.Info) (v3.RKEPlan, error) {
return cluster.GeneratePlan(ctx, rkeConfig.DeepCopy(), dockerInfo)
}
func GetDockerInfo(node *v3.Node) (map[string]types.Info, error) {
infos := map[string]types.Info{}
if node.Status.DockerInfo != nil {
dockerInfo := types.Info{}
err := convert.ToObj(node.Status.DockerInfo, &dockerInfo)
if err != nil {
return nil, err
}
infos[node.Status.NodeConfig.Address] = dockerInfo
}
return infos, nil
}
|
package main
import "fmt"
func main() {
sampleVarFunc(2, 2)
}
//variadic function test
func sampleVarFunc(x ...int) {
sum := 0
for _, v := range x {
sum += v
}
fmt.Printf(`%T`, x)
}
|
package models
import (
"log"
"os"
)
//LogError logs all error to file
func LogError(err error) {
f, _ := os.OpenFile("logs/errors.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()
logger := log.New(f, "Error: ", log.LstdFlags)
logger.Println(err.Error())
}
//ValidResponse structures valid api response into a json object
func ValidResponse(code int, body interface{}, message string) ResponseObject {
var response ResponseObject
response.Code = code
response.Message = message
response.Body = body
return response
}
|
package tsmt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03700103 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.037.001.03 Document"`
Message *StatusReportV03 `xml:"StsRpt"`
}
func (d *Document03700103) AddMessage() *StatusReportV03 {
d.Message = new(StatusReportV03)
return d.Message
}
// Scope
// The StatusReport message is sent by the matching application to the requester of a status report.
// This message is used to report on the status of transactions registered in the matching application.
// Usage
// The StatusReport message can be sent by the matching application to report on the status and sub-status of all transactions that the requester of the report is involved in. The message can be sent in response to a StatusReportRequest message.
type StatusReportV03 struct {
// Identifies the report.
ReportIdentification *iso20022.MessageIdentification1 `xml:"RptId"`
// Reference to the previous message requesting the report.
RelatedMessageReference *iso20022.MessageIdentification1 `xml:"RltdMsgRef"`
// Describes a transaction and its status.
ReportedItems []*iso20022.StatusReportItems2 `xml:"RptdItms,omitempty"`
}
func (s *StatusReportV03) AddReportIdentification() *iso20022.MessageIdentification1 {
s.ReportIdentification = new(iso20022.MessageIdentification1)
return s.ReportIdentification
}
func (s *StatusReportV03) AddRelatedMessageReference() *iso20022.MessageIdentification1 {
s.RelatedMessageReference = new(iso20022.MessageIdentification1)
return s.RelatedMessageReference
}
func (s *StatusReportV03) AddReportedItems() *iso20022.StatusReportItems2 {
newValue := new(iso20022.StatusReportItems2)
s.ReportedItems = append(s.ReportedItems, newValue)
return newValue
}
|
package streams
import (
"context"
"encoding/json"
"github.com/go-fed/activity/streams/vocab"
"github.com/go-test/deep"
"net/url"
"testing"
)
type serializer interface {
Serialize() (map[string]interface{}, error)
}
// IsKnownResolverError returns true if it is known that an example from
// GetTestTable will trigger a JSONResolver error.
func IsKnownResolverError(t TestTable) (b bool, reason string) {
if t.name == "Example 61" {
b = true
reason = "no \"type\" property is on the root object"
} else if t.name == "Example 62" {
b = true
reason = "an unknown \"type\" property is on the root object"
} else if t.name == "Example 153" {
b = true
reason = "no \"type\" property is on the root object"
}
return
}
func TestJSONResolver(t *testing.T) {
for _, example := range GetTestTable() {
if skip, reason := IsKnownResolverError(example); skip {
t.Logf("Skipping table test case %q as it's known an error will be returned because %s", example.name, reason)
continue
}
name := example.name
t.Logf("Testing table test case %q", name)
ex := example.expectedJSON
resFn := func(s serializer) error {
m, err := s.Serialize()
if err != nil {
return err
}
m["@context"] = "https://www.w3.org/ns/activitystreams"
actual, err := json.Marshal(m)
if diff, err := GetJSONDiff(actual, []byte(ex)); err == nil && diff != nil {
t.Errorf("%s: Serialize JSON equality is false:\n%s", name, diff)
} else if err != nil {
t.Errorf("%s: GetJSONDiff returned error: %s", name, err)
}
return nil
}
r, err := NewJSONResolver(
func(c context.Context, x vocab.ActivityStreamsAccept) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsActivity) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAdd) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAnnounce) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsApplication) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsArrive) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsArticle) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAudio) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsBlock) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCollection) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCollectionPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCreate) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDelete) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDislike) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDocument) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsEvent) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsFlag) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsFollow) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsGroup) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsIgnore) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsImage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsIntransitiveActivity) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsInvite) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsJoin) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLeave) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLike) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLink) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsListen) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsMention) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsMove) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsNote) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsObject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOffer) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrderedCollection) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrderedCollectionPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrganization) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPerson) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPlace) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsProfile) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsQuestion) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRead) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsReject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRelationship) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRemove) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsService) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTentativeAccept) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTentativeReject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTombstone) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTravel) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsUndo) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsUpdate) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsVideo) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsView) error {
return resFn(x)
},
)
if err != nil {
t.Errorf("%s: Cannot create JSONResolver: %s", name, err)
continue
}
m := make(map[string]interface{})
err = json.Unmarshal([]byte(ex), &m)
if err != nil {
t.Errorf("%s: Cannot json.Unmarshal: %s", name, err)
continue
}
err = r.Resolve(context.Background(), m)
if err != nil {
t.Errorf("%s: Cannot JSONResolver.Deserialize: %s", name, err)
continue
}
}
}
func TestJSONResolverErrors(t *testing.T) {
for _, example := range GetTestTable() {
isError, reason := IsKnownResolverError(example)
if !isError {
continue
}
name := example.name
t.Logf("Testing table test case %q", name)
ex := example.expectedJSON
resFn := func(s serializer) error { return nil }
r, err := NewJSONResolver(
func(c context.Context, x vocab.ActivityStreamsAccept) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsActivity) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAdd) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAnnounce) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsApplication) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsArrive) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsArticle) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsAudio) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsBlock) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCollection) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCollectionPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsCreate) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDelete) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDislike) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsDocument) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsEvent) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsFlag) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsFollow) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsGroup) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsIgnore) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsImage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsIntransitiveActivity) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsInvite) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsJoin) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLeave) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLike) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsLink) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsListen) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsMention) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsMove) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsNote) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsObject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOffer) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrderedCollection) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrderedCollectionPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsOrganization) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPage) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPerson) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsPlace) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsProfile) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsQuestion) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRead) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsReject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRelationship) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsRemove) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsService) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTentativeAccept) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTentativeReject) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTombstone) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsTravel) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsUndo) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsUpdate) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsVideo) error {
return resFn(x)
},
func(c context.Context, x vocab.ActivityStreamsView) error {
return resFn(x)
},
)
if err != nil {
t.Errorf("%s: Cannot create JSONResolver: %s", name, err)
continue
}
m := make(map[string]interface{})
err = json.Unmarshal([]byte(ex), &m)
if err != nil {
t.Errorf("%s: Cannot json.Unmarshal: %s", name, err)
continue
}
err = r.Resolve(context.Background(), m)
if err == nil {
t.Errorf("%s: Expected error because %s", name, reason)
}
}
}
func TestNulls(t *testing.T) {
const (
samIRIInboxString = "https://example.com/sam/inbox"
samIRIString = "https://example.com/sam"
noteURIString = "https://example.com/note/123"
sallyIRIString = "https://example.com/sally"
activityIRIString = "https://example.com/test/new/iri"
)
samIRIInbox, err := url.Parse(samIRIInboxString)
if err != nil {
t.Fatal(err)
}
samIRI, err := url.Parse(samIRIString)
if err != nil {
t.Fatal(err)
}
noteIRI, err := url.Parse(noteURIString)
if err != nil {
t.Fatal(err)
}
sallyIRI, err := url.Parse(sallyIRIString)
if err != nil {
t.Fatal(err)
}
activityIRI, err := url.Parse(activityIRIString)
if err != nil {
t.Fatal(err)
}
noteIdProperty := NewActivityStreamsIdProperty()
noteIdProperty.SetIRI(noteIRI)
expectedNote := NewActivityStreamsNote()
expectedNote.SetActivityStreamsId(noteIdProperty)
noteNameProperty := NewActivityStreamsNameProperty()
noteNameProperty.AppendXMLSchemaString("A Note")
expectedNote.SetActivityStreamsName(noteNameProperty)
noteContentProperty := NewActivityStreamsContentProperty()
noteContentProperty.AppendXMLSchemaString("This is a simple note")
expectedNote.SetActivityStreamsContent(noteContentProperty)
noteToProperty := NewActivityStreamsToProperty()
expectedSamActor := NewActivityStreamsPerson()
samInboxProperty := NewActivityStreamsInboxProperty()
samInboxProperty.SetIRI(samIRIInbox)
expectedSamActor.SetActivityStreamsInbox(samInboxProperty)
samIdProperty := NewActivityStreamsIdProperty()
samIdProperty.SetIRI(samIRI)
expectedSamActor.SetActivityStreamsId(samIdProperty)
noteToProperty.AppendActivityStreamsPerson(expectedSamActor)
expectedNote.SetActivityStreamsTo(noteToProperty)
expectedUpdate := NewActivityStreamsUpdate()
sallyIdProperty := NewActivityStreamsIdProperty()
sallyIdProperty.SetIRI(sallyIRI)
sallyPerson := NewActivityStreamsPerson()
sallyPerson.SetActivityStreamsId(sallyIdProperty)
sallyActor := NewActivityStreamsActorProperty()
sallyActor.AppendActivityStreamsPerson(sallyPerson)
expectedUpdate.SetActivityStreamsActor(sallyActor)
summaryProperty := NewActivityStreamsSummaryProperty()
summaryProperty.AppendXMLSchemaString("Sally updated her note")
expectedUpdate.SetActivityStreamsSummary(summaryProperty)
updateIdProperty := NewActivityStreamsIdProperty()
updateIdProperty.SetIRI(activityIRI)
expectedUpdate.SetActivityStreamsId(updateIdProperty)
objectNote := NewActivityStreamsObjectProperty()
objectNote.AppendActivityStreamsNote(expectedNote)
expectedUpdate.SetActivityStreamsObject(objectNote)
// Variable to aid in deserialization in tests
var actual serializer
tables := []struct {
name string
expected serializer
callback interface{}
input string
inputWithoutNulls string
}{
{
name: "JSON nulls are not preserved",
expected: expectedUpdate,
callback: func(c context.Context, v vocab.ActivityStreamsUpdate) error {
actual = v
return nil
},
input: `
{
"@context": "https://www.w3.org/ns/activitystreams",
"summary": "Sally updated her note",
"type": "Update",
"actor": "https://example.com/sally",
"id": "https://example.com/test/new/iri",
"object": {
"id": "https://example.com/note/123",
"type": "Note",
"to": {
"id": "https://example.com/sam",
"inbox": "https://example.com/sam/inbox",
"type": "Person",
"name": null
}
}
}
`,
inputWithoutNulls: `
{
"@context": "https://www.w3.org/ns/activitystreams",
"summary": "Sally updated her note",
"type": "Update",
"actor": "https://example.com/sally",
"id": "https://example.com/test/new/iri",
"object": {
"id": "https://example.com/note/123",
"type": "Note",
"to": {
"id": "https://example.com/sam",
"inbox": "https://example.com/sam/inbox",
"type": "Person"
}
}
}
`,
},
}
for _, r := range tables {
t.Logf("Testing table test case %q", r.name)
res, err := NewJSONResolver(r.callback)
if err != nil {
t.Errorf("%s: cannot create resolver: %s", r.name, err)
continue
}
m := make(map[string]interface{})
err = json.Unmarshal([]byte(r.input), &m)
if err != nil {
t.Errorf("%s: Cannot json.Unmarshal: %s", r.name, err)
continue
}
err = res.Resolve(context.Background(), m)
if err != nil {
t.Errorf("%s: Cannot Deserialize: %s", r.name, err)
continue
}
if diff := deep.Equal(actual, r.expected); diff != nil {
t.Errorf("%s: Deserialize deep equal is false: %s", r.name, diff)
}
m, err = actual.Serialize()
if err != nil {
t.Errorf("%s: Cannot Serialize: %s", r.name, err)
continue
}
m["@context"] = "https://www.w3.org/ns/activitystreams"
reser, err := json.Marshal(m)
if err != nil {
t.Errorf("%s: Cannot json.Marshal: %s", r.name, err)
continue
}
if diff, err := GetJSONDiff(reser, []byte(r.inputWithoutNulls)); err == nil && diff != nil {
t.Errorf("%s: Serialize JSON equality is false:\n%s", r.name, diff)
} else if err != nil {
t.Errorf("%s: GetJSONDiff returned error: %s", r.name, err)
}
}
}
func GetJSONDiff(str1, str2 []byte) ([]string, error) {
var i1 interface{}
var i2 interface{}
err := json.Unmarshal(str1, &i1)
if err != nil {
return nil, err
}
err = json.Unmarshal(str2, &i2)
if err != nil {
return nil, err
}
return deep.Equal(i1, i2), nil
}
|
package main
import (
"fmt"
"math"
"strings"
)
type particle struct {
x, y, dx, dy int
}
func loaddata(input string) (result []particle) {
for _, line := range strings.Split(input, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
p := particle{}
fmt.Sscanf(line, "position=<%d, %d> velocity=<%d, %d>", &p.x, &p.y, &p.dx, &p.dy)
result = append(result, p)
}
return result
}
func moveparticles(ps []particle) {
for i, p := range ps {
p.x += p.dx
p.y += p.dy
ps[i] = p
}
}
type xy struct {
x, y int
}
type boundedgrid struct {
minx, miny, maxx, maxy int
grid map[xy]bool
}
func buildgrid(particles []particle) boundedgrid {
grid := map[xy]bool{}
minx := math.MaxInt32
miny := math.MaxInt32
maxx := 0
maxy := 0
for _, p := range particles {
grid[xy{x: p.x, y: p.y}] = true
if p.x > maxx {
maxx = p.x
}
if p.y > maxy {
maxy = p.y
}
if p.x < minx {
minx = p.x
}
if p.y < miny {
miny = p.y
}
}
return boundedgrid{minx: minx, miny: miny, maxx: maxx, maxy: maxy, grid: grid}
}
//dump grid using same output as example
func printgrid(particles []particle) {
bgrid := buildgrid(particles)
for y := bgrid.miny; y <= bgrid.maxy; y++ {
for x := bgrid.minx; x <= bgrid.maxx; x++ {
if bgrid.grid[xy{x: x, y: y}] {
fmt.Print("#")
} else {
fmt.Print(".")
}
}
fmt.Println("")
}
}
func candidate(particles []particle) bool {
//look for at least 3 sets of 6 #'s aligned vertically
seekcols := 3
bgrid := buildgrid(particles)
cols := 0
for t := range bgrid.grid {
if bgrid.grid[xy{t.x, t.y - 1}] &&
bgrid.grid[xy{t.x, t.y - 2}] &&
bgrid.grid[xy{t.x, t.y - 3}] &&
bgrid.grid[xy{t.x, t.y - 4}] &&
bgrid.grid[xy{t.x, t.y - 5}] {
cols++
}
if cols > seekcols-1 {
break
}
}
return cols > seekcols-1
}
func moveuntilcandidate(particles []particle) int {
iter := 0
found := false
for !found {
iter++
moveparticles(particles)
found = candidate(particles)
}
printgrid(particles)
return iter
}
func main() {
particles := loaddata(testdata())
iter := moveuntilcandidate(particles)
main2(iter)
}
func testdata() string {
return `
position=< 9, 1> velocity=< 0, 2>
position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1>
position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> velocity=< 2, 2>
position=<-6, 10> velocity=< 2, -2>
position=< 1, 8> velocity=< 1, -1>
position=< 1, 7> velocity=< 1, 0>
position=<-3, 11> velocity=< 1, -2>
position=< 7, 6> velocity=<-1, -1>
position=<-2, 3> velocity=< 1, 0>
position=<-4, 3> velocity=< 2, 0>
position=<10, -3> velocity=<-1, 1>
position=< 5, 11> velocity=< 1, -2>
position=< 4, 7> velocity=< 0, -1>
position=< 8, -2> velocity=< 0, 1>
position=<15, 0> velocity=<-2, 0>
position=< 1, 6> velocity=< 1, 0>
position=< 8, 9> velocity=< 0, -1>
position=< 3, 3> velocity=<-1, 1>
position=< 0, 5> velocity=< 0, -1>
position=<-2, 2> velocity=< 2, 0>
position=< 5, -2> velocity=< 1, 2>
position=< 1, 4> velocity=< 2, 1>
position=<-2, 7> velocity=< 2, -2>
position=< 3, 6> velocity=<-1, -1>
position=< 5, 0> velocity=< 1, 0>
position=<-6, 0> velocity=< 2, 0>
position=< 5, 9> velocity=< 1, -2>
position=<14, 7> velocity=<-2, 0>
position=<-3, 6> velocity=< 2, -1>
`
}
|
package peer
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/perlin-network/noise/protobuf"
)
// ID is an identity of nodes, using its public key and network address
type ID protobuf.ID
// CreateID is a factory function creating ID
func CreateID(address string, publicKey []byte) ID {
return ID{PublicKey: publicKey, Address: address}
}
//
func (id ID) String() string {
return fmt.Sprintf("ID{PublicKey: %v, Address: %v}", id.PublicKey, id.Address)
}
// Equals determines if two peer IDs are equal to each other based on the contents of their public keys.
func (id ID) Equals(other ID) bool {
return bytes.Equal(id.PublicKey, other.PublicKey)
}
// Less determines if this peer.ID's public keys is less than the other's
func (id ID) Less(other interface{}) bool {
if other, is := other.(ID); is {
return bytes.Compare(id.PublicKey, other.PublicKey) == -1
}
return false
}
// PublicKeyHex generates hex-encoded string of public key of this given peer ID.
func (id ID) PublicKeyHex() string {
return hex.EncodeToString(id.PublicKey)
}
// Xor performs XOR (^) over another peer ID's public key.
func (id ID) Xor(other ID) ID {
result := make([]byte, len(id.PublicKey))
for i := 0; i < len(id.PublicKey) && i < len(other.PublicKey); i++ {
result[i] = id.PublicKey[i] ^ other.PublicKey[i]
}
return ID{Address: id.Address, PublicKey: result}
}
// PrefixLen returns the number of prefixed zeros in a peer ID.
func (id ID) PrefixLen() int {
for x := 0; x < len(id.PublicKey); x++ {
for y := 0; y < 8; y++ {
if (id.PublicKey[x]>>uint8(7-y))&0x1 != 0 {
return x*8 + y
}
}
}
return len(id.PublicKey)*8 - 1
}
|
package main
import (
"errors"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/gelidus/nogo/utils"
"github.com/gelidus/nogo/visitors/example"
"github.com/gelidus/nogo/visitors/govisitor"
"github.com/gelidus/nogo/visitors/pointers"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
var (
visitors = map[string]utils.Visitor{
"example": &example.Visitor{},
"go": &govisitor.Visitor{},
"pointers": &pointers.Visitor{},
}
)
func main() {
log.SetLevel(log.DebugLevel)
app := cli.NewApp()
app.Name = "nogo"
app.Usage = ""
app.Flags = []cli.Flag{
cli.StringSliceFlag{
Name: "pattern, p",
Usage: "Enables given pattern visitor",
},
}
app.Action = func(c *cli.Context) error {
if c.NArg() <= 0 {
return errors.New("Missing file name")
}
// filename to parse
fileName := c.Args()[0]
info, err := os.Stat(fileName)
if os.IsNotExist(err) {
return err
}
// fset for parse functions
astFileMap := map[string]utils.SourceFile{}
if info.IsDir() {
log.Debug("Executing on folder: ", fileName)
err := filepath.Walk(fileName, func(path string, info os.FileInfo, err error) error {
if info.IsDir() != true && strings.HasSuffix(info.Name(), ".go") {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return err
}
astFileMap[path] = utils.SourceFile{
Node: f,
Fset: fset,
}
}
return nil
})
if err != nil {
return err
}
} else {
log.Debug("Executing on file: ", fileName)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, fileName, nil, parser.ParseComments)
if err != nil {
return err
}
astFileMap[fileName] = utils.SourceFile{
Node: f,
Fset: fset,
}
}
log.Debug("Parse successful for target: ", fileName)
patterns := c.GlobalStringSlice("pattern")
vs := []utils.Visitor{}
for _, p := range patterns {
vs = append(vs, visitors[p])
}
errs := utils.RunVisitorsInParallel(astFileMap, vs)
if len(errs) > 0 {
log.Warn("Errors were reported by the visitor: ")
for _, vs := range errs {
for _, visitor := range vs {
log.Warn(visitor[0])
}
}
} else {
log.Info("No errors found #shipit")
}
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
|
package main
import (
"fmt"
"bufio"
"os"
"net/http"
"log"
"io/ioutil"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Give me a number: ")
num, _ := reader.ReadString('\n')
num = strings.TrimSuffix(num, "\n")
url := fmt.Sprintf("http://numbersapi.com/%s/math",num)
response, err := http.Get(url)
if err != nil {
log.Fatal("NewRequest: ", err)
return
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
fmt.Printf("%s\n", string(contents))
}
}
|
package main
import (
"fmt"
facebook "github.com/madebyais/facebook-go-sdk"
)
// BasicFeedPost will show you about
// how to post a feed to your timeline
func BasicFeedPost() {
// initalize facebook-go-sdk
fb := facebook.New()
// set your access token
// NOTES: Please exchange with your access token
fb.SetAccessToken(`...`)
// submit your feed
data, err := fb.API(`/me/feed`).Messages(`coba yo`).Post()
if err != nil {
panic(err)
}
fmt.Println(`
## SAMPLE - POST A FEED
`)
fmt.Println(data)
// if you want to share a link you can use the `Link` method
// e.g. fb.API(`/me/feed`).Messages(`coba yo`).Link(`http://madebyais.com`).Post()
}
|
package main
import "sort"
type ints [][]int
func (s ints) Len() int {
return len(s)
}
func (s ints) Less(i, j int) bool {
return s[i][0] < s[j][0]
}
func (s ints) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func merge(intervals [][]int) [][]int {
var res [][]int
if len(intervals) == 0 {
return res
}
sort.Sort(ints(intervals))
for _, interval := range intervals {
if len(res) == 0 || res[len(res)-1][1] < interval[0] {
res = append(res, interval)
} else {
if interval[1] > res[len(res)-1][1] {
res[len(res)-1][1] = interval[1]
}
}
}
return res
}
|
package linkedlist
import (
"fmt"
"strings"
)
type Node struct {
Value interface{}
next *Node
}
func (node *Node) String() string {
return fmt.Sprint(node.Value)
}
type LinkedList struct {
head *Node
len int
}
func (l *LinkedList) String() string {
cur := l.head
ret := strings.Builder{}
for cur != nil {
ret.WriteString(cur.String())
if cur.next != nil {
ret.WriteString(" -> ")
}
cur = cur.next
}
return ret.String()
}
// 链表的反转操作,pre 代表了反转后链表的尾节点。O(N) 复杂度
// 如果想直接反转链表,传入 pre 为 nil 即可
func (l *LinkedList) Reverse(pre *Node) {
if l.len <= 1 {
return
}
for l.head != nil {
temp := l.head.next
l.head.next = pre
pre = l.head
l.head = temp
}
l.head = pre
}
// 找到链表的中间节点,共计偶数个节点时返回前一个中间节点。O(N) 时间复杂度
// 1—>2—>3—>4—>5 返回值为 3 的节点
// 1—>2—>3—>4 返回值为 2 的节点
func (l *LinkedList) FindMiddleNode() *Node {
if l.len < 2 {
return nil
}
slow, fast := l.head, l.head
// 共计偶数个节点时返回后一个中间节点时,修改条件为
// for fast != nil && fast.next != nil{
for fast.next != nil && fast.next.next != nil {
slow = slow.next
fast = fast.next.next
}
return slow
}
// 已知链表的长度,删除链表的倒数第 n 个节点。O(N)复杂度
// 如果 n 大于链表的长度,返回 nil
func (l *LinkedList) DeleteBottomNWithLength(n int) *Node {
index := l.len - n
if index < 0 || index == l.len {
return nil
}
// 删除头节点需要单独判断
if index == 0 {
temp := l.head
l.head = temp.next
l.len--
return temp
}
// 1.获取要删除的节点的前驱结点
i := 0
pre := l.head
for i+1 != index {
pre = pre.next
i++
}
// 2.删除节点
temp := pre.next
pre.next = temp.next
temp.next = nil
l.len--
return temp
}
// 在不遍历链表就无法得到链表长度时,删除链表的倒数第 n 个节点。O(N)复杂度
// 如果 n 大于链表的长度,返回 nil
func (l *LinkedList) DeleteBottomN(n int) *Node {
if n <= 0 || l.head == nil {
return nil
}
fast, slow := l.head, l.head
// 1. 快指针先走 n 步
for i := 0; i < n; i++ {
// 删除头节点 head
if fast.next == nil && i == n-1 {
temp := l.head
l.head = temp.next
temp.next = nil
return temp
// 要删除的节点不存在,如链表共 2 个元素,但 n==3
} else if fast.next == nil && i < n-1 {
return nil
}
fast = fast.next
}
// 2. 快慢指针同时走,直到快指针到达尾节点
for fast.next != nil {
slow = slow.next
fast = fast.next
}
// 这里借助 fast 暂时存储要删除的节点,防止删除后链表断裂
fast = slow.next
slow.next = fast.next
fast.next = nil
return fast
}
// 合并两个有序链表,假设这两个链表都按从小到大的顺序排列
func MergeSortedList(l1, l2 *LinkedList) *LinkedList {
if 0 == l1.len {
return l2
}
if 0 == l2.len {
return l1
}
cur1, cur2 := l1.head, l2.head
l := &LinkedList{&Node{}, 0}
cur := l.head
for cur1 != nil && cur2 != nil {
if cur1.Value.(int) > cur2.Value.(int) {
cur.next = cur2
cur2 = cur2.next
l.len++
} else {
cur.next = cur1
cur1 = cur1.next
l.len++
}
cur = cur.next
}
if cur1 == nil {
cur.next = cur2
for cur2 != nil {
l.len++
cur2 = cur2.next
}
}
if cur2 == nil {
cur.next = cur1
for cur1 != nil {
l.len++
cur1 = cur1.next
}
}
l.head = l.head.next
return l
}
|
package data
import (
"gobackend/chitChat/db"
"gobackend/chitChat/models"
)
func GetThreads() (ThreadList []*ThreadList, err error) {
err = db.GetDB().Model(&models.Threads{}).Scan(&ThreadList).Error
return
}
func GetThread(id int64) (Thread models.Threads, err error) {
err = db.GetDB().Where("id = ?", id).First(&Thread).Error
return
}
func CreateThread(topic string, userid int64) error {
md := &models.Threads{Topic: topic, UserId: userid}
err := db.GetDB().Model(&models.Threads{}).
Create(md).Error
return err
}
|
package images
import (
"context"
"fmt"
"sync"
"time"
"github.com/dollarshaveclub/acyl/pkg/eventlogger"
"github.com/dollarshaveclub/acyl/pkg/models"
nitroerrors "github.com/dollarshaveclub/acyl/pkg/nitro/errors"
"github.com/dollarshaveclub/acyl/pkg/nitro/metrics"
"github.com/dollarshaveclub/acyl/pkg/persistence"
"github.com/pkg/errors"
)
// BuildOptions models optional image build options
type BuildOptions struct {
// Relative path to Dockerfile within build context
DockerfilePath string
// key-value pairs for optional build arguments
BuildArgs map[string]string
}
// BuilderBackend describes the object that actually does image builds
type BuilderBackend interface {
BuildImage(ctx context.Context, envName, githubRepo, imageRepo, ref string, ops BuildOptions) error
}
// Builder describes an object that builds a set of container images
type Builder interface {
StartBuilds(ctx context.Context, envname string, rc *models.RepoConfig) (Batch, error)
}
// Batch describes a BuildBatch object
type Batch interface {
Completed(envname, name string) (bool, error)
Started(envname, name string) bool
Done() bool
Stop()
}
type lockingOutcomes struct {
sync.RWMutex
started map[string]struct{}
completed map[string]error
}
var _ Builder = &ImageBuilder{}
// ImageBuilder is an object that builds images using imageBuilderBackend
// it is intended to be a singleton instance shared among multiple concurrent environment
// creation procedures. Consequently, build IDs contain the name of the environment to avoid collisions
type ImageBuilder struct {
Backend BuilderBackend
BuildTimeout time.Duration
DL persistence.DataLayer
MC metrics.Collector
}
var DefaultBuildTimeout = 1 * time.Hour
type BuildBatch struct {
outcomes *lockingOutcomes
stopf func()
}
func buildid(envname, name string) string {
return envname + "-" + name
}
// Completed returns if build for repo has completed along with outcome
func (b *BuildBatch) Completed(envname, name string) (bool, error) {
b.outcomes.RLock()
defer b.outcomes.RUnlock()
err, ok := b.outcomes.completed[buildid(envname, name)]
return ok, err
}
func (b *BuildBatch) Started(envname, name string) bool {
b.outcomes.RLock()
defer b.outcomes.RUnlock()
_, ok := b.outcomes.started[buildid(envname, name)]
return ok
}
// Done returns whether all builds in the batch have completed
func (b *BuildBatch) Done() bool {
b.outcomes.RLock()
defer b.outcomes.RUnlock()
return len(b.outcomes.completed) == len(b.outcomes.started)
}
// Stop aborts any running builds in the batch and cleans up orphaned resources
func (b *BuildBatch) Stop() {
b.stopf()
}
// StartBuilds begins asynchronously building all container images according to rm, pushing to image repositories specified in rc.
func (b *ImageBuilder) StartBuilds(ctx context.Context, envname string, rc *models.RepoConfig) (Batch, error) {
batch := &BuildBatch{outcomes: &lockingOutcomes{started: make(map[string]struct{}), completed: make(map[string]error)}}
if envname == "" || rc == nil {
return batch, errors.New("at least one parameter is nil")
}
if b.BuildTimeout == time.Duration(0) {
b.BuildTimeout = DefaultBuildTimeout
}
buildimage := func(ctx context.Context, name, repo, image, ref, dockerfilepath string) {
batch.outcomes.Lock()
batch.outcomes.started[buildid(envname, name)] = struct{}{}
batch.outcomes.Unlock()
eventlogger.GetLogger(ctx).SetImageStarted(name)
end := b.MC.Timing("images.build", "repo:"+repo, "triggering_repo:"+rc.Application.Repo)
err := b.Backend.BuildImage(ctx, envname, repo, image, ref, BuildOptions{DockerfilePath: dockerfilepath})
end(fmt.Sprintf("success:%v", err == nil))
eventlogger.GetLogger(ctx).SetImageCompleted(name, err != nil)
batch.outcomes.Lock()
batch.outcomes.completed[buildid(envname, name)] = nitroerrors.User(err)
batch.outcomes.Unlock()
}
cfs := []context.CancelFunc{}
ctx2, cf := context.WithTimeout(ctx, b.BuildTimeout)
cfs = append(cfs, cf)
go buildimage(ctx2, models.GetName(rc.Application.Repo), rc.Application.Repo, rc.Application.Image, rc.Application.Ref, rc.Application.DockerfilePath)
for _, d := range rc.Dependencies.All() {
if d.Repo != "" { // only build images for Repo (branch-matched) dependencies
ctx3, cf := context.WithTimeout(ctx, b.BuildTimeout)
cfs = append(cfs, cf)
go buildimage(ctx3, d.Name, d.Repo, d.AppMetadata.Image, d.AppMetadata.Ref, d.AppMetadata.DockerfilePath)
}
}
stopf := func() {
for _, cf := range cfs {
cf()
}
}
batch.stopf = stopf
return batch, nil
}
|
package cache
import (
"strconv"
"strings"
"sync"
"time"
"github.com/lexesjan/go-web-proxy-server/pkg/http"
"github.com/lexesjan/go-web-proxy-server/pkg/log"
)
// Cache represents the proxy cache
type Cache struct {
cacheMap *sync.Map
}
// NewCache returns a new Cache
func NewCache() (cache *Cache) {
cache = &Cache{cacheMap: &sync.Map{}}
return cache
}
// Entry represents a cache entry
type Entry struct {
Response string
Stale bool
UncachedResponseTime time.Duration
UncachedBandwidth int64
}
// CacheResponse adds a HTTP response to the cache and starts a timer which
// marks the cache entry stale
func (cache *Cache) CacheResponse(
reqURL string,
resp *http.Response,
duration time.Duration,
) (err error) {
contains := func(arr []string, str string) bool {
for _, elem := range arr {
if elem == str {
return true
}
}
return false
}
newCacheEntry := &Entry{
Response: resp.String(),
Stale: false,
UncachedResponseTime: duration,
UncachedBandwidth: int64(len(resp.String())),
}
cacheControl := resp.Headers.CacheControl()
uncacheable := contains(cacheControl, "no-store") || resp.StatusCode == 304
// Can't be cached.
if uncacheable {
return nil
}
cache.cacheMap.Store(reqURL, newCacheEntry)
err = newCacheEntry.ResetTimer(reqURL, cacheControl)
if err != nil {
return err
}
return nil
}
// ResetTimer resets the timer which marks a cache entry stale
func (entry *Entry) ResetTimer(
reqURL string,
cacheControl []string,
) (err error) {
entry.Stale = false
maxAge := 0
for _, elem := range cacheControl {
if strings.HasPrefix(elem, "max-age") {
tokens := strings.Split(elem, "=")
maxAge, err = strconv.Atoi(tokens[1])
if err != nil {
return err
}
}
}
// Mark expired cache as stale
time.AfterFunc(time.Duration(maxAge)*time.Second, func() {
entry.Stale = true
log.ProxyCacheStale(reqURL)
})
return nil
}
// Get returns the cache Entry in the map. The ok result indicates whether the
// value was found in the map
func (cache *Cache) Get(key string) (value *Entry, ok bool) {
cachedEntryInterface, ok := cache.cacheMap.Load(key)
value = &Entry{}
if ok {
value = cachedEntryInterface.(*Entry)
}
return value, ok
}
|
package golang
import (
"reflect"
"testing"
)
var tests = []struct {
input []int
output int
}{
/*
* {input: []int{1, 3, 5, 7, 9}, output: 4},
* {input: []int{1, 1, 1, 3, 3, 3, 7}, output: 15},
* {input: []int{149, 107, 1, 63, 0, 1, 6867, 1325, 5611, 2581, 39, 89, 46, 18, 12, 20, 22, 234}, output: 12},
*/
{input: []int{2160, 1936, 3, 29, 27, 5, 2503, 1593, 2, 0, 16, 0, 3860, 28908, 6, 2, 15, 49, 6246, 1946, 23, 105, 7996, 196, 0, 2, 55, 457, 5, 3, 924, 7268, 16, 48, 4, 0, 12, 116, 2628, 1468}, output: 53},
}
func TestCountPairs(t *testing.T) {
for idx, test := range tests {
copyData := make([]int, len(test.input), len(test.input))
copy(copyData, test.input)
actual := countPairs(copyData)
if !reflect.DeepEqual(actual, test.output) {
t.Errorf(
"TestCase[%d]: deliciousness = %v, expected %d but get %d",
idx,
test.input,
test.output,
actual,
)
}
}
}
|
package field
import (
"encoding/binary"
"io"
"github.com/tombell/go-serato/internal/decode"
"github.com/tombell/go-serato/internal/trim"
)
// Comment is the comment on the track.
type Comment struct {
header *Header
data []byte
}
// Value returns the comment.
func (f *Comment) Value() string {
s := decode.UTF16(f.data)
return trim.Nil(s)
}
func (f *Comment) String() string {
return f.Value()
}
// NewCommentField returns an initialised Comment, using the given field header.
func NewCommentField(header *Header, r io.Reader) (*Comment, error) {
if header.Identifier != commentID {
return nil, ErrUnexpectedIdentifier
}
data := make([]byte, header.Length)
if err := binary.Read(r, binary.BigEndian, &data); err != nil {
return nil, err
}
return &Comment{
header: header,
data: data[:],
}, nil
}
|
package tsin
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01000101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsin.010.001.01 Document"`
Message *PartyRegistrationAndGuaranteeStatusV01 `xml:"PtyRegnAndGrntSts"`
}
func (d *Document01000101) AddMessage() *PartyRegistrationAndGuaranteeStatusV01 {
d.Message = new(PartyRegistrationAndGuaranteeStatusV01)
return d.Message
}
// The message PartyRegistrationAndGuaranteeStatus is either sent by a factoring service to a financing client to indicate the status of a factoring service agreement or from a guarantee issuer to a factoring client or a factoring service to indicate the guarantee covering a requested factoring service agreement. The message can also be sent to an interested party.
// The factoring service or guarantee issuer may include references to a corresponding PartyRegistrationAndGuaranteeRequest message or other related messages and may include referenced data.
// The message contains information about other parties to be notified about the financial service agreement or the guarantee and whether these parties are required to acknowledge the agreement.
// The message contains information returned by the financial institution indicating acceptance or rejection of the trade partner; a positive response is necessary before being able to assign financial items concerning the trade party.
// This message contains identifications of cash accounts to enable payer and payee to treat the transferred payment obligations.
// The message can carry digital signatures if required by context.
type PartyRegistrationAndGuaranteeStatusV01 struct {
// Set of characteristics that unambiguously identify the status, common parameters, documents and identifications.
Header *iso20022.BusinessLetter1 `xml:"Hdr"`
// List of agreements.
AgreementList []*iso20022.FinancingAgreementList1 `xml:"AgrmtList"`
// Number of agreement lists as control value.
AgreementCount *iso20022.Max15NumericText `xml:"AgrmtCnt,omitempty"`
// Total number of individual items in all lists.
ItemCount *iso20022.Max15NumericText `xml:"ItmCnt,omitempty"`
// Total of all individual amounts included in all lists, irrespective of currencies or direction.
ControlSum *iso20022.DecimalNumber `xml:"CtrlSum,omitempty"`
// Referenced or related business message.
AttachedMessage []*iso20022.EncapsulatedBusinessMessage1 `xml:"AttchdMsg,omitempty"`
}
func (p *PartyRegistrationAndGuaranteeStatusV01) AddHeader() *iso20022.BusinessLetter1 {
p.Header = new(iso20022.BusinessLetter1)
return p.Header
}
func (p *PartyRegistrationAndGuaranteeStatusV01) AddAgreementList() *iso20022.FinancingAgreementList1 {
newValue := new(iso20022.FinancingAgreementList1)
p.AgreementList = append(p.AgreementList, newValue)
return newValue
}
func (p *PartyRegistrationAndGuaranteeStatusV01) SetAgreementCount(value string) {
p.AgreementCount = (*iso20022.Max15NumericText)(&value)
}
func (p *PartyRegistrationAndGuaranteeStatusV01) SetItemCount(value string) {
p.ItemCount = (*iso20022.Max15NumericText)(&value)
}
func (p *PartyRegistrationAndGuaranteeStatusV01) SetControlSum(value string) {
p.ControlSum = (*iso20022.DecimalNumber)(&value)
}
func (p *PartyRegistrationAndGuaranteeStatusV01) AddAttachedMessage() *iso20022.EncapsulatedBusinessMessage1 {
newValue := new(iso20022.EncapsulatedBusinessMessage1)
p.AttachedMessage = append(p.AttachedMessage, newValue)
return newValue
}
|
package main
import (
"fmt"
"strconv"
)
func sendWithBuffer(ch chan int) {
count := 100
for count > 0 {
ch <- count
fmt.Println("send " + strconv.Itoa(count))
count--
}
close(ch)
}
func receiveWithBuffer(ch chan int) {
for {
value, ok := <- ch
if ok {
fmt.Println("receive " + strconv.Itoa(value))
} else {
break
}
}
}
func main() {
chBuffer := make(chan int, 10)
go receiveWithBuffer(chBuffer)
sendWithBuffer(chBuffer)
}
|
package service
import (
"encoding/json"
"errors"
"fmt"
"io"
"krpc/codec"
"krpc/conf"
"log"
"net"
"reflect"
"strings"
"sync"
"time"
)
// Connection's message between client & server
// | Option{..., CodeType: xxx} | Header..., Body ... | Header2, Body2, ...
// |<------ Json Encode ------> | <------ Encode With CodeType ------> |
// Server represents an RPC server
type Server struct {
serviceMap sync.Map // service Name, service
opt *conf.Option
}
func NewServer() *Server {
return &Server{}
}
// DefaultServer the instance of *Server
var DefaultServer = NewServer()
// Register publishes in the server
// init service's methodTypes...
func (s *Server) Register(rcvr interface{}) error {
svc := newService(rcvr)
if _, dup := s.serviceMap.LoadOrStore(svc.name, svc); dup {
return errors.New("rpc: service already defined: " + svc.name)
}
return nil
}
// findService find service from serviceMap
// argument: service.method
// 1. check service in serviceMap
// 2. check method in service.method
func (s *Server) findService(serviceMethod string) (svc *service, mtype *methodType, err error) {
dot := strings.LastIndex(serviceMethod, ".")
if dot < 0 {
err = errors.New("rpc server: service/method request ill-format: " + serviceMethod)
return
}
serviceName, methodName := serviceMethod[:dot], serviceMethod[dot+1:]
// Load: return interface{}
svci, ok := s.serviceMap.Load(serviceName)
if !ok {
err = errors.New("rpc server: can't find service " + serviceName)
return
}
svc = svci.(*service)
mtype = svc.method[methodName]
if mtype == nil {
err = errors.New("rpc server: can't find method " + methodName)
}
return
}
// Accept , lis: {Accept, Close, Addr}
func (s *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Printf("rpc server: accept error: %s\n", err)
return
}
go s.ServeConn(conn)
}
}
// ServeConn one goroutine per connection
// net.Conn {read, write, close...}
func (s *Server) ServeConn(conn io.ReadWriteCloser) {
// decode a Option instance
defer func() { _ = conn.Close() }()
var opt conf.Option
if err := json.NewDecoder(conn).Decode(&opt); err != nil {
log.Printf("rpc server: decode option error: %s\n", err)
return
}
if opt.MagicNumber != conf.MagicNumber {
log.Printf("rpc server: MagicNumber dismatch, your magic: %v\n", opt.MagicNumber)
return
}
newCodecF := codec.NewCodecFuncMap[opt.CodeType]
if newCodecF == nil {
log.Printf("rpc server: code type not found%s\n", opt.CodeType)
return
}
s.opt = &opt
s.serveCodec(newCodecF(conn))
}
// a placeholder in response when error occurs.
var invalidRequest = struct{}{}
// serveCodec get request & serve (decode every request...)
func (s *Server) serveCodec(cc codec.Codec) {
sending := new(sync.Mutex)
wg := new(sync.WaitGroup)
for {
req, err := s.readRequest(cc)
if err != nil {
if req == nil {
break // can't recover, close the connection
}
req.h.Error = err.Error()
s.sendResponse(cc, req.h, invalidRequest, sending)
continue
}
wg.Add(1)
go s.handleRequest(cc, req, sending, wg, s.opt.HandleTimeout)
}
wg.Wait()
}
type request struct {
h *codec.Header
argv, replyv reflect.Value
mtype *methodType
svc *service
}
// readRequest read request from client.
// check service.method...
func (s *Server) readRequest(c codec.Codec) (*request, error) {
h, err := s.readRequestHeader(c)
if err != nil {
return nil, err
}
req := &request{h: h}
// check if the server has the service.method
req.svc, req.mtype, err = s.findService(h.ServiceMethod)
if err != nil {
return req, err
}
// "占位" & init argv
req.argv = req.mtype.newArgv()
req.replyv = req.mtype.newReply()
// make sure that argvi is a pointer, ReadBody need a pointer as parameter.
// argv: instance or ptr... need check it!
argvi := req.argv.Interface()
if req.argv.Type().Kind() != reflect.Ptr {
// get pointer.
argvi = req.argv.Addr().Interface()
}
// ReadBody(&item)
if err = c.ReadBody(argvi); err != nil {
log.Printf("rpc server: read argv err: %s\n", err)
}
return req, nil
}
// readRequestHeader read & decode header with codec
func (s *Server) readRequestHeader(cc codec.Codec) (*codec.Header, error) {
var h codec.Header
if err := cc.ReadHeader(&h); err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
log.Printf("rpc server: read header error: %s\n", err)
}
return nil, err
}
return &h, nil
}
// handleRequest handle client's request if no error.
// todo: send chan ?
func (s *Server) handleRequest(cc codec.Codec, req *request, sending *sync.Mutex, wg *sync.WaitGroup, timeout time.Duration) {
defer wg.Done()
callCh := make(chan struct{})
go func() {
err := req.svc.call(req.mtype, req.argv, req.replyv)
callCh <- struct{}{}
// call it...
if err != nil {
req.h.Error = err.Error()
s.sendResponse(cc, req.h, invalidRequest, sending)
return
}
s.sendResponse(cc, req.h, req.replyv.Interface(), sending)
}()
if timeout == 0 {
<- callCh
return
}
select {
case <- time.After(timeout):
req.h.Error = fmt.Sprintf("rpc server: request handle timeout ")
s.sendResponse(cc, req.h, invalidRequest, sending)
case <- callCh:
return
}
}
// sendResponse need mutex
func (s *Server) sendResponse(c codec.Codec, h *codec.Header, body interface{}, sending *sync.Mutex) {
sending.Lock()
defer sending.Unlock()
if err := c.Write(h, body); err != nil {
log.Printf("rpc server: write response err: %s\n", err)
}
}
// Accept Usual accept method
func Accept(lis net.Listener) { DefaultServer.Accept(lis) }
|
package main
import "fmt"
func Example_simple() {
fmt.Println("this is not it")
// Output:
// this is it
}
|
package main
import (
"encoding/json"
"os"
"strings"
"fmt"
)
type person struct {
Fname string
Lname string
Age int //start with caps to export and thus print data after using marshal
}
func main() {
p1 :=person{"AMan","Patel",21}
//p2 :=person{"acd","gupta",22,2}
json.NewEncoder(os.Stdout).Encode(p1) //encode
var i int
//json.NewEncoder(os.Stdout).Encode(i)
var p2 person
t :=strings.NewReader(`{"Fname":"AMan","Lname":"Patel","Age":21}`)
json.NewDecoder(t).Decode(&p2) //decode
fmt.Println(p2)
t1 :=strings.NewReader(`2`)
json.NewDecoder(t1).Decode(&i) //decode
fmt.Println(i)
}
|
package util
import (
"camp/lib"
"errors"
"github.com/globalsign/mgo/bson"
)
func TokenToUid(base lib.IBase) (uid bson.ObjectId, err error) {
if v, exists := base.GetParam("uid"); !exists {
return bson.ObjectIdHex(""), errors.New("uid not exists")
} else {
uid = v.(bson.ObjectId)
}
return
}
|
package publickey
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"github.com/SIGBlockchain/project_aurum/internal/hashing"
)
// AurumPublicKey struct holds public key for user
type AurumPublicKey struct {
Key *ecdsa.PublicKey
Bytes []byte
Hex string
Hash []byte
}
// NewFromPublic returns an AurumPublicKey given a ecdsa.PublicKey
func NewFromPublic(key *ecdsa.PublicKey) (AurumPublicKey, error) {
bytes, err := Encode(key)
if err != nil {
return AurumPublicKey{}, errors.New("Failed to encode public key inside of private key")
}
return AurumPublicKey{Key: key, Bytes: bytes, Hex: hex.EncodeToString(bytes), Hash: hashing.New(bytes)}, nil
}
// New returns an AurumPublicKey given a ecdsa.PrivateKey
func New(key *ecdsa.PrivateKey) (AurumPublicKey, error) {
//try type assertion
k, ok := key.Public().(*ecdsa.PublicKey)
if !ok {
return AurumPublicKey{}, errors.New("Cannot extract a ecdsa public key from private key given")
}
return NewFromPublic(k)
}
// Encode returns the PEM-Encoded byte slice from a given public key or a non-nil error if fail
func Encode(key *ecdsa.PublicKey) ([]byte, error) {
if key == nil {
return nil, errors.New("Could not return the encoded public key - the key value is nil")
}
x509EncodedPub, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub}), nil
}
// Decode returns the public key from a given PEM-Encoded byte slice representation of the public key or a non-nil error if fail
func Decode(key []byte) (*ecdsa.PublicKey, error) {
if key == nil {
return nil, errors.New("Could not return the decoded public key - the key value is nil")
}
blockPub, _ := pem.Decode(key)
// pem.Decode will return nil for the first value if no PEM data is found. This would be bad
if blockPub == nil {
return nil, errors.New("Could not return the public key - failed to PEM decode in preparation x509 encode")
}
x509EncodedPub := blockPub.Bytes
genericPublicKey, err := x509.ParsePKIXPublicKey(x509EncodedPub)
if err != nil {
return nil, err
}
return genericPublicKey.(*ecdsa.PublicKey), nil
}
// Equals returns true if the given two *ecdsa.PublicKey are equal
func (pbKey AurumPublicKey) Equals(pbKey2 *ecdsa.PublicKey) bool {
if pbKey.Key == nil || pbKey2 == nil {
return false
}
if pbKey.Key.X.Cmp(pbKey2.X) != 0 ||
pbKey.Key.Y.Cmp(pbKey2.Y) != 0 ||
pbKey.Key.Curve != pbKey2.Curve {
return false
}
return true
}
|
package core
// BoolType express SQL boolean including Null
type BoolType int
const (
// True is true of BoolType
True BoolType = iota
// False is false of BoolType
False
// Null is null of BoolType
Null
)
type WildcardType int
const (
Wildcard WildcardType = iota
)
// ColType is a type of column
type ColType int
const (
Integer ColType = iota
VarChar
)
// ColumnName is column name
type ColumnName struct {
TableName string
Name string
}
func (cn ColumnName) String() string {
if cn.TableName == "" {
return cn.Name
}
return cn.TableName + "." + cn.Name
}
// Copy copies ColumnName
func (cn ColumnName) Copy() ColumnName {
return ColumnName{
TableName: cn.TableName,
Name: cn.Name,
}
}
// ColumnNames is list of ColumnName
type ColumnNames []ColumnName
// Copy copies ColumnNames
func (cn ColumnNames) Copy() ColumnNames {
names := make(ColumnNames, 0, len(cn))
for _, name := range cn {
names = append(names, name.Copy())
}
return names
}
// Equal checks the equality of ColumnName
func (cn ColumnName) Equal(other ColumnName) bool {
return cn.TableName == other.TableName && cn.Name == other.Name
}
// Equal checks the equality of ColumnNames
func (cn ColumnNames) Equal(others ColumnNames) bool {
if len(cn) != len(others) {
return false
}
if len(cn) == len(others) && len(cn) == 0 {
return true
}
for k, name := range cn {
if !name.Equal(others[k]) {
return false
}
}
return true
}
// Value is any type for column
type Value interface{}
// Values is list of Value
type Values []Value
// ValuesList is list of Values
type ValuesList []Values
// Col is type of column
type Col struct {
ColName ColumnName
ColType ColType
}
// Cols is list of Col
type Cols []Col
// Equal check the equality of Col
func (col Col) Equal(other Col) bool {
return col.ColName.Equal(other.ColName) && col.ColType == other.ColType
}
// Equal checks the equality of Cols
func (cols Cols) Equal(others Cols) bool {
for k, col := range cols {
if !col.Equal(others[k]) {
return false
}
}
return true
}
// NotEqual checks the non-equality of Cols
func (cols Cols) NotEqual(others Cols) bool {
return !cols.Equal(others)
}
// Copy copies Col.
func (col Col) Copy() Col {
return Col{col.ColName, col.ColType}
}
// Copy copies Cols.
func (cols Cols) Copy() Cols {
newCols := make(Cols, 0, len(cols))
for _, col := range cols {
newCols = append(newCols, col.Copy())
}
return newCols
}
|
package main
import (
"fmt"
)
// https://leetcode-cn.com/problems/gray-code/
// 89. 格雷编码 | Gray Code
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Solution
//
// 找规律
// i res | bit | xor res[i-1]
// ------+------+-------------
// 0. 0 | 0000 |
// 1. 1 | 0001 | 1
// 2. 3 | 0011 | 2
// 3. 2 | 0010 | 1
// 4. 6 | 0110 | 4
// 5. 7 | 0111 | 1
// 6. 5 | 0101 | 2
// 7. 4 | 0100 | 1
// 8. 12 | 1100 | 8
// 9. 13 | 1101 | 1
// 10. 15 | 1111 | 2
// 11. 14 | 1110 | 1
// 12. 10 | 1010 | 4
// 13. 11 | 1011 | 1
// 14. 9 | 1001 | 2
// 15. 8 | 1000 | 1
// 复杂度分析:
// * 时间:
// * 空间:
func grayCode(n int) []int {
if n == 0 {
return []int{0}
}
N := 1 << uint(n)
res := make([]int, N)
res[0], res[1] = 0, 1
for i, e := 1, 2; i < n; i++ {
res[e] = e
copy(res[e+1:], res[1:e])
e <<= 1
}
for i := 1; i < N; i++ {
res[i] ^= res[i-1]
}
return res
}
// 看前两列的规律: res[i] = i^(i>>1)
func grayCode1(n int) []int {
var res []int
N := 1 << uint(n)
for i := 0; i < N; i++ {
res = append(res, i^(i>>1))
}
return res
}
//------------------------------------------------------------------------------
// main
func main() {
cases := []int{
3, 4,
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(grayCode(c))
fmt.Println(grayCode1(c))
}
a := []int{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8}
for i, v := range a {
fmt.Printf("%2d. %2d | %04b |", i, v, v)
if i != 0 {
fmt.Printf(" %2d\n", v^a[i-1])
} else {
fmt.Println()
}
}
}
|
// Copyright 2017
// Author: catlittlechen@gmail.com
package main
import (
"encoding/json"
"fmt"
"github.com/catlittlechen/nexus"
"github.com/garyburd/redigo/redis"
"time"
)
type config struct {
Addr string `json:"addr"`
DB int `json:"db"`
PoolSize int `json:"poolsize"`
Idle int `json:"idle"`
}
// Redis the implement of nexus.DB
type Redis struct {
cfg string
pool *redis.Pool
}
// NewRedis .
func NewRedis(cfg string) (nexus.DB, error) {
var obj config
fmt.Println(cfg)
err := json.Unmarshal([]byte(cfg), &obj)
if nil != err {
return nil, err
}
return &Redis{
cfg: cfg,
pool: NewRedisPool(obj.Addr, obj.DB, obj.PoolSize, obj.PoolSize),
}, nil
}
// Set .
func (r *Redis) Set(key string, value string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("SET", key, value)
return err
}
// Get .
func (r *Redis) Get(key string) (string, error) {
conn := r.pool.Get()
defer conn.Close()
value, err := redis.String(conn.Do("GET", key))
if err == redis.ErrNil {
err = nexus.ErrKeyNotFound
}
return value, err
}
// Del .
func (r *Redis) Del(key string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", key)
return err
}
// Close .
func (r *Redis) Close() error {
err := r.pool.Close()
return err
}
// String .
func (r *Redis) String() string {
return r.cfg
}
// NewRedisPool init Redis pool
func NewRedisPool(addr string, db, poolsize, idle int) *redis.Pool {
return &redis.Pool{
MaxIdle: poolsize,
IdleTimeout: time.Duration(idle) * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", addr)
if err != nil {
fmt.Printf("Redis Dial Error: %s\n", err.Error())
return nil, err
}
if _, err = c.Do("SELECT", db); err != nil {
fmt.Printf("Redis SELECT Error: %s\n", err.Error())
c.Close()
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
|
package main
import (
"encoding/json"
"fmt"
"net"
"crypto/md5"
"encoding/hex"
"github.com/m4ttclendenen/basen"
)
type Message struct {
Code int
Payload json.RawMessage
}
type Range struct {
Start []byte
End []byte
}
type User struct {
ID int
Pass int
}
type Job struct {
Hash string
Range Range
}
type Password struct {
Value string
}
func main() {
////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Test Data //////////////////////////////////
////////////////////////////////////////////////////////////////////////////
password := "ax3"
// hash the password
hasher := md5.New()
hasher.Write([]byte(password))
hash := hex.EncodeToString(hasher.Sum(nil))
fmt.Printf("\nHash: %s\n", hash)
// base 62 arithmetic
base62 := basen.New([]byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), 62)
// Starting string
currBase := []byte("0")
// Increment set to 4C92 = 1,000,000 in base10
increment := []byte("4C92")
// Prepare server address for listener
sAddr := net.UDPAddr {
Port: 1234,
IP: net.ParseIP("127.0.0.1"),
}
fmt.Printf("Server Address: %+v\n", sAddr)
// listener for incoming clients
conn, err := net.ListenUDP("udp", &sAddr)
if err != nil {
fmt.Printf("Error %v", err)
return
}
// keep listening
for {
read := make([]byte, 2048)
// Blocking call
n, cAddr, err := conn.ReadFromUDP(read)
if err != nil {
fmt.Printf("Error %v", err)
return
}
inMessage := Message{}
err = json.Unmarshal(read[:n], &inMessage)
if err != nil {
fmt.Printf("Error %v\n", err)
return
}
fmt.Printf("\nMessage Received!\nFrom Address: %s\nCode: %v\n", cAddr, inMessage.Code)
if inMessage.Code == 1 {
newBase := base62.Add(currBase, increment)
minorRange := Range {
Start: currBase,
End: newBase,
}
job := Job {
Hash: hash,
Range: minorRange,
}
// Update current base
currBase = newBase
// Marshall data
j, err := json.Marshal(job)
if err != nil {
fmt.Printf("Error %v", err)
return
}
outMessage := Message {
Code: 2,
Payload: j,
}
om, err := json.Marshal(outMessage)
if err != nil {
fmt.Printf("Error %v", err)
return
}
_, err = conn.WriteToUDP(om, cAddr)
if err != nil {
fmt.Printf("Error %v", err)
return
}
fmt.Printf("\nMessage Sent!\nTo Address: %s\nCode: %v\nRange: %v - %v\n",
cAddr, outMessage.Code, minorRange.Start, minorRange.End)
} else if inMessage.Code == 3 {
password := Password{}
err = json.Unmarshal(inMessage.Payload, &password)
fmt.Printf("Client Found the Password! %s\n", password.Value)
return
}
}
}
|
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"database/sql"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/br/pkg/version"
tcontext "github.com/pingcap/tidb/dumpling/context"
"go.uber.org/zap"
)
// rowIter implements the SQLRowIter interface.
// Note: To create a rowIter, please use `newRowIter()` instead of struct literal.
type rowIter struct {
rows *sql.Rows
hasNext bool
args []interface{}
}
func newRowIter(rows *sql.Rows, argLen int) *rowIter {
r := &rowIter{
rows: rows,
hasNext: false,
args: make([]interface{}, argLen),
}
r.hasNext = r.rows.Next()
return r
}
func (iter *rowIter) Close() error {
return iter.rows.Close()
}
func (iter *rowIter) Decode(row RowReceiver) error {
return decodeFromRows(iter.rows, iter.args, row)
}
func (iter *rowIter) Error() error {
return errors.Trace(iter.rows.Err())
}
func (iter *rowIter) Next() {
iter.hasNext = iter.rows.Next()
}
func (iter *rowIter) HasNext() bool {
return iter.hasNext
}
// multiQueriesChunkIter implements the SQLRowIter interface.
// Note: To create a rowIter, please use `newRowIter()` instead of struct literal.
type multiQueriesChunkIter struct {
tctx *tcontext.Context
conn *sql.Conn
rows *sql.Rows
hasNext bool
id int
queries []string
args []interface{}
err error
}
func newMultiQueryChunkIter(tctx *tcontext.Context, conn *sql.Conn, queries []string, argLen int) *multiQueriesChunkIter {
r := &multiQueriesChunkIter{
tctx: tctx,
conn: conn,
queries: queries,
id: 0,
args: make([]interface{}, argLen),
}
r.nextRows()
return r
}
func (iter *multiQueriesChunkIter) nextRows() {
if iter.id >= len(iter.queries) {
iter.hasNext = false
return
}
var err error
defer func() {
if err != nil {
iter.hasNext = false
iter.err = errors.Trace(err)
}
}()
tctx, conn := iter.tctx, iter.conn
// avoid the empty chunk
for iter.id < len(iter.queries) {
rows := iter.rows
if rows != nil {
if err = rows.Close(); err != nil {
return
}
if err = rows.Err(); err != nil {
return
}
}
tctx.L().Debug("try to start nextRows", zap.String("query", iter.queries[iter.id]))
rows, err = conn.QueryContext(tctx, iter.queries[iter.id])
if err != nil {
return
}
if err = rows.Err(); err != nil {
return
}
iter.id++
iter.rows = rows
iter.hasNext = iter.rows.Next()
if iter.hasNext {
return
}
}
}
func (iter *multiQueriesChunkIter) Close() error {
if iter.err != nil {
return iter.err
}
if iter.rows != nil {
return iter.rows.Close()
}
return nil
}
func (iter *multiQueriesChunkIter) Decode(row RowReceiver) error {
if iter.err != nil {
return iter.err
}
if iter.rows == nil {
return errors.Errorf("no valid rows found, id: %d", iter.id)
}
return decodeFromRows(iter.rows, iter.args, row)
}
func (iter *multiQueriesChunkIter) Error() error {
if iter.err != nil {
return iter.err
}
if iter.rows != nil {
return errors.Trace(iter.rows.Err())
}
return nil
}
func (iter *multiQueriesChunkIter) Next() {
if iter.err == nil {
iter.hasNext = iter.rows.Next()
if !iter.hasNext {
iter.nextRows()
}
}
}
func (iter *multiQueriesChunkIter) HasNext() bool {
return iter.hasNext
}
type stringIter struct {
idx int
ss []string
}
func newStringIter(ss ...string) StringIter {
return &stringIter{
idx: 0,
ss: ss,
}
}
func (m *stringIter) Next() string {
if m.idx >= len(m.ss) {
return ""
}
ret := m.ss[m.idx]
m.idx++
return ret
}
func (m *stringIter) HasNext() bool {
return m.idx < len(m.ss)
}
type tableData struct {
query string
rows *sql.Rows
colLen int
needColTypes bool
colTypes []string
SQLRowIter
}
func newTableData(query string, colLength int, needColTypes bool) *tableData {
return &tableData{
query: query,
colLen: colLength,
needColTypes: needColTypes,
}
}
func (td *tableData) Start(tctx *tcontext.Context, conn *sql.Conn) error {
tctx.L().Debug("try to start tableData", zap.String("query", td.query))
rows, err := conn.QueryContext(tctx, td.query)
if err != nil {
return errors.Annotatef(err, "sql: %s", td.query)
}
if err = rows.Err(); err != nil {
return errors.Annotatef(err, "sql: %s", td.query)
}
td.SQLRowIter = nil
td.rows = rows
if td.needColTypes {
ns, err := rows.Columns()
if err != nil {
return errors.Trace(err)
}
td.colLen = len(ns)
td.colTypes = make([]string, 0, td.colLen)
colTps, err := rows.ColumnTypes()
if err != nil {
return errors.Trace(err)
}
for _, c := range colTps {
td.colTypes = append(td.colTypes, c.DatabaseTypeName())
}
}
return nil
}
func (td *tableData) Rows() SQLRowIter {
// should be initialized lazily since it calls rows.Next() which might close the rows when
// there's nothing to read, causes code which relies on rows not closed to fail.
if td.SQLRowIter == nil {
td.SQLRowIter = newRowIter(td.rows, td.colLen)
}
return td.SQLRowIter
}
func (td *tableData) Close() error {
if td.SQLRowIter != nil {
// will close td.rows internally
return td.SQLRowIter.Close()
} else if td.rows != nil {
return td.rows.Close()
}
return nil
}
func (td *tableData) RawRows() *sql.Rows {
return td.rows
}
type tableMeta struct {
database string
table string
colTypes []*sql.ColumnType
selectedField string
selectedLen int
specCmts []string
showCreateTable string
showCreateView string
avgRowLength uint64
hasImplicitRowID bool
}
func (tm *tableMeta) ColumnTypes() []string {
colTypes := make([]string, len(tm.colTypes))
for i, ct := range tm.colTypes {
colTypes[i] = ct.DatabaseTypeName()
}
return colTypes
}
func (tm *tableMeta) ColumnNames() []string {
colNames := make([]string, len(tm.colTypes))
for i, ct := range tm.colTypes {
colNames[i] = ct.Name()
}
return colNames
}
func (tm *tableMeta) DatabaseName() string {
return tm.database
}
func (tm *tableMeta) TableName() string {
return tm.table
}
func (tm *tableMeta) ColumnCount() uint {
return uint(len(tm.colTypes))
}
func (tm *tableMeta) SelectedField() string {
return tm.selectedField
}
func (tm *tableMeta) SelectedLen() int {
return tm.selectedLen
}
func (tm *tableMeta) SpecialComments() StringIter {
return newStringIter(tm.specCmts...)
}
func (tm *tableMeta) ShowCreateTable() string {
return tm.showCreateTable
}
func (tm *tableMeta) ShowCreateView() string {
return tm.showCreateView
}
func (tm *tableMeta) AvgRowLength() uint64 {
return tm.avgRowLength
}
func (tm *tableMeta) HasImplicitRowID() bool {
return tm.hasImplicitRowID
}
type metaData struct {
target string
metaSQL string
specCmts []string
}
func (m *metaData) SpecialComments() StringIter {
return newStringIter(m.specCmts...)
}
func (m *metaData) TargetName() string {
return m.target
}
func (m *metaData) MetaSQL() string {
if !strings.HasSuffix(m.metaSQL, ";\n") {
m.metaSQL += ";\n"
}
return m.metaSQL
}
type multiQueriesChunk struct {
tctx *tcontext.Context
conn *sql.Conn
queries []string
colLen int
SQLRowIter
}
func newMultiQueriesChunk(queries []string, colLength int) *multiQueriesChunk {
return &multiQueriesChunk{
queries: queries,
colLen: colLength,
}
}
func (td *multiQueriesChunk) Start(tctx *tcontext.Context, conn *sql.Conn) error {
td.tctx = tctx
td.conn = conn
td.SQLRowIter = nil
return nil
}
func (td *multiQueriesChunk) Rows() SQLRowIter {
if td.SQLRowIter == nil {
td.SQLRowIter = newMultiQueryChunkIter(td.tctx, td.conn, td.queries, td.colLen)
}
return td.SQLRowIter
}
func (td *multiQueriesChunk) Close() error {
if td.SQLRowIter != nil {
return td.SQLRowIter.Close()
}
return nil
}
func (*multiQueriesChunk) RawRows() *sql.Rows {
return nil
}
var serverSpecialComments = map[version.ServerType][]string{
version.ServerTypeMySQL: {
"/*!40014 SET FOREIGN_KEY_CHECKS=0*/;",
"/*!40101 SET NAMES binary*/;",
},
version.ServerTypeTiDB: {
"/*!40014 SET FOREIGN_KEY_CHECKS=0*/;",
"/*!40101 SET NAMES binary*/;",
},
version.ServerTypeMariaDB: {
"/*!40101 SET NAMES binary*/;",
"SET FOREIGN_KEY_CHECKS=0;",
},
}
func getSpecialComments(serverType version.ServerType) []string {
return serverSpecialComments[serverType]
}
|
package usecase
import (
"github.com/dkpeakbil/taskserver/domain"
)
type UseCase interface {
Register(*domain.RegisterRequest) *domain.RegisterResponse
Auth(request *domain.AuthRequest) *domain.AuthResponse
AuthGame(request *domain.AuthGameRequest) *domain.AuthGameResponse
GetUsers(request *domain.GetUsersRequest) *domain.GetUsersResponse
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.