text stringlengths 11 4.05M |
|---|
package hsm
import "container/list"
import "errors"
// Trigger() is a helper function to dispatch event of different types to
// the corresponding method.
func Trigger(hsm HSM, state State, event Event) State {
switch event.Type() {
case EventEmpty:
return state.Super()
case EventInit:
return state.Init(hsm, event)
case EventEntry:
return state.Entry(hsm, event)
case EventExit:
return state.Exit(hsm, event)
default:
return state.Handle(hsm, event)
}
}
func TriggerInit(hsm HSM, state State, event Event) State {
return state.Init(hsm, event)
}
func TriggerEntry(hsm HSM, state State, event Event) State {
return state.Entry(hsm, event)
}
func TriggerExit(hsm HSM, state State, event Event) State {
return state.Exit(hsm, event)
}
func Record(
stdEvent Event, actions *list.List, hsm HSM, state State, event Event) {
var trigger func(hsm HSM, state State, event Event) State
switch stdEvent.Type() {
case EventInit:
trigger = TriggerInit
case EventEntry:
trigger = TriggerEntry
case EventExit:
trigger = TriggerExit
default:
// invalid call
AssertTrue(false)
}
if trigger(hsm, state, event) == nil {
action := &StaticTranAction{
State: state,
Event: stdEvent,
}
actions.PushBack(action)
}
}
func RecordInit(actions *list.List, hsm HSM, state State, event Event) {
Record(StdEvents[EventInit], actions, hsm, state, event)
}
func RecordEntry(actions *list.List, hsm HSM, state State, event Event) {
Record(StdEvents[EventEntry], actions, hsm, state, event)
}
func RecordExit(actions *list.List, hsm HSM, state State, event Event) {
Record(StdEvents[EventExit], actions, hsm, state, event)
}
// ListTruncate() removes elements from `e' to the last element in list `l'.
// The range to be removed is [e, l.Back()]. It returns list `l'.
func ListTruncate(l *list.List, e *list.Element) *list.List {
AssertNotEqual(nil, l)
AssertNotEqual(nil, e)
// remove `e' and all elements after `e'
var next *list.Element
for ; e != nil; e = next {
next = e.Next()
l.Remove(e)
}
return l
}
// ListFind() searchs the first element which has the same value of `value' in
// list `l'. It uses object comparation for equality check.
func ListFind(l *list.List, value interface{}) (*list.Element, error) {
predicate := func(v interface{}) bool {
return ObjectAreEqual(value, v)
}
return ListFindIf(l, predicate)
}
// ListFindIf() searchs for and element of the list `l' that
// satifies the predicate function `predicate'.
func ListFindIf(l *list.List, predicate func(value interface{}) bool) (*list.Element, error) {
for e := l.Front(); e != nil; e = e.Next() {
if predicate(e.Value) {
return e, nil
}
}
return nil, errors.New("find no match")
}
// ListIn() tests whether `value' is in list `l'.
func ListIn(l *list.List, value interface{}) bool {
e, err := ListFind(l, value)
if e == nil && err != nil {
return false
}
return true
}
|
package proxy
import (
"context"
"crypto/cipher"
"fmt"
"net/url"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/sessions/cookie"
"github.com/pomerium/pomerium/pkg/cryptutil"
"github.com/pomerium/pomerium/pkg/grpc"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
"github.com/pomerium/pomerium/pkg/hpke"
)
var outboundGRPCConnection = new(grpc.CachedOutboundGRPClientConn)
type proxyState struct {
sharedKey []byte
sharedCipher cipher.AEAD
authenticateURL *url.URL
authenticateDashboardURL *url.URL
authenticateSigninURL *url.URL
authenticateRefreshURL *url.URL
encoder encoding.MarshalUnmarshaler
cookieSecret []byte
sessionStore sessions.SessionStore
jwtClaimHeaders config.JWTClaimHeaders
hpkePrivateKey *hpke.PrivateKey
authenticateKeyFetcher hpke.KeyFetcher
dataBrokerClient databroker.DataBrokerServiceClient
programmaticRedirectDomainWhitelist []string
}
func newProxyStateFromConfig(cfg *config.Config) (*proxyState, error) {
err := ValidateOptions(cfg.Options)
if err != nil {
return nil, err
}
state := new(proxyState)
state.sharedKey, err = cfg.Options.GetSharedKey()
if err != nil {
return nil, err
}
state.hpkePrivateKey, err = cfg.Options.GetHPKEPrivateKey()
if err != nil {
return nil, err
}
state.authenticateKeyFetcher, err = cfg.GetAuthenticateKeyFetcher()
if err != nil {
return nil, fmt.Errorf("authorize: get authenticate JWKS key fetcher: %w", err)
}
state.sharedCipher, err = cryptutil.NewAEADCipher(state.sharedKey)
if err != nil {
return nil, err
}
state.cookieSecret, err = cfg.Options.GetCookieSecret()
if err != nil {
return nil, err
}
// used to load and verify JWT tokens signed by the authenticate service
state.encoder, err = jws.NewHS256Signer(state.sharedKey)
if err != nil {
return nil, err
}
state.jwtClaimHeaders = cfg.Options.JWTClaimsHeaders
// errors checked in ValidateOptions
state.authenticateURL, err = cfg.Options.GetAuthenticateURL()
if err != nil {
return nil, err
}
state.authenticateDashboardURL = state.authenticateURL.ResolveReference(&url.URL{Path: "/.pomerium/"})
state.authenticateSigninURL = state.authenticateURL.ResolveReference(&url.URL{Path: signinURL})
state.authenticateRefreshURL = state.authenticateURL.ResolveReference(&url.URL{Path: refreshURL})
state.sessionStore, err = cookie.NewStore(func() cookie.Options {
return cookie.Options{
Name: cfg.Options.CookieName,
Domain: cfg.Options.CookieDomain,
Secure: cfg.Options.CookieSecure,
HTTPOnly: cfg.Options.CookieHTTPOnly,
Expire: cfg.Options.CookieExpire,
SameSite: cfg.Options.GetCookieSameSite(),
}
}, state.encoder)
if err != nil {
return nil, err
}
dataBrokerConn, err := outboundGRPCConnection.Get(context.Background(), &grpc.OutboundOptions{
OutboundPort: cfg.OutboundPort,
InstallationID: cfg.Options.InstallationID,
ServiceName: cfg.Options.Services,
SignedJWTKey: state.sharedKey,
})
if err != nil {
return nil, err
}
state.dataBrokerClient = databroker.NewDataBrokerServiceClient(dataBrokerConn)
state.programmaticRedirectDomainWhitelist = cfg.Options.ProgrammaticRedirectDomainWhitelist
return state, nil
}
|
package paillier
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/base64"
"fmt"
"math/big"
)
var curve = elliptic.P256()
// ECDSASignature is the structure for marshall signature
type ECDSASignature struct {
R, S *big.Int
}
func Commit(prvkey *ecdsa.PrivateKey, cipher, user string) (string, error) {
msg := cipher + user
hash := sha256.Sum256([]byte(msg))
pk := prvkey.PublicKey
pubkey := elliptic.Marshal(pk.Curve, pk.X, pk.Y)
r, s, err := ecdsa.Sign(rand.Reader, prvkey, hash[:])
if err != nil {
return "", fmt.Errorf("ecdsa sign error: %v", err)
}
sigRS := ECDSASignature{r, s}
sig, err := asn1.Marshal(sigRS)
if err != nil {
return "", fmt.Errorf("marshal signature error: %v", err)
}
commitment := make([]byte, 65+len(sig))
copy(commitment[0:], pubkey)
copy(commitment[65:], sig)
return base64.RawStdEncoding.EncodeToString(commitment), nil
}
// authorization check
func CheckCommitment(cipher, user, commitment string) (bool, error) {
commData, err := base64.RawStdEncoding.DecodeString(commitment)
if err != nil {
return false, fmt.Errorf("decode commitment error: %v", err)
}
hash := sha256.Sum256([]byte(cipher + user))
x, y := elliptic.Unmarshal(curve, commData[:65])
pub := &ecdsa.PublicKey{curve, x, y}
sig := commData[65:]
sigRS := new(ECDSASignature)
_, err = asn1.Unmarshal(sig, sigRS)
if err != nil {
return false, fmt.Errorf("unmarshal signature error: %v", err)
}
return ecdsa.Verify(pub, hash[:], sigRS.R, sigRS.S), nil
}
|
package httputil
import (
"encoding/json"
"io"
"net/http"
"github.com/go-playground/form"
)
type response struct {
StatusCode int `json:"status_code"`
Messages []string `json:"messages"`
Data interface{} `json:"data"`
}
func marshalJSONResponse(statusCode int, messages []string, data interface{}) ([]byte, error) {
resp := response{
statusCode,
messages,
data,
}
bs, err := json.Marshal(&resp)
if err != nil {
return nil, err
}
return bs, nil
}
func AcceptAllRequest(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
func DecodeFormRequest(r *http.Request, req interface{}) error {
decoder := form.NewDecoder()
r.ParseForm()
err := decoder.Decode(&req, r.Form)
switch {
case err == io.EOF:
return nil
case err != nil:
return err
}
return nil
}
func DecodeJSONRequest(r *http.Request, req interface{}) error {
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
return nil
case err != nil:
return err
}
return nil
}
func EncodeJSONResponse(resp interface{}) ([]byte, error) {
return json.Marshal(&resp)
}
func SetContentJSON(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
}
func SetContentHTML(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html")
}
func WriteInternalServerError(w http.ResponseWriter) {
w.WriteHeader(500)
w.Write([]byte(ErrInternalServerError.Error()))
}
func WriteDecodeRequestError(w http.ResponseWriter, exampleReq interface{}) {
WriteResponse(w, 400, []string{ErrDecodeRequest.Error()}, exampleReq)
}
func WriteRedirectResponse(w http.ResponseWriter, url string) {
w.Header().Set("Location", url)
w.WriteHeader(301)
}
func WriteErrorResponse(w http.ResponseWriter, err error, statusCode int, messages []string, data interface{}) {
if err == ErrInternalServerError {
WriteInternalServerError(w)
return
}
WriteResponse(w, statusCode, messages, data)
}
func WriteResponse(w http.ResponseWriter, statusCode int, messages []string, data interface{}) {
resp, err := marshalJSONResponse(statusCode, messages, data)
if err != nil {
WriteInternalServerError(w)
return
}
w.WriteHeader(statusCode)
w.Write(resp)
}
|
package util
import (
"bytes"
"crypto/ecdsa"
"crypto/sm2"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
)
func PriKeyToPem(sm2PriKey interface{}) (pemPriKey string, err error) {
priKeyStream, _ := x509.MarshalSm2PrivateKey(sm2PriKey.(*sm2.PrivateKey))
fmt.Println("-----------------SM2私钥字节-----------------")
fmt.Println(priKeyStream)
fmt.Println("length:", len(priKeyStream))
block := &pem.Block{
Type: "SM2 PRIVATE KEY",
Bytes: priKeyStream,
}
priKey := bytes.NewBuffer(make([]byte, 0))
err = pem.Encode(priKey, block)
if err != nil {
return "", errors.New("Encode failed")
}
pemPriKey = priKey.String()
return pemPriKey, nil
}
func DerKeyToPem(keyBytes []byte) (pemPriKey string, err error) {
block := &pem.Block{
Type: "PRIVATE KEY",
Bytes: keyBytes,
}
priKey := bytes.NewBuffer(make([]byte, 0))
err = pem.Encode(priKey, block)
if err != nil {
return "", errors.New("Encode failed")
}
pemPriKey = priKey.String()
return pemPriKey, nil
}
func ECKeyToSM2Key(ecKey ecdsa.PublicKey) sm2.PublicKey {
sm2PubKey := sm2.PublicKey{
Curve: ecKey.Curve,
X: ecKey.X,
Y: ecKey.Y,
}
return sm2PubKey
}
|
/*
description :
helloworld is a Go version of the Hello World program
author :
Tom Geudens (https://github.com/tomgeudens/)
modified :
2017/07/17
*/
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, 世界")
}
|
package queue
// (slice)
type Queue struct {
Ele []interface{}
}
func NewQueue() *Queue {
return &Queue{
Ele: make([]interface{}, 0),
}
}
func (q Queue) Empty() bool {
if q.Ele == nil || len(q.Ele) == 0 {
return true
}
return false
}
func (q Queue) Size() int {
return len(q.Ele)
}
// 入队列
func (q *Queue) Offer(item interface{}) {
q.Ele = append(q.Ele, item)
}
// 出队并删除
func (q *Queue) Poll() interface{} {
if q.Size() > 0 {
v := q.Ele[0]
q.Ele = q.Ele[1:q.Size()] // [ )
return v
}
return nil
}
// 出队不删除
func (q *Queue) Peek() interface{} {
if q.Size() > 0 {
return q.Ele[0]
}
return nil
}
func (q *Queue) GetAll() []interface{} {
return q.Ele
}
|
// ˅
package main
import (
"fmt"
"os"
)
// ˄
type HTMLBuilder struct {
// ˅
// ˄
// File name to create
result string
writer *os.File
// ˅
// ˄
}
func NewHTMLBuilder() *HTMLBuilder {
// ˅
return &HTMLBuilder{}
// ˄
}
// Make a title of HTML file
func (self *HTMLBuilder) CreateTitle(title string) {
// ˅
self.result = title + ".html" // Set a title as a file name
var err error
self.writer, err = os.Create(self.result)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
self.writer.WriteString("<html><head><title>" + title + "</title></head><body>\n")
self.writer.WriteString("<h1>" + title + "</h1>\n")
// ˄
}
// Make a section of HTML file
func (self *HTMLBuilder) CreateSection(section string) {
// ˅
self.writer.WriteString("<p>" + section + "</p>\n") // Write a section
// ˄
}
// Make items of HTML file
func (self *HTMLBuilder) CreateItems(items []string) {
// ˅
self.writer.WriteString("<ul>\n") // Write items
for i := 0; i < len(items); i++ {
self.writer.WriteString("<li>" + items[i] + "</li>\n")
}
self.writer.WriteString("</ul>\n")
// ˄
}
func (self *HTMLBuilder) Close() {
// ˅
self.writer.WriteString("</body></html>\n")
defer self.writer.Close() // Close file
// ˄
}
// ˅
// ˄
|
// Package route and its subpackages provides
// most of what you need for http server.
//
//
package route
import (
"os"
chi "github.com/go-chi/chi"
docgen "github.com/go-chi/docgen"
// middleware "github.com/go-chi/chi/middleware"
)
// Router embeds chi router
type Router struct {
chi.Router
}
// New returns new instance of router
func New() Router {
return Router{chi.NewRouter()}
}
// GenerateDocs json docs string for the router
func GenerateDocs(r Router) string {
// docgen need gopath for whatever reason
if gp := os.Getenv("GOPATH"); gp == "" {
os.Setenv("GOPATH", "/dummy")
}
return docgen.JSONRoutesDoc(r.Router)
}
|
package cgo
import (
"fmt"
"strings"
"github.com/graphql-go/graphql"
)
// UserRoleType role of user
var UserRoleType = graphql.NewEnum(graphql.EnumConfig{
Name: "UserRole",
Description: "The role of the user",
Values: graphql.EnumValueConfigMap{
strings.ToUpper(ContextRoleAdmin): &graphql.EnumValueConfig{
Value: ContextRoleAdmin,
},
strings.ToUpper(ContextRoleStaff): &graphql.EnumValueConfig{
Value: ContextRoleStaff,
},
strings.ToUpper(ContextRoleUser): &graphql.EnumValueConfig{
Value: ContextRoleUser,
},
},
})
// UserStateType state of user
var UserStateType = graphql.NewEnum(graphql.EnumConfig{
Name: "UserState",
Description: "The state of the user",
Values: graphql.EnumValueConfigMap{
strings.ToUpper(ContextStateEnable): &graphql.EnumValueConfig{
Value: ContextStateEnable,
},
strings.ToUpper(ContextStateDisable): &graphql.EnumValueConfig{
Value: ContextStateDisable,
},
strings.ToUpper(ContextStateMaintenance): &graphql.EnumValueConfig{
Value: ContextStateMaintenance,
},
},
})
// NewUserTypeFields return default UserType fields
func NewUserTypeFields(fields graphql.Fields) graphql.Fields {
userFields := graphql.Fields{
"id": GlobalIDField("User"),
"email": &graphql.Field{
Type: graphql.String,
Description: "The email of the user.",
},
"username": &graphql.Field{
Type: graphql.String,
Description: "The name of the user.",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
u := p.Source.(Context)
return u.Username.Ptr(), nil
},
},
"hasPassword": &graphql.Field{
Type: graphql.Boolean,
Description: "Is password is defined.",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
u := p.Source.(Context)
return u.Password.Ptr() != nil, nil
},
},
"displayName": &graphql.Field{
Type: graphql.String,
Description: "The name of the user.",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
u := p.Source.(Context)
return u.DisplayName.Ptr(), nil
},
},
"picture": &graphql.Field{
Type: graphql.String,
Description: "The picture of the user.",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
u := p.Source.(Context)
return u.Picture.Ptr(), nil
},
},
"avatar": &graphql.Field{
Type: graphql.String,
Description: "The avatar of the user.",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
u := p.Source.(Context)
if u.Picture.Ptr() == nil {
return fmt.Sprintf("https://www.gravatar.com/avatar/%s?d=identicon&s=68", u.EmailHash), nil
}
return u.Picture.Ptr(), nil
},
},
"role": &graphql.Field{
Type: UserRoleType,
},
"state": &graphql.Field{
Type: UserStateType,
},
}
for key, field := range fields {
userFields[key] = field
}
return userFields
}
|
// Package ut implements some testing utilities. So far it includes CallTracker, which helps you build
// mock implementations of interfaces.
package ut
import (
"bytes"
"fmt"
"reflect"
"runtime"
"sync"
"testing"
)
// CallTracker is an interface to help build mocks.
//
// Build the CallTracker interface into your mocks. Use TrackCall within mock methods to track calls to the method
// and the parameters used.
// Within tests use AddCall to add expected method calls, and SetReturns to indicate what the calls will return.
//
// The tests for this package contain a full example.
//
// type MyMock struct {ut.CallTracker}
//
// func (m *MyMock) AFunction(p int) error {
// r := m.TrackCall("AFunction", p)
// return NilOrError(r[0])
// }
//
// func Something(m Functioner) {
// m.AFunction(37)
// }
//
// func TestSomething(t *testing.T) {
// m := &MyMock{NewCallRecords(t)}
// m.AddCall("AFunction", 37).SetReturns(nil)
//
// Something(m)
//
// m.AssertDone()
// }
type CallTracker interface {
// AddCall() is used by tests to add an expected call to the tracker
AddCall(name string, params ...any) CallTracker
// SetReturns() is called immediately after AddCall() to set the return
// values for the call.
SetReturns(returns ...any) CallTracker
// TrackCall() is called within mocks to track a call to the Mock. It
// returns the return values registered via SetReturns()
TrackCall(name string, params ...any) []any
// AssertDone() should be called at the end of a test to confirm all
// the expected calls have been made
AssertDone()
// RecordCall() is called to indicate calls to the named mock method should
// be recorded rather than asserted. The parameters to any call to the
// named method will be recorded and may be retrieved via GetRecordedParams.
// The returns from the method are also specified on this call and must be
// the same each time.
// Note that the ordering of recorded calls relative to other calls is not
// tracked.
RecordCall(name string, returns ...any) CallTracker
// GetRecordedParams returns the sets of parameters passed to a call captured
// via RecordCall
GetRecordedParams(name string) ([][]any, bool)
}
type callRecord struct {
name string
params []any
returns []any
}
func (e *callRecord) assert(t testing.TB, name string, params ...any) {
if name != e.name {
t.Logf("Expected call to %s%s", e.name, paramsToString(e.params))
t.Logf(" got call to %s%s", name, paramsToString(params))
showStack(t)
t.Fail()
return
}
if len(params) != len(e.params) {
t.Logf("Call to (%s) unexpected parameters", name)
t.Logf(" expected %s", paramsToString(e.params))
t.Logf(" got %s", paramsToString(params))
showStack(t)
t.FailNow()
return
}
for i, ap := range params {
ep := e.params[i]
if ap == nil && ep == nil {
continue
}
switch ep := ep.(type) {
case func(actual any):
ep(ap)
default:
if !reflect.DeepEqual(ap, ep) {
t.Logf("Call to %s parameter %d unexpected", name, i)
t.Logf(" expected %#v (%T)", ep, ep)
t.Logf(" got %#v (%T)", ap, ap)
showStack(t)
t.Fail()
}
}
}
}
func showStack(t testing.TB) {
pc := make([]uintptr, 10)
n := runtime.Callers(4, pc)
for i := 0; i < n; i++ {
f := runtime.FuncForPC(pc[i])
file, line := f.FileLine(pc[i])
t.Logf(" %s (%s line %d", f.Name(), file, line)
}
}
func paramsToString(params []any) string {
w := &bytes.Buffer{}
w.WriteString("(")
l := len(params)
for i, p := range params {
fmt.Fprintf(w, "%#v", p)
if i < l-1 {
w.WriteString(", ")
}
}
w.WriteString(")")
return w.String()
}
// recording tracks calls actually made to the mock. It is used only when the
// user choses to record calls for a method rather than assert them
type recording struct {
// The returned values are the same for each call to a recorded method.
returns []any
// We record the parameters from each call to the method.
params [][]any
}
type callRecords struct {
sync.Mutex
t testing.TB
calls []callRecord
records map[string]*recording
current int
}
// NewCallRecords creates a new call tracker
func NewCallRecords(t testing.TB) CallTracker {
return &callRecords{
t: t,
records: make(map[string]*recording),
}
}
func (cr *callRecords) AddCall(name string, params ...any) CallTracker {
cr.calls = append(cr.calls, callRecord{name: name, params: params})
return cr
}
func (cr *callRecords) RecordCall(name string, returns ...any) CallTracker {
cr.records[name] = &recording{
returns: returns,
params: make([][]any, 0),
}
return cr
}
func (cr *callRecords) SetReturns(returns ...any) CallTracker {
cr.calls[len(cr.calls)-1].returns = returns
return cr
}
func (cr *callRecords) TrackCall(name string, params ...any) []any {
cr.Lock()
defer cr.Unlock()
if record, ok := cr.records[name]; ok {
// Call is to be recorded, not asserted
record.params = append(record.params, params)
return record.returns
}
// Call is to be asserted
if cr.current >= len(cr.calls) {
cr.t.Logf("Unexpected call to %s%s", name, paramsToString(params))
showStack(cr.t)
cr.t.FailNow()
}
expectedCall := cr.calls[cr.current]
expectedCall.assert(cr.t, name, params...)
cr.current += 1
return expectedCall.returns
}
func (cr *callRecords) AssertDone() {
if cr.current < len(cr.calls) {
// We don't call Fatalf or FailNow because that may mask other errors if this AssertDone
// is called from a defer
missed := &bytes.Buffer{}
for i, call := range cr.calls[cr.current:] {
if i != 0 {
missed.WriteString(", ")
}
missed.WriteString(call.name)
}
cr.t.Errorf("Only %d of %d expected calls made. Missed calls to %s", cr.current, len(cr.calls), missed)
}
}
func (cr *callRecords) GetRecordedParams(name string) ([][]any, bool) {
cr.Lock()
defer cr.Unlock()
record, ok := cr.records[name]
if ok {
return record.params, true
}
return nil, false
}
// NilOrError is a utility function for returning err from mocked methods
func NilOrError(val any) error {
if val == nil {
return nil
}
return val.(error)
}
|
// Generated from AdlP.g4 by ANTLR 4.7.
package adllp // AdlP
import "github.com/wxio/goantlr"
// AdlPListener is a complete listener for a parse tree produced by AdlP.
type AdlPListener interface {
antlr.ParseTreeListener
AdlEntryListener
AdlExitListener
ModuleStatementEntryListener
ModuleStatementExitListener
ImportScopedNameEntryListener
ImportScopedNameExitListener
ImportModuleNameEntryListener
ImportModuleNameExitListener
LocalAnnoEntryListener
LocalAnnoExitListener
DocAnnoEntryListener
DocAnnoExitListener
ModuleAnnotationEntryListener
ModuleAnnotationExitListener
DeclAnnotationEntryListener
DeclAnnotationExitListener
FieldAnnotationEntryListener
FieldAnnotationExitListener
StructOrUnionEntryListener
StructOrUnionExitListener
TypeOrNewtypeEntryListener
TypeOrNewtypeExitListener
TypeParameterEntryListener
TypeParameterExitListener
TypeExprSimpleEntryListener
TypeExprSimpleExitListener
TypeExprGenericEntryListener
TypeExprGenericExitListener
FieldStatementEntryListener
FieldStatementExitListener
StringStatementEntryListener
StringStatementExitListener
TrueFalseNullEntryListener
TrueFalseNullExitListener
NumberStatementEntryListener
NumberStatementExitListener
FloatStatementEntryListener
FloatStatementExitListener
ArrayStatementEntryListener
ArrayStatementExitListener
ObjStatementEntryListener
ObjStatementExitListener
JsonObjStatementEntryListener
JsonObjStatementExitListener
}
//
// Rules with unnamed alternatives
//
type AdlEntryListener interface {
EnterAdl(c *AdlContext)
}
type AdlExitListener interface {
ExitAdl(c *AdlContext)
}
//
// Named alternatives
//
//
// From Rule 'module'
type ModuleStatementEntryListener interface {
EnterModuleStatement(c *ModuleStatementContext)
}
type ModuleStatementExitListener interface {
ExitModuleStatement(c *ModuleStatementContext)
}
// From Rule 'imports'
type ImportScopedNameEntryListener interface {
EnterImportScopedName(c *ImportScopedNameContext)
}
type ImportScopedNameExitListener interface {
ExitImportScopedName(c *ImportScopedNameContext)
}
// From Rule 'imports'
type ImportModuleNameEntryListener interface {
EnterImportModuleName(c *ImportModuleNameContext)
}
type ImportModuleNameExitListener interface {
ExitImportModuleName(c *ImportModuleNameContext)
}
// From Rule 'annon'
type LocalAnnoEntryListener interface {
EnterLocalAnno(c *LocalAnnoContext)
}
type LocalAnnoExitListener interface {
ExitLocalAnno(c *LocalAnnoContext)
}
// From Rule 'annon'
type DocAnnoEntryListener interface {
EnterDocAnno(c *DocAnnoContext)
}
type DocAnnoExitListener interface {
ExitDocAnno(c *DocAnnoContext)
}
// From Rule 'top_level_statement'
type ModuleAnnotationEntryListener interface {
EnterModuleAnnotation(c *ModuleAnnotationContext)
}
type ModuleAnnotationExitListener interface {
ExitModuleAnnotation(c *ModuleAnnotationContext)
}
// From Rule 'top_level_statement'
type DeclAnnotationEntryListener interface {
EnterDeclAnnotation(c *DeclAnnotationContext)
}
type DeclAnnotationExitListener interface {
ExitDeclAnnotation(c *DeclAnnotationContext)
}
// From Rule 'top_level_statement'
type FieldAnnotationEntryListener interface {
EnterFieldAnnotation(c *FieldAnnotationContext)
}
type FieldAnnotationExitListener interface {
ExitFieldAnnotation(c *FieldAnnotationContext)
}
// From Rule 'top_level_statement'
type StructOrUnionEntryListener interface {
EnterStructOrUnion(c *StructOrUnionContext)
}
type StructOrUnionExitListener interface {
ExitStructOrUnion(c *StructOrUnionContext)
}
// From Rule 'top_level_statement'
type TypeOrNewtypeEntryListener interface {
EnterTypeOrNewtype(c *TypeOrNewtypeContext)
}
type TypeOrNewtypeExitListener interface {
ExitTypeOrNewtype(c *TypeOrNewtypeContext)
}
// From Rule 'typeParam'
type TypeParameterEntryListener interface {
EnterTypeParameter(c *TypeParameterContext)
}
type TypeParameterExitListener interface {
ExitTypeParameter(c *TypeParameterContext)
}
// From Rule 'typeExpr'
type TypeExprSimpleEntryListener interface {
EnterTypeExprSimple(c *TypeExprSimpleContext)
}
type TypeExprSimpleExitListener interface {
ExitTypeExprSimple(c *TypeExprSimpleContext)
}
// From Rule 'typeExpr'
type TypeExprGenericEntryListener interface {
EnterTypeExprGeneric(c *TypeExprGenericContext)
}
type TypeExprGenericExitListener interface {
ExitTypeExprGeneric(c *TypeExprGenericContext)
}
// From Rule 'soruBody'
type FieldStatementEntryListener interface {
EnterFieldStatement(c *FieldStatementContext)
}
type FieldStatementExitListener interface {
ExitFieldStatement(c *FieldStatementContext)
}
// From Rule 'jsonValue'
type StringStatementEntryListener interface {
EnterStringStatement(c *StringStatementContext)
}
type StringStatementExitListener interface {
ExitStringStatement(c *StringStatementContext)
}
// From Rule 'jsonValue'
type TrueFalseNullEntryListener interface {
EnterTrueFalseNull(c *TrueFalseNullContext)
}
type TrueFalseNullExitListener interface {
ExitTrueFalseNull(c *TrueFalseNullContext)
}
// From Rule 'jsonValue'
type NumberStatementEntryListener interface {
EnterNumberStatement(c *NumberStatementContext)
}
type NumberStatementExitListener interface {
ExitNumberStatement(c *NumberStatementContext)
}
// From Rule 'jsonValue'
type FloatStatementEntryListener interface {
EnterFloatStatement(c *FloatStatementContext)
}
type FloatStatementExitListener interface {
ExitFloatStatement(c *FloatStatementContext)
}
// From Rule 'jsonValue'
type ArrayStatementEntryListener interface {
EnterArrayStatement(c *ArrayStatementContext)
}
type ArrayStatementExitListener interface {
ExitArrayStatement(c *ArrayStatementContext)
}
// From Rule 'jsonValue'
type ObjStatementEntryListener interface {
EnterObjStatement(c *ObjStatementContext)
}
type ObjStatementExitListener interface {
ExitObjStatement(c *ObjStatementContext)
}
// From Rule 'jsonObj'
type JsonObjStatementEntryListener interface {
EnterJsonObjStatement(c *JsonObjStatementContext)
}
type JsonObjStatementExitListener interface {
ExitJsonObjStatement(c *JsonObjStatementContext)
}
|
embedded_components {
id: "sprite"
type: "sprite"
data: "tile_set: \"/main/outfit_lg.atlas\"\n"
"default_animation: \"dollv_blazer\"\n"
"material: \"/materials/solid.material\"\n"
"blend_mode: BLEND_MODE_ALPHA\n"
""
position {
x: 0.0
y: 0.0
z: 0.0
}
rotation {
x: 0.0
y: 0.0
z: 0.0
w: 1.0
}
}
|
package main
import (
"log"
)
// RainDrop holds the state of a single raindrop
type RainDrop struct {
char rune
x int
y int
}
// Rain holds the state of all raindrops
// Density detemines number of raindrops created for a rain
// For a rain with 50w and 20h, the area is 50 * 20 = 1000
// Density of 0.5 means 0.5 * 1000 = 500 raindrops
type Rain struct {
w int
h int
density float64
drops []*RainDrop
}
// NewRain creates a new rain
func NewRain(w, h int, density float64) *Rain {
log.Println("create new rain...")
// Create rain
rain := &Rain{w: w, h: h, density: density}
// Create raindrops
area := rain.w * rain.h
totalDrops := int(rain.density * float64(area))
drops := make([]*RainDrop, totalDrops)
for i := range drops {
// We want more heavy drops than light drops
// To create the illusion of depth
var char rune
switch RandInt(0, 5) {
case 0, 1, 2:
char = '|'
case 3, 4:
char = ':'
case 5:
char = '.'
}
drop := &RainDrop{
char: char,
x: RandInt(0, rain.w-1),
y: RandInt(-rain.h, -1),
}
drops[i] = drop
}
rain.drops = drops
log.Printf("rain = {drops:[%d], w:%d, h:%d}", len(rain.drops), rain.w, rain.h)
return rain
}
// Fall updates the state of rainfall by one tick
func (r *Rain) Fall() {
for _, drop := range r.drops {
if drop.y+1 < r.h {
drop.y++
} else {
// If a raindrop has reached the ground, reset its position
drop.x = RandInt(0, r.w-1)
drop.y = 0
}
}
}
|
// 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 config
import (
"container/list"
"context"
"sync"
"time"
)
// List is a goroutine-safe FIFO list of *Config, which supports removal
// from the middle. The list is not expected to be very long.
type List struct {
cond *sync.Cond
taskIDMap map[int64]*list.Element
nodes list.List
// lastID records the largest task ID being Push()'ed to the List.
// In the rare case where two Push() are executed in the same nanosecond
// (or the not-so-rare case where the clock's precision is lower than CPU
// speed), we'll need to manually force one of the task to use the ID as
// lastID + 1.
lastID int64
}
// NewConfigList creates a new ConfigList instance.
func NewConfigList() *List {
return &List{
cond: sync.NewCond(new(sync.Mutex)),
taskIDMap: make(map[int64]*list.Element),
}
}
// Push adds a configuration to the end of the list. The field `cfg.TaskID` will
// be modified to include a unique ID to identify this task.
func (cl *List) Push(cfg *Config) {
id := time.Now().UnixNano()
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
if id <= cl.lastID {
id = cl.lastID + 1
}
cfg.TaskID = id
cl.lastID = id
cl.taskIDMap[id] = cl.nodes.PushBack(cfg)
cl.cond.Broadcast()
}
// Pop removes a configuration from the front of the list. If the list is empty,
// this method will block until either another goroutines calls Push() or the
// input context expired.
//
// If the context expired, the error field will contain the error from context.
func (cl *List) Pop(ctx context.Context) (*Config, error) {
res := make(chan *Config)
go func() {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
for {
if front := cl.nodes.Front(); front != nil {
cfg := front.Value.(*Config)
delete(cl.taskIDMap, cfg.TaskID)
cl.nodes.Remove(front)
res <- cfg
break
}
cl.cond.Wait()
}
}()
select {
case cfg := <-res:
return cfg, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Remove removes a task from the list given its task ID. Returns true if a task
// is successfully removed, false if the task ID did not exist.
func (cl *List) Remove(taskID int64) bool {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
element, ok := cl.taskIDMap[taskID]
if !ok {
return false
}
delete(cl.taskIDMap, taskID)
cl.nodes.Remove(element)
return true
}
// Get obtains a task from the list given its task ID. If the task ID did not
// exist, the returned bool field will be false.
func (cl *List) Get(taskID int64) (*Config, bool) {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
element, ok := cl.taskIDMap[taskID]
if !ok {
return nil, false
}
return element.Value.(*Config), true
}
// AllIDs returns a list of all task IDs in the list.
func (cl *List) AllIDs() []int64 {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
res := make([]int64, 0, len(cl.taskIDMap))
for element := cl.nodes.Front(); element != nil; element = element.Next() {
res = append(res, element.Value.(*Config).TaskID)
}
return res
}
// MoveToFront moves a task to the front of the list. Returns true if the task
// is successfully moved (including no-op), false if the task ID did not exist.
func (cl *List) MoveToFront(taskID int64) bool {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
element, ok := cl.taskIDMap[taskID]
if !ok {
return false
}
cl.nodes.MoveToFront(element)
return true
}
// MoveToBack moves a task to the back of the list. Returns true if the task is
// successfully moved (including no-op), false if the task ID did not exist.
func (cl *List) MoveToBack(taskID int64) bool {
cl.cond.L.Lock()
defer cl.cond.L.Unlock()
element, ok := cl.taskIDMap[taskID]
if !ok {
return false
}
cl.nodes.MoveToBack(element)
return true
}
|
package lambda
import (
"encoding/json"
"io"
"io/ioutil"
"os"
)
type configLoader struct {
ConfigURL string `json:"config_url"`
}
// ReadFromFile reads a file from disk
func (c *configLoader) ReadFromFile(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
config, err := ioutil.ReadAll(f)
if err := json.Unmarshal(config, c); err != nil {
return err
}
return nil
}
// LoadConfig from a file on disk
func LoadConfig(name string) (*configLoader, error) {
config := new(configLoader)
if err := config.ReadFromFile(name); err != nil {
return nil, err
}
return config, nil
}
// Config holder object
type Config struct {
Bucket string `json:"bucket"`
EnvironmentName string `json:"environment_name"`
KMSKeyID string `json:"kms_key_id"`
}
// ReadFromFile reads a file from disk
func (c *Config) ReadFromReader(r io.Reader) error {
config, err := ioutil.ReadAll(r)
if err != nil {
return err
}
if err := json.Unmarshal(config, c); err != nil {
return err
}
return nil
}
|
package email
// Custom map implementation as GoLang maps are not ordered
type Map struct {
Key string
Value string
}
|
// Copyright 2022 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 executor_test
import (
"encoding/json"
"fmt"
"strconv"
"testing"
"time"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics/handle"
"github.com/pingcap/tidb/testkit"
"github.com/stretchr/testify/require"
"github.com/tikv/client-go/v2/oracle"
)
func TestRecordHistoryStatsAfterAnalyze(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set @@tidb_analyze_version = 2")
tk.MustExec("set global tidb_enable_historical_stats = 0")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b varchar(10))")
h := dom.StatsHandle()
is := dom.InfoSchema()
tableInfo, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
// 1. switch off the tidb_enable_historical_stats, and there is no records in table `mysql.stats_history`
rows := tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'", tableInfo.Meta().ID)).Rows()
num, _ := strconv.Atoi(rows[0][0].(string))
require.Equal(t, num, 0)
tk.MustExec("analyze table t with 2 topn")
rows = tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'", tableInfo.Meta().ID)).Rows()
num, _ = strconv.Atoi(rows[0][0].(string))
require.Equal(t, num, 0)
// 2. switch on the tidb_enable_historical_stats and do analyze
tk.MustExec("set global tidb_enable_historical_stats = 1")
defer tk.MustExec("set global tidb_enable_historical_stats = 0")
tk.MustExec("analyze table t with 2 topn")
// dump historical stats
hsWorker := dom.GetHistoricalStatsWorker()
tblID := hsWorker.GetOneHistoricalStatsTable()
err = hsWorker.DumpHistoricalStats(tblID, h)
require.Nil(t, err)
rows = tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'", tableInfo.Meta().ID)).Rows()
num, _ = strconv.Atoi(rows[0][0].(string))
require.GreaterOrEqual(t, num, 1)
// 3. dump current stats json
dumpJSONTable, err := h.DumpStatsToJSON("test", tableInfo.Meta(), nil, true)
require.NoError(t, err)
jsOrigin, _ := json.Marshal(dumpJSONTable)
// 4. get the historical stats json
rows = tk.MustQuery(fmt.Sprintf("select * from mysql.stats_history where table_id = '%d' and create_time = ("+
"select create_time from mysql.stats_history where table_id = '%d' order by create_time desc limit 1) "+
"order by seq_no", tableInfo.Meta().ID, tableInfo.Meta().ID)).Rows()
num = len(rows)
require.GreaterOrEqual(t, num, 1)
data := make([][]byte, num)
for i, row := range rows {
data[i] = []byte(row[1].(string))
}
jsonTbl, err := handle.BlocksToJSONTable(data)
require.NoError(t, err)
jsCur, err := json.Marshal(jsonTbl)
require.NoError(t, err)
// 5. historical stats must be equal to the current stats
require.JSONEq(t, string(jsOrigin), string(jsCur))
}
func TestRecordHistoryStatsMetaAfterAnalyze(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set @@tidb_analyze_version = 2")
tk.MustExec("set global tidb_enable_historical_stats = 0")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b int)")
tk.MustExec("analyze table test.t")
h := dom.StatsHandle()
is := dom.InfoSchema()
tableInfo, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
// 1. switch off the tidb_enable_historical_stats, and there is no record in table `mysql.stats_meta_history`
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d'", tableInfo.Meta().ID)).Check(testkit.Rows("0"))
// insert demo tuples, and there is no record either.
insertNums := 5
for i := 0; i < insertNums; i++ {
tk.MustExec("insert into test.t (a,b) values (1,1), (2,2), (3,3)")
err := h.DumpStatsDeltaToKV(handle.DumpDelta)
require.NoError(t, err)
}
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d'", tableInfo.Meta().ID)).Check(testkit.Rows("0"))
// 2. switch on the tidb_enable_historical_stats and insert tuples to produce count/modifyCount delta change.
tk.MustExec("set global tidb_enable_historical_stats = 1")
defer tk.MustExec("set global tidb_enable_historical_stats = 0")
for i := 0; i < insertNums; i++ {
tk.MustExec("insert into test.t (a,b) values (1,1), (2,2), (3,3)")
err := h.DumpStatsDeltaToKV(handle.DumpDelta)
require.NoError(t, err)
}
tk.MustQuery(fmt.Sprintf("select modify_count, count from mysql.stats_meta_history where table_id = '%d' order by create_time", tableInfo.Meta().ID)).Sort().Check(
testkit.Rows("18 18", "21 21", "24 24", "27 27", "30 30"))
tk.MustQuery(fmt.Sprintf("select distinct source from mysql.stats_meta_history where table_id = '%d'", tableInfo.Meta().ID)).Sort().Check(testkit.Rows("flush stats"))
// assert delete
tk.MustExec("delete from test.t where test.t.a = 1")
err = h.DumpStatsDeltaToKV(handle.DumpAll)
require.NoError(t, err)
tk.MustQuery(fmt.Sprintf("select modify_count, count from mysql.stats_meta where table_id = '%d' order by create_time desc", tableInfo.Meta().ID)).Sort().Check(
testkit.Rows("40 20"))
tk.MustQuery(fmt.Sprintf("select modify_count, count from mysql.stats_meta_history where table_id = '%d' order by create_time desc limit 1", tableInfo.Meta().ID)).Sort().Check(
testkit.Rows("40 20"))
// assert update
tk.MustExec("update test.t set test.t.b = 4 where test.t.a = 2")
err = h.DumpStatsDeltaToKV(handle.DumpAll)
require.NoError(t, err)
tk.MustQuery(fmt.Sprintf("select modify_count, count from mysql.stats_meta where table_id = '%d' order by create_time desc", tableInfo.Meta().ID)).Sort().Check(
testkit.Rows("50 20"))
tk.MustQuery(fmt.Sprintf("select modify_count, count from mysql.stats_meta_history where table_id = '%d' order by create_time desc limit 1", tableInfo.Meta().ID)).Sort().Check(
testkit.Rows("50 20"))
}
func TestGCHistoryStatsAfterDropTable(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 1")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b varchar(10))")
tk.MustExec("analyze table test.t")
is := dom.InfoSchema()
tableInfo, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
// dump historical stats
h := dom.StatsHandle()
hsWorker := dom.GetHistoricalStatsWorker()
tblID := hsWorker.GetOneHistoricalStatsTable()
err = hsWorker.DumpHistoricalStats(tblID, h)
require.Nil(t, err)
// assert the records of history stats table
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d' order by create_time",
tableInfo.Meta().ID)).Check(testkit.Rows("1"))
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'",
tableInfo.Meta().ID)).Check(testkit.Rows("1"))
// drop the table and gc stats
tk.MustExec("drop table t")
is = dom.InfoSchema()
h.GCStats(is, 0)
// assert stats_history tables delete the record of dropped table
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d' order by create_time",
tableInfo.Meta().ID)).Check(testkit.Rows("0"))
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'",
tableInfo.Meta().ID)).Check(testkit.Rows("0"))
}
func TestAssertHistoricalStatsAfterAlterTable(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 1")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b varchar(10),c int, KEY `idx` (`c`))")
tk.MustExec("analyze table test.t")
is := dom.InfoSchema()
tableInfo, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
// dump historical stats
h := dom.StatsHandle()
hsWorker := dom.GetHistoricalStatsWorker()
tblID := hsWorker.GetOneHistoricalStatsTable()
err = hsWorker.DumpHistoricalStats(tblID, h)
require.Nil(t, err)
time.Sleep(1 * time.Second)
snapshot := oracle.GoTimeToTS(time.Now())
jsTable, _, err := h.DumpHistoricalStatsBySnapshot("test", tableInfo.Meta(), snapshot)
require.NoError(t, err)
require.NotNil(t, jsTable)
require.NotEqual(t, jsTable.Version, uint64(0))
originVersion := jsTable.Version
// assert historical stats non-change after drop column
tk.MustExec("alter table t drop column b")
h.GCStats(is, 0)
snapshot = oracle.GoTimeToTS(time.Now())
jsTable, _, err = h.DumpHistoricalStatsBySnapshot("test", tableInfo.Meta(), snapshot)
require.NoError(t, err)
require.NotNil(t, jsTable)
require.Equal(t, jsTable.Version, originVersion)
// assert historical stats non-change after drop index
tk.MustExec("alter table t drop index idx")
h.GCStats(is, 0)
snapshot = oracle.GoTimeToTS(time.Now())
jsTable, _, err = h.DumpHistoricalStatsBySnapshot("test", tableInfo.Meta(), snapshot)
require.NoError(t, err)
require.NotNil(t, jsTable)
require.Equal(t, jsTable.Version, originVersion)
}
func TestGCOutdatedHistoryStats(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 1")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b varchar(10))")
tk.MustExec("analyze table test.t")
is := dom.InfoSchema()
tableInfo, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
// dump historical stats
h := dom.StatsHandle()
hsWorker := dom.GetHistoricalStatsWorker()
tblID := hsWorker.GetOneHistoricalStatsTable()
err = hsWorker.DumpHistoricalStats(tblID, h)
require.Nil(t, err)
// assert the records of history stats table
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d' order by create_time",
tableInfo.Meta().ID)).Check(testkit.Rows("1"))
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'",
tableInfo.Meta().ID)).Check(testkit.Rows("1"))
tk.MustExec("set @@global.tidb_historical_stats_duration = '1s'")
duration := variable.HistoricalStatsDuration.Load()
fmt.Println(duration.String())
time.Sleep(2 * time.Second)
err = dom.StatsHandle().ClearOutdatedHistoryStats()
require.NoError(t, err)
// assert the records of history stats table
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_meta_history where table_id = '%d' order by create_time",
tableInfo.Meta().ID)).Check(testkit.Rows("0"))
tk.MustQuery(fmt.Sprintf("select count(*) from mysql.stats_history where table_id = '%d'",
tableInfo.Meta().ID)).Check(testkit.Rows("0"))
}
func TestPartitionTableHistoricalStats(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 1")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec(`CREATE TABLE t (a int, b int, index idx(b))
PARTITION BY RANGE ( a ) (
PARTITION p0 VALUES LESS THAN (6)
)`)
tk.MustExec("delete from mysql.stats_history")
tk.MustExec("analyze table test.t")
// dump historical stats
h := dom.StatsHandle()
hsWorker := dom.GetHistoricalStatsWorker()
// assert global table and partition table be dumped
tblID := hsWorker.GetOneHistoricalStatsTable()
err := hsWorker.DumpHistoricalStats(tblID, h)
require.NoError(t, err)
tblID = hsWorker.GetOneHistoricalStatsTable()
err = hsWorker.DumpHistoricalStats(tblID, h)
require.NoError(t, err)
tk.MustQuery("select count(*) from mysql.stats_history").Check(testkit.Rows("2"))
}
func TestDumpHistoricalStatsByTable(t *testing.T) {
failpoint.Enable("github.com/pingcap/tidb/domain/sendHistoricalStats", "return(true)")
defer failpoint.Disable("github.com/pingcap/tidb/domain/sendHistoricalStats")
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 1")
tk.MustExec("set @@tidb_partition_prune_mode='static'")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec(`CREATE TABLE t (a int, b int, index idx(b))
PARTITION BY RANGE ( a ) (
PARTITION p0 VALUES LESS THAN (6)
)`)
// dump historical stats
h := dom.StatsHandle()
tk.MustExec("analyze table t")
is := dom.InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
require.NotNil(t, tbl)
// dump historical stats
hsWorker := dom.GetHistoricalStatsWorker()
// only partition p0 stats will be dumped in static mode
tblID := hsWorker.GetOneHistoricalStatsTable()
require.NotEqual(t, tblID, -1)
err = hsWorker.DumpHistoricalStats(tblID, h)
require.NoError(t, err)
tblID = hsWorker.GetOneHistoricalStatsTable()
require.Equal(t, tblID, int64(-1))
time.Sleep(1 * time.Second)
snapshot := oracle.GoTimeToTS(time.Now())
jsTable, _, err := h.DumpHistoricalStatsBySnapshot("test", tbl.Meta(), snapshot)
require.NoError(t, err)
require.NotNil(t, jsTable)
// only has p0 stats
require.NotNil(t, jsTable.Partitions["p0"])
require.Nil(t, jsTable.Partitions["global"])
// change static to dynamic then assert
tk.MustExec("set @@tidb_partition_prune_mode='dynamic'")
tk.MustExec("analyze table t")
require.NoError(t, err)
// global and p0's stats will be dumped
tblID = hsWorker.GetOneHistoricalStatsTable()
require.NotEqual(t, tblID, -1)
err = hsWorker.DumpHistoricalStats(tblID, h)
require.NoError(t, err)
tblID = hsWorker.GetOneHistoricalStatsTable()
require.NotEqual(t, tblID, -1)
err = hsWorker.DumpHistoricalStats(tblID, h)
require.NoError(t, err)
time.Sleep(1 * time.Second)
snapshot = oracle.GoTimeToTS(time.Now())
jsTable, _, err = h.DumpHistoricalStatsBySnapshot("test", tbl.Meta(), snapshot)
require.NoError(t, err)
require.NotNil(t, jsTable)
// has both global and p0 stats
require.NotNil(t, jsTable.Partitions["p0"])
require.NotNil(t, jsTable.Partitions["global"])
}
func TestDumpHistoricalStatsFallback(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set global tidb_enable_historical_stats = 0")
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec(`CREATE TABLE t (a int, b int, index idx(b))
PARTITION BY RANGE ( a ) (
PARTITION p0 VALUES LESS THAN (6)
)`)
// dump historical stats
tk.MustExec("analyze table t")
is := dom.InfoSchema()
tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
require.NoError(t, err)
require.NotNil(t, tbl)
// dump historical stats
hsWorker := dom.GetHistoricalStatsWorker()
tblID := hsWorker.GetOneHistoricalStatsTable()
// assert no historical stats task generated
require.Equal(t, tblID, int64(-1))
tk.MustExec("set global tidb_enable_historical_stats = 1")
h := dom.StatsHandle()
jt, _, err := h.DumpHistoricalStatsBySnapshot("test", tbl.Meta(), oracle.GoTimeToTS(time.Now()))
require.NoError(t, err)
require.NotNil(t, jt)
require.False(t, jt.IsHistoricalStats)
}
|
package util
import (
"io/ioutil"
"fmt"
"encoding/json"
"flag"
)
var (
instance *Config
conf = flag.String("conf","../etc/config.json","描述")
)
type Config struct {
BasePath string `json:"base_path"`
DataPath string `json:"data_path"`
}
func init() {
//NewConfigWithFile("/Users/derek/go/src/sixedu/data/config.json")
flag.Parse()
NewConfigWithFile(*conf)
}
func NewConfigWithFile(name string) {
if instance == nil {
c := &Config{}
instance = c
fielContentsBytes, err := ioutil.ReadFile(name)
if err != nil {
fmt.Println("读取配置文件失败:",err)
return
}
err = json.Unmarshal(fielContentsBytes, c)
if err != nil {
fmt.Println("解析失败")
return
}
}
// fmt.Println(fileContent)
}
func GetConfig() *Config{
//fmt.Println(instance)
//fmt.Printf(*conf)
return instance
} |
package main
import (
"runtime"
_ "fmt"
"regexp"
"strings"
"dytt8_spider/handle/dl"
"dytt8_spider/util"
)
func main() {
//最大开两个原生线程,以达到真正的并行
runtime.GOMAXPROCS(2)
run()
}
var (
//匹配出需要的html
title_pattern = regexp.MustCompile(`<div class="title_all">(.*?)</div>`)
//标题名字匹配
name_pattern = regexp.MustCompile(`<strong>(.*?)</strong>`)
//更多按钮的url 匹配
url_pattern = regexp.MustCompile(`href="(.*?)"`)
)
func run() {
sites := util.GetSites()
//needSource := util.GetNeedSource()
//url := "http://" + sites[0].Url
//body ,err := dl.GetBody(url)
//if nil != err {
// fmt.Println(err)
// return
//}
//
//title_groups := title_pattern.FindAllSubmatch(body,len(body))
//var dataMap map[string]string
//dataMap = make(map[string]string)
//
////获取有效的数据
//for i:=0 ; i< len(title_groups) ; i++ {
// if len(title_groups[i]) >= 1 {
// mt_name, mt_url := getTitleNameAndUrl(title_groups[i][1])
// if "" == mt_url || "" == mt_name {
// continue
// }
// if isIn := In_array(mt_name,needSource);true == isIn {
// dataMap[mt_name] = resetUrl(mt_url,url)
// }
// }
//}
dl.DLrun("2018新片精品","http://www.dytt8.net/html/gndy/dyzz/index.html",sites[0].Url)
//dl.DLrun("华语电视剧","http://www.dytt8.net/html/tv/hytv/",sites[0].Url)
//dl.DLrun("日韩电视剧","http://www.dytt8.net/html/tv/rihantv/index.html",sites[0].Url)
//dl.DLrun("欧美电视剧","http://www.dytt8.net/html/tv/oumeitv/index.html",sites[0].Url)
// "http://www.dytt8.net/html/dongman/index.html"
//dl.DLrun("动漫","http://www.dytt8.net/html/dongman/index.html",sites[0].Url)
//cto := new(sync.WaitGroup)
//cto.Add(len(dataMap))
//for n, v:= range dataMap {
// dl.DLrun(n,v,sites[0].Url)
//}
//cto.Wait()
}
func resetUrl(old_url,host string) (new_url string) {
new_url = old_url
isOk1 := strings.Contains(old_url,host)
if false == isOk1 {
new_url = host + old_url
}
isOk2 := strings.Contains(new_url,"http://")
if false == isOk2 {
new_url += "http://"
}
return
}
func getTitleNameAndUrl(Bytes []byte) (name ,url string){
name_groups := name_pattern.FindSubmatch(Bytes)
url_groups := url_pattern.FindSubmatch(Bytes)
if len(name_groups) >=1 && len(url_groups) >=1 {
name = string(name_groups[1])
url = string(url_groups[1])
}
return
}
func In_array(hack string,needle []string) bool {
for _, val := range needle {
if val == hack {
return true
}
}
return false
}
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus"
)
// App is the application configuration and runtime information
type App struct {
ShowHelp bool `envconfig:"HELP" default:"false" desc:"show this message"`
OFTeeAPI string `envconfig:"OFTEE_API" default:"http://127.0.0.1:8002" desc:"HOST:PORT on which to connect to OFTEE REST API"`
}
func main() {
var app App
var flags flag.FlagSet
err := flags.Parse(os.Args[1:])
if err != nil {
if err = envconfig.Usage("", &(app)); err != nil {
log.
WithError(err).
Fatal("Unable to display usage information")
}
return
}
err = envconfig.Process("", &app)
if err != nil {
log.WithError(err).Fatal("Unable to parse application configuration")
}
if app.ShowHelp {
if err = envconfig.Usage("", &(app)); err != nil {
log.
WithError(err).
Fatal("Unable to display usage information")
}
return
}
resp, err := http.Get(fmt.Sprintf("%s/oftee", app.OFTeeAPI))
if err != nil {
log.
WithFields(log.Fields{
"oftee": app.OFTeeAPI,
}).
WithError(err).
Fatal("Unable to connect to oftee API end point")
} else if int(resp.StatusCode/100) != 2 {
log.
WithFields(log.Fields{
"oftee": app.OFTeeAPI,
"response-code": resp.StatusCode,
"response": resp.Status,
}).
Fatal("Non success code returned from oftee")
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.
WithFields(log.Fields{
"oftee": app.OFTeeAPI,
}).
WithError(err).
Fatal("Unable to read response from oftee")
}
fmt.Print(string(data))
}
|
package pie
// Intersect returns items that exist in all lists.
//
// It returns slice without any duplicates.
// If zero slice arguments are provided, then nil is returned.
func Intersect[T comparable](ss []T, slices ...[]T) (ss2 []T) {
if slices == nil {
return nil
}
var uniqs = make([]map[T]struct{}, len(slices))
for i := 0; i < len(slices); i++ {
m := make(map[T]struct{})
for _, el := range slices[i] {
m[el] = struct{}{}
}
uniqs[i] = m
}
var containsInAll = false
for _, el := range Unique(ss) {
for _, u := range uniqs {
if _, exists := u[el]; !exists {
containsInAll = false
break
}
containsInAll = true
}
if containsInAll {
ss2 = append(ss2, el)
}
}
return
}
|
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
import (
"fmt"
"os"
)
// Since, you didn't learn about the control flow statements yet
// I didn't include an error detection here.
//
// So, if you don't pass a name and a lastname,
// this program will fail.
// This is intentional.
func main() {
// assign a new value to the string variable below
name := os.Args[1]
fmt.Println("Hello great", name, "!")
// changes the name, declares the age with 85
name, age := "gandalf", 2019
fmt.Println("My name is", name)
fmt.Println("My age is", age)
fmt.Println("BTW, you shall pass!")
}
|
package response
type CreatedBill struct {
Url string `json:"url,omitempty"`
BillId int `json:"bill"`
}
|
package protocols
import (
"github.com/stellar/go/amount"
"github.com/stellar/go/keypair"
)
// IsValidAccountID returns true if account ID is valid
func IsValidAccountID(accountID string) bool {
_, err := keypair.Parse(accountID)
if err != nil {
return false
}
if accountID[0] != 'G' {
return false
}
return true
}
// IsValidSecret returns true if secret is valid
func IsValidSecret(secret string) bool {
_, err := keypair.Parse(secret)
if err != nil {
return false
}
if secret[0] != 'S' {
return false
}
return true
}
// IsValidAssetCode returns true if asset code is valid
func IsValidAssetCode(code string) bool {
if len(code) < 1 || len(code) > 12 {
return false
}
return true
}
// IsValidAmount returns true if amount is valid
func IsValidAmount(a string) bool {
_, err := amount.Parse(a)
if err != nil {
return false
}
return true
}
|
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
package tsdb
import (
"fmt"
"io"
"regexp"
"strconv"
"strings"
"testing"
)
var testDecode = []struct {
in string
err string
}{
{
in: timeSequence(
"1000000001",
"1000000002",
),
err: "",
},
{
in: timeSequence(
"1000000001001",
"1000000002000",
),
err: "",
},
{
in: timeSequence(
"1000000001",
"1000000001",
),
err: "order error: collision at time 1000000001",
},
{
in: timeSequence(
"1000000001001",
"1000000001002",
),
err: "order error: collision at time 1000000001",
},
{
in: timeSequence(
"1000000001001",
"1000000001999",
),
err: "order error: collision at time 1000000001",
},
{
in: timeSequence(
"1000000001",
"1000000000",
),
err: "order error: got time 1000000000, want at least 1000000002",
},
{
in: timeSequence(
"1000000001",
"1000000002",
"1000000000",
),
err: "order error: got time 1000000000, want at least 1000000003",
},
{
in: timeSequence(
"1000000001",
"1000086402",
),
err: "order error: stepped too far into the future \\(24h0m1s>24h0m0s\\)",
},
{
in: timeSequence(
"1000000001",
"1000000001000",
),
err: "order error: collision at time 1000000001",
},
/*
{
in: timeSequence(
"2147483647",
"1000000001",
),
err: "order error: stepped too far into the future",
},
*/
}
func TestDecode(t *testing.T) {
for _, tt := range testDecode {
dec := NewDecoder(strings.NewReader(tt.in))
var err error
for {
_, err = dec.Decode()
if err != nil {
break
}
}
if err == io.EOF {
err = nil
}
if err != nil {
if tt.err == "" {
t.Errorf("Decode(%q): unexpected error:\ngot: %v\nwant success", tt.in, err)
continue
}
re := regexp.MustCompile(tt.err)
if !re.MatchString(err.Error()) {
t.Errorf("Decode(%q): invalid error:\ngot: %v\nwant: /%s/", tt.in, err, tt.err)
}
continue
}
if tt.err != "" {
t.Errorf("Decode(%q):\ngot success\nwant error: %v", tt.in, tt.err)
continue
}
}
}
func BenchmarkDecode(b *testing.B) {
b.SetBytes(int64(len(pointText)))
b.ReportAllocs()
dec := NewDecoder(&infiniteReader{})
for i := 0; i < b.N; i++ {
p, err := dec.Decode()
if err != nil {
b.Fatal(err)
}
p.Free()
}
}
type infiniteReader struct {
time int64
}
func (r *infiniteReader) Read(b []byte) (int, error) {
r.time++
b = b[:0]
b = append(b, "xxx.xxx.xxx "...)
b = strconv.AppendInt(b, r.time, 10)
b = append(b, " 111 a=a b=b c=c\n"...)
return len(b), nil
}
func timeSequence(times ...string) string {
var input string
for _, t := range times {
input += fmt.Sprintf("foo %s 1 a=a\n", t)
}
return input
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"time"
)
func main() {
go func() {
sc := bufio.NewScanner(os.Stdin)
f := func() bool {
fmt.Print(">> ")
return sc.Scan()
}
for f() {
if err := sc.Err(); err != nil {
log.Fatal(err)
}
switch sc.Text() {
case "exit":
os.Exit(0)
default:
fmt.Println(sc.Text())
}
}
fmt.Println("fail sc scan")
os.Exit(1)
}()
fmt.Println("input accept: time limit of one minute")
time.Sleep(time.Minute)
}
|
package cera
import (
_ "github.com/xxxmailk/cera/http"
_ "github.com/xxxmailk/cera/middlewares"
_ "github.com/xxxmailk/cera/middlewares/access"
_ "github.com/xxxmailk/cera/middlewares/auth"
_ "github.com/xxxmailk/cera/router"
_ "github.com/xxxmailk/cera/view"
)
|
package models
import (
"time"
"github.com/astaxie/beego/orm"
)
const UserTableName = "user"
// User model defines structure of users table
type User struct {
ID int `orm:"column(id)"`
Name string `orm:"column(name)"`
Email string `orm:"column(email);unique"`
Password string `orm:"column(password)"`
InsertedAt time.Time `orm:"auto_now_add;type(datetime)"`
UpdatedAt time.Time `orm:"auto_now;type(datetime)"`
Active bool `orm:"column(active);default(1)"`
}
// TableName returns normalized table name
func (p *User) TableName() string {
return UserTableName
}
func init() {
// Need to register model in init
orm.RegisterModel(new(User))
}
|
package master
import (
"FoG/src/github.com/cl/crontab/common"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"time"
)
//日志查看相关
type ApiServer struct {
httpServer *http.Server
}
var (
// 单例对象,首字母大写,可以被其他包访问到
G_apiServer *ApiServer
)
// 保存任务的接口
// POST job={name command cronExpr}
func handlerJobSave(resp http.ResponseWriter, req *http.Request) {
var (
err error
postJob string
job common.Job
oldJob *common.Job
bytes []byte
)
// 1 解析POST表单
if err = req.ParseForm(); err != nil {
goto ERR
}
// 2 获取表单的数据
postJob = req.PostForm.Get("job")
// 3 反序列化job
if err = json.Unmarshal([]byte(postJob), &job); err != nil {
goto ERR
}
// 4 调用etcd层存放job数据
if oldJob, err = G_jobMgr.SaveJob(&job); err != nil {
goto ERR
}
// 5 返回正常应答-- 定义统一响应结构体
if bytes, err = common.BuildResponse(0, "success", oldJob); err == nil {
// 写入响应
resp.Write(bytes)
} else {
goto ERR
}
return
ERR:
fmt.Println(err)
}
// 查询任务的接口
func handlerJobList(resp http.ResponseWriter, req *http.Request) {
var (
jobList []*common.Job
bytes []byte
err error
)
if jobList, err = G_jobMgr.ListJobs(); err != nil {
goto ERR
}
if jobList != nil {
if bytes, err = common.BuildResponse(0, "success", jobList); err != nil {
goto ERR
}
}
if bytes != nil {
resp.Write(bytes)
}
return
ERR:
fmt.Println(err)
}
// 杀死任务接口
func handlerJobDel(resp http.ResponseWriter, req *http.Request) {
var (
jobName string
err error
jobList []*common.Job
bytes []byte
)
if err = req.ParseForm(); err != nil {
return
}
// 获取任务名
jobName = req.PostForm.Get("name")
if jobList, err = G_jobMgr.DelJob(jobName); err != nil {
goto ERR
}
if jobList != nil {
if bytes, err = common.BuildResponse(0, "success", jobList); err != nil {
resp.Write(bytes)
} else {
goto ERR
}
}
return
ERR:
fmt.Println(err)
}
// 任务强杀 -- 强杀只是,杀死当前任务,并不会删除当前人物的的执行
func handlerJobKill(resp http.ResponseWriter, req *http.Request) {
// 将强杀任务放入某一目录下,调度器监听改任务,并强杀任务
var (
err error
bytes []byte
jobName string
)
if err = req.ParseForm(); err != nil {
return
}
jobName = req.PostForm.Get("name")
// 强杀jobName
if err = G_jobMgr.KillJob(jobName); err != nil {
goto ERR
}
if bytes, err = common.BuildResponse(0, "success", nil); err == nil {
resp.Write(bytes)
}
return
ERR:
fmt.Println("任务强杀错误", err)
return
}
//初始化服务
func InitApiServer() (err error) {
var (
mux *http.ServeMux
listener net.Listener
httpServer *http.Server
staticDir http.Dir
staticHandler http.Handler
)
// 配置路由服务
mux = http.NewServeMux()
// 路由,目标方法--新增更新
mux.HandleFunc("/job/save", handlerJobSave)
// 路由查询
mux.HandleFunc("/job/list", handlerJobList)
// 任务杀死
mux.HandleFunc("/job/del", handlerJobDel)
// 任务强杀 --中断command的执行
mux.HandleFunc("/job/kill", handlerJobKill)
// 静态文件目录配置
staticDir = http.Dir(G_config.Webroot)
staticHandler = http.FileServer(staticDir)
mux.Handle("/", http.StripPrefix("/", staticHandler)) // 路径转换
// 启动TCP监听 , 并将产生的错误抛出
if listener, err = net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPort)); err != nil {
return
}
// 创建一个Http服务
httpServer = &http.Server{
ReadTimeout: time.Duration(G_config.ApiReadTimeout) * time.Second,
WriteTimeout: time.Duration(G_config.ApiWriteTimeout) * time.Second,
Handler: mux,
}
// 单例赋值
G_apiServer = &ApiServer{
httpServer: httpServer,
}
// 启动了http服务端
go httpServer.Serve(listener)
return
}
|
package dalmodel
import "github.com/jinzhu/gorm"
type Measurement struct {
gorm.Model
Name string
Description string
UserID uint
Hashtags []Hashtag `gorm:"many2many:measurement_hashtags;"`
Measurements []MeasurementResult `gorm:"foreignkey:MeasurementID"`
}
type MeasurementResult struct {
gorm.Model
MeasurementID uint `sql:"index"`
}
|
package hw04_lru_cache //nolint:golint,stylecheck
type List interface {
Len() int
Front() *listItem
Back() *listItem
PushFront(v interface{}) *listItem
PushBack(v interface{}) *listItem
Remove(i *listItem)
MoveToFront(i *listItem)
}
type listItem struct {
Next *listItem
Prev *listItem
Value interface{}
}
type list struct {
firstItem *listItem
lastItem *listItem
length int
}
func (l list) Len() int {
return l.length
}
func (l list) Front() *listItem {
return l.firstItem
}
func (l list) Back() *listItem {
return l.lastItem
}
func (l *list) insertAfter(item *listItem, newItem *listItem) {
newItem.Prev = item
if item.Next == nil {
newItem.Next = nil
l.lastItem = newItem
} else {
newItem.Next = item.Next
item.Next.Prev = newItem
}
item.Next = newItem
}
func (l *list) insertBefore(item *listItem, newItem *listItem) {
newItem.Next = item
if item.Prev == nil {
newItem.Prev = nil
l.firstItem = newItem
} else {
newItem.Prev = item.Prev
item.Prev.Next = newItem
}
item.Prev = newItem
}
func (l *list) PushFront(v interface{}) *listItem {
newItem := &listItem{Value: v}
if l.firstItem == nil {
l.firstItem = newItem
l.lastItem = newItem
} else {
l.insertBefore(l.firstItem, newItem)
}
l.length++
return newItem
}
func (l *list) PushBack(v interface{}) *listItem {
var newItem *listItem
if l.lastItem == nil {
newItem = l.PushFront(v)
} else {
newItem = &listItem{Value: v}
l.insertAfter(l.lastItem, newItem)
}
l.length++
return newItem
}
func (l *list) Remove(i *listItem) {
if i.Prev == nil {
l.firstItem = i.Next
} else {
i.Prev.Next = i.Next
}
if i.Next == nil {
l.lastItem = i.Prev
} else {
i.Next.Prev = i.Prev
}
l.length--
}
func (l *list) MoveToFront(i *listItem) {
if l.firstItem == i {
return
}
if l.lastItem == i {
l.lastItem = i.Prev
}
i.Prev.Next = i.Next
if i.Next != nil {
i.Next.Prev = i.Prev
}
tmpFirstItem := l.firstItem
l.firstItem = i
i.Prev = nil
i.Next = tmpFirstItem
tmpFirstItem.Prev = i
}
func NewList() List {
return &list{}
}
|
package session
type Session interface {
Set(key, value interface{}) error
Get(key interface{}) interface{}
Delete(key interface{}) error
SessionID() string
} |
package goSolution
import "math"
func powerfulIntegers(x int, y int, bound int) []int {
t := make(map[int]bool, bound)
for i := 0; ; i++ {
c := true
for j := 0; ; j++ {
k := int(math.Pow(float64(x), float64(i))) + int(math.Pow(float64(y), float64(j)))
if k > bound {
break
}
c = false
t[k] = true
if y == 1 {
break
}
}
if c || x == 1 {
break
}
}
ret := []int{}
for k, _ := range t {
ret = append(ret, k)
}
return ret
}
|
package main
import "os"
type Config struct {
FileLocation string
}
func CollectConfig() (config Config) {
// DB_ENGINE
fileLocation := os.Getenv("FILE_LOCATION")
if fileLocation == "" {
config.FileLocation = "relay.jsonld"
} else {
config.FileLocation = fileLocation
}
return
}
|
// Copyright 2017 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package vars
// 所有标签的定义
const (
API = "@api"
APIDoc = "@apidoc"
APILicense = "@apiLicense"
APIVersion = "@apiVersion"
APIParam = "@apiParam"
APIQuery = "@apiQuery"
APIHeader = "@apiHeader"
APISuccess = "@apiSuccess"
APIError = "@apiError"
APIRequest = "@apiRequest"
APIBaseURL = "@apiBaseURL"
APIGroup = "@apiGroup"
APIIgnore = "@apiIgnore"
APIContent = "@apiContent"
APIExample = "@apiExample"
)
|
/*
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 controllers
import (
"context"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
corev1 "github.com/yamajik/kess/api/v1"
"github.com/yamajik/kess/controllers/operations"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
)
// RuntimeReconciler reconciles a Runtime object
type RuntimeReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
ops operations.ResourceOperationsInterface
}
// Resource bulabula
func (r *RuntimeReconciler) Resource() operations.ResourceOperationsInterface {
if r.ops == nil {
r.ops = operations.NewResourceOperations(r.Client)
}
return r.ops
}
// +kubebuilder:rbac:groups=core.kess.io,resources=runtimes,verbs=list;get;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core.kess.io,resources=runtimes/status,verbs=update;patch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=list;get;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=update;patch
// +kubebuilder:rbac:groups="",resources=services,verbs=list;get;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services/status,verbs=update;patch
// Reconcile runtime
func (r *RuntimeReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
log := r.Log.WithValues("runtime", req.NamespacedName)
var rt corev1.Runtime
if _, err := r.Resource().Get(ctx, req.NamespacedName, &rt); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if _, err := r.Resource().ApplyDefaultAll(ctx, &rt); err != nil {
log.Error(err, "unable to set default for runtime")
return ctrl.Result{}, err
}
if rt.DeletionTimestamp.IsZero() {
if !r.Resource().ContainsFinalizer(&rt, corev1.Finalizer) {
if _, err := r.Resource().AddFinalizer(ctx, &rt, corev1.Finalizer); err != nil {
log.Error(err, "unable to add runtime finalizer")
return ctrl.Result{}, err
}
}
} else {
if r.Resource().ContainsFinalizer(&rt, corev1.Finalizer) {
if err := r.deleteExternalResources(ctx, &rt); err != nil {
log.Error(err, "unable to delete runtime external resources")
return ctrl.Result{}, err
}
if _, err := r.Resource().RemoveFinalizer(ctx, &rt, corev1.Finalizer); err != nil {
log.Error(err, "unable to remove runtime finalizer")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
if err := r.applyExternalResources(ctx, &rt); err != nil {
log.Error(err, "unable to apply runtime external resources")
return ctrl.Result{}, err
}
if err := r.applyStatus(ctx, &rt); err != nil {
log.Error(err, "unable to apply runtime status")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *RuntimeReconciler) applyStatus(ctx context.Context, rt *corev1.Runtime) error {
var (
fns corev1.FunctionList
libs corev1.LibraryList
matchLabels = client.MatchingLabels{"kess-runtime": rt.Name}
)
if _, err := r.Resource().Status().Update(ctx, rt, func() error {
var deploy appsv1.Deployment
r.Get(ctx, rt.NamespacedName(), &deploy)
rt.UpdateStatusReady(&deploy)
return nil
}); err != nil {
return err
}
if _, err := r.Resource().List(ctx, &fns, matchLabels); err != nil {
return err
}
if _, err := r.Resource().List(ctx, &libs, matchLabels); err != nil {
return err
}
var errors []error
for _, fn := range fns.Items {
if _, err := r.Resource().Status().Update(ctx, &fn, func() error {
fn.UpdateStatusReady(rt)
return nil
}); err != nil {
errors = append(errors, err)
}
}
for _, lib := range libs.Items {
if _, err := r.Resource().Status().Update(ctx, &lib, func() error {
lib.UpdateStatusReady(rt)
return nil
}); err != nil {
errors = append(errors, err)
}
}
if len(errors) > 0 {
return errors[0]
}
return nil
}
func (r *RuntimeReconciler) applyExternalResources(ctx context.Context, rt *corev1.Runtime) error {
var (
deploy = rt.Deployment()
svc = rt.Service()
patchOptions = client.PatchOptions{FieldManager: corev1.FieldManager}
)
ctrl.SetControllerReference(rt, &deploy, r.Scheme)
if _, err := r.Resource().Patch(ctx, &deploy, client.Apply, &patchOptions); err != nil {
return err
}
ctrl.SetControllerReference(rt, &svc, r.Scheme)
if _, err := r.Resource().Patch(ctx, &svc, client.Apply, &patchOptions); err != nil {
return err
}
return nil
}
func (r *RuntimeReconciler) deleteExternalResources(ctx context.Context, rt *corev1.Runtime) error {
var (
deploy appsv1.Deployment
svc apiv1.Service
namespacedName = rt.NamespacedName()
deleteOptions = client.DeleteOptions{}
)
if _, err := r.Resource().GetAndDelete(ctx, namespacedName, &deploy, &deleteOptions); err != nil {
return err
}
if _, err := r.Resource().GetAndDelete(ctx, namespacedName, &svc, &deleteOptions); err != nil {
return err
}
return nil
}
// SetupWithManager runtime
func (r *RuntimeReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&corev1.Runtime{}).
Complete(r)
}
|
package values
import (
"context"
"helm.sh/helm/v3/pkg/chart"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
chartsapi "x-helm.dev/apimachinery/apis/charts/v1alpha1"
)
func MergePresetValues(kc client.Client, chrt *chart.Chart, ref chartsapi.ChartPresetFlatRef) (map[string]interface{}, error) {
var valOpts Options
if ref.PresetName != "" {
ps, err := ref.ClusterChartPreset()
if err != nil {
return nil, err
}
valOpts, err = LoadClusterChartPresetValues(kc, ps, ref.Namespace)
if err != nil {
return nil, err
}
}
return valOpts.MergeValues(chrt)
}
func LoadClusterChartPresetValues(kc client.Client, in chartsapi.Preset, ns string) (Options, error) {
var opts Options
err := mergeClusterChartPresetValues(kc, in, ns, &opts)
if err != nil {
return Options{}, err
}
return opts, nil
}
func mergeClusterChartPresetValues(kc client.Client, in chartsapi.Preset, ns string, opts *Options) error {
for _, ps := range in.GetSpec().UsePresets {
var presets []chartsapi.Preset
if ps.Name != "" {
obj, err := getPreset(kc, ps, ns)
if err != nil {
return err
}
presets = append(presets, obj)
} else if ps.Selector != nil {
sel, err := metav1.LabelSelectorAsSelector(ps.Selector)
if err != nil {
return err
}
var list metav1.PartialObjectMetadataList
list.SetGroupVersionKind(chartsapi.GroupVersion.WithKind(chartsapi.ResourceKindClusterChartPreset))
err = kc.List(context.TODO(), &list, client.MatchingLabelsSelector{
Selector: sel,
})
if err != nil {
return err
}
for _, md := range list.Items {
ref := chartsapi.TypedLocalObjectReference{
APIGroup: &chartsapi.GroupVersion.Group,
Kind: chartsapi.ResourceKindClusterChartPreset,
Name: md.Name,
}
obj, err := getPreset(kc, ref, ns)
if err != nil {
return err
}
presets = append(presets, obj)
}
}
for _, obj := range presets {
if err := mergeClusterChartPresetValues(kc, obj, ns, opts); err != nil {
return err
}
}
}
if in.GetSpec().Values != nil && in.GetSpec().Values.Raw != nil {
opts.ValueBytes = append(opts.ValueBytes, in.GetSpec().Values.Raw)
}
return nil
}
func getPreset(kc client.Client, in chartsapi.TypedLocalObjectReference, ns string) (chartsapi.Preset, error) {
// Usually namespace is set by user for Options chart values
if ns != "" {
var cp chartsapi.ChartPreset
err := kc.Get(context.TODO(), client.ObjectKey{Namespace: ns, Name: in.Name}, &cp)
if client.IgnoreNotFound(err) != nil {
return nil, err
} else if err == nil {
return &cp, nil
}
}
var ccp chartsapi.ClusterChartPreset
err := kc.Get(context.TODO(), client.ObjectKey{Name: in.Name}, &ccp)
return &ccp, err
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
//"ms/sun/servises/file_service_old"
"ms/sun/shared/helper"
"net/http"
"strings"
"time"
"ms/sun/shared/xc"
"ms/sun/servises/file_service/file_store"
)
var cnt int = 1
var size int = 0
func main() {
Insert_many(10)
//file_service_old.Run()
http.HandleFunc("/hi", func(writer http.ResponseWriter, r *http.Request) {
writer.Write([]byte("hi"))
})
go func() {
time.Sleep(time.Second)
http.Get("http://localhost:1100/post_file/1518506476136010007_180.jpg")
}()
http.ListenAndServe(":1100", nil)
}
func Insert_many(num int) {
for i := 0; i < num; i++ {
insertPost()
fmt.Println("cnt: ", i, " size:(mb)", size/1000000)
}
}
func insertPost() {
ext, bs, err := RandFile()
if err != nil {
return
}
ref := &xc.FileRef{
Extension: ext,
FileRefId: helper.NanoRowIdSeq(),
Height: 0,
Length: 0,
Md5Key: "",
MimeType: "",
Name: "file_sampl."+ext,
StorageUserId: 0,
StoreType: file_store.SOTRE_TYPE_DIRECT_FILE,
UserId: 5,
Width: 0,
}
file_store.SavaFile(ref,bs)
cnt++
}
func RandFile() (ext string, bs []byte, err error) {
const dir = `C:\Go\_gopath\src\ms\sun_old\upload\all_file_samples2`
imageFiles, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
fn := dir + "/" + imageFiles[rand.Intn(len(imageFiles))].Name()
bs, err = ioutil.ReadFile(fn)
if err != nil {
log.Fatal(err)
}
size += len(bs)
ind := strings.LastIndex(fn, ".")
if ind > 0 {
ext = fn[ind:]
}
return ext, bs, nil
}
|
package business
import "fmt"
var searchAllWithNameLikeKeywordStmt = `
MATCH (n)
WHERE n.name =~ $regex
RETURN n, labels(n)
SKIP $offset LIMIT $limit
`
var countSearchAllWithNameLikeKeywordStmt = `
MATCH (n)
WHERE n.name =~ $regex
RETURN count(n)
`
func SearchAllWithNameLikeKeywoard(keyword string, page, limit int64) (interface{}, error) {
searchStmt := searchAllWithNameLikeKeywordStmt
searchParamsMap := make(map[string]interface{})
searchParamsMap["regex"] = fmt.Sprintf(".*%s.*", keyword)
searchParamsMap["offset"] = (page - 1) * limit
searchParamsMap["limit"] = limit
countStmt := countSearchAllWithNameLikeKeywordStmt
countParamsMap := make(map[string]interface{})
countParamsMap["regex"] = fmt.Sprintf(".*%s.*", keyword)
statements := []string{searchStmt, countStmt}
paramsMapArr := []map[string]interface{}{searchParamsMap, countParamsMap}
includeGraphs := []bool{false, false}
return Neo4jMultiQuery(statements, paramsMapArr, includeGraphs)
}
var searchInLabelsStmtTempl = `
MATCH (n)
WHERE (%s) AND n.name =~ $regex
RETURN n, labels(n)
SKIP $offset
LIMIT $limit
`
var countSearchInLabelsStmtTempl = `
MATCH (n)
WHERE (%s) AND n.name =~ $regex
RETURN count(n)
`
func SearchInLabelsWithNameLikeKeyword(keyword string, labels []string, page, limit int64) (interface{}, error) {
subQuery := fmt.Sprintf("n:%s", labels[0])
if len(labels) == 1 {
// pass
} else {
for i, label := range labels {
if i > 0 {
subQuery += fmt.Sprintf(" OR n:%s", label)
}
}
}
searchInLabelsStmt := fmt.Sprintf(searchInLabelsStmtTempl, subQuery)
searchParamsMap := make(map[string]interface{})
searchParamsMap["regex"] = fmt.Sprintf(".*%s.*", keyword)
searchParamsMap["offset"] = (page - 1) * limit
searchParamsMap["limit"] = limit
countInLabelsStmt := fmt.Sprintf(countSearchInLabelsStmtTempl, subQuery)
countParamsMap := make(map[string]interface{})
countParamsMap["regex"] = fmt.Sprintf(".*%s.*", keyword)
statements := []string{searchInLabelsStmt, countInLabelsStmt}
paramsMapArr := []map[string]interface{}{searchParamsMap, countParamsMap}
includeGraphs := []bool{false, false}
return Neo4jMultiQuery(statements, paramsMapArr, includeGraphs)
}
|
package main
import (
"fmt"
"regexp"
"log"
"strings"
)
func LongestWord(sen string) string {
var longest string
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatal(err)
}
words := strings.Split(reg.ReplaceAllString(sen, " "), " ")
for _, word := range words {
if len(longest) < len(word) {
longest = word
}
}
return longest
}
func main() {
fmt.Println(LongestWord("hello world"), " || The correct answer is hello")
fmt.Println(LongestWord("this is some sort of sentence"), " || The correct answer is sentence")
fmt.Println(LongestWord("longest word!!"), " || The correct answer is longest")
fmt.Println(LongestWord("a beautiful sentence^&!"), " || The correct answer is beautiful")
fmt.Println(LongestWord("oxford press"), " || The correct answer is oxford")
fmt.Println(LongestWord("123456789 98765432"), " || The correct answer is 123456789")
fmt.Println(LongestWord("letter after letter!!"), " || The correct answer is letter")
fmt.Println(LongestWord("a b c dee"), " || The correct answer is dee")
fmt.Println(LongestWord("a confusing /:sentence:/[ this is not!!!!!!!~"), " || The correct answer is confusing")
}
|
package controllers
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/insisthzr/echo-test/cookbook/twitter/db"
"github.com/insisthzr/echo-test/cookbook/twitter/utils"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
func TestSignup(t *testing.T) {
err := db.InitDB()
if !assert.NoError(t, err) {
return
}
var userIn = map[string]string{
"email": "hello" + strconv.FormatInt(time.Now().Unix(), 10),
"password": "world",
}
b, _ := json.Marshal(userIn)
e := echo.New()
req, err := http.NewRequest("POST", "/api/v1/signup", strings.NewReader(string(b)))
if !assert.NoError(t, err) {
return
}
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
// Assertions
if !assert.NoError(t, Signup(c)) {
return
}
assert.Equal(t, 201, rec.Code)
t.Log("Signup:", rec.Body.String())
}
func TestLogin(t *testing.T) {
err := db.InitDB()
if !assert.NoError(t, err) {
return
}
user := map[string]string{
"email": "hello",
"password": "world",
}
b, _ := json.Marshal(user)
e := echo.New()
req, err := http.NewRequest("POST", "/api/v1/login", strings.NewReader(string(b)))
if !assert.NoError(t, err) {
return
}
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
if !assert.NoError(t, Login(c)) {
return
}
assert.Equal(t, 200, rec.Code)
t.Log("Login:", rec.Body.String())
}
func TestFollow(t *testing.T) {
err := db.InitDB()
if !assert.NoError(t, err) {
return
}
from := "58c75a9ff825dda245aa7aa4" // email=hello
to := "58d21dd1ad9dce0f86b62223" // email=hello
e := echo.New()
req, err := http.NewRequest("POST", "/api/v1/follow/:to", nil)
if !assert.NoError(t, err) {
return
}
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
token := utils.NewToken(from)
c.Set("user", token)
c.SetParamNames("to")
c.SetParamValues(to)
if !assert.NoError(t, Follow(c)) {
return
}
assert.Equal(t, http.StatusOK, rec.Code)
t.Log("follow:", rec.Body.String())
}
|
package nats
type NatsCluster struct {
ApiVs string `json:"apiVersion"`
Kind string `json:"Kind"`
Metadata `json:"metadata"`
Spec `json:"spec"`
}
type NatsGetCluster struct {
ApiVs string `json:"apiVersion"`
Kind string `json:"Kind"`
Metadata `json:"metadata"`
}
type NatsConfig struct {
Debug bool `json:"debug"`
Trace bool `json:"trace"`
}
type Pod struct {
EnableCfgReload bool `json:"enableConfigReload"`
EnableMetrics bool `json:"enableMetrics"`
Resources
}
type Resources struct {
Limits struct {
Cpu string `json:"cpu"`
Memory string `json:"memory"`
} `json:"limits"`
Requests struct {
Cpu string `json:"cpu"`
Memory string `json:"memory"`
} `json:"requests"`
}
type Size int
type Version string
type Metadata struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
}
type Spec struct {
Auth
GatewayConfig
NatsConfig
Pod
Size `json:"size"`
Version `json:"version"`
}
type Auth struct {
EnableSvcAccounts bool `json:"enableServiceAccounts"`
}
type Gateway struct {
Url string `json:"url"`
Name string `json:"name"`
}
type GatewayConfig struct {
Gateways []Gateway
HostPort int `json:"hostPort"`
Name string `json:"name"`
RejectUnkown bool `json:"rejectUnkown"`
}
|
package version
import (
"fmt"
"github.com/spf13/cobra"
"github.com/ovh/venom"
)
// Cmd version
var Cmd = &cobra.Command{
Use: "version",
Short: "Display Version of venom: venom version",
Long: `venom version`,
Aliases: []string{"v"},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Version venom: %s\n", venom.Version)
},
}
|
// 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 rowcodec
import (
"encoding/binary"
"fmt"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/codec"
)
// decoder contains base util for decode row.
type decoder struct {
row
columns []ColInfo
handleColIDs []int64
loc *time.Location
}
// NewDecoder creates a decoder.
func NewDecoder(columns []ColInfo, handleColIDs []int64, loc *time.Location) *decoder {
return &decoder{
columns: columns,
handleColIDs: handleColIDs,
loc: loc,
}
}
// ColInfo is used as column meta info for row decoder.
type ColInfo struct {
ID int64
IsPKHandle bool
VirtualGenCol bool
Ft *types.FieldType
}
// DatumMapDecoder decodes the row to datum map.
type DatumMapDecoder struct {
decoder
}
// NewDatumMapDecoder creates a DatumMapDecoder.
func NewDatumMapDecoder(columns []ColInfo, loc *time.Location) *DatumMapDecoder {
return &DatumMapDecoder{decoder{
columns: columns,
loc: loc,
}}
}
// DecodeToDatumMap decodes byte slices to datum map.
func (decoder *DatumMapDecoder) DecodeToDatumMap(rowData []byte, row map[int64]types.Datum) (map[int64]types.Datum, error) {
if row == nil {
row = make(map[int64]types.Datum, len(decoder.columns))
}
err := decoder.fromBytes(rowData)
if err != nil {
return nil, err
}
for i := range decoder.columns {
col := &decoder.columns[i]
idx, isNil, notFound := decoder.row.findColID(col.ID)
if !notFound && !isNil {
colData := decoder.getData(idx)
d, err := decoder.decodeColDatum(col, colData)
if err != nil {
return nil, err
}
row[col.ID] = d
continue
}
if isNil {
var d types.Datum
d.SetNull()
row[col.ID] = d
continue
}
}
return row, nil
}
func (decoder *DatumMapDecoder) decodeColDatum(col *ColInfo, colData []byte) (types.Datum, error) {
var d types.Datum
switch col.Ft.GetType() {
case mysql.TypeLonglong, mysql.TypeLong, mysql.TypeInt24, mysql.TypeShort, mysql.TypeTiny:
if mysql.HasUnsignedFlag(col.Ft.GetFlag()) {
d.SetUint64(decodeUint(colData))
} else {
d.SetInt64(decodeInt(colData))
}
case mysql.TypeYear:
d.SetInt64(decodeInt(colData))
case mysql.TypeFloat:
_, fVal, err := codec.DecodeFloat(colData)
if err != nil {
return d, err
}
d.SetFloat32(float32(fVal))
case mysql.TypeDouble:
_, fVal, err := codec.DecodeFloat(colData)
if err != nil {
return d, err
}
d.SetFloat64(fVal)
case mysql.TypeVarString, mysql.TypeVarchar, mysql.TypeString, mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:
d.SetString(string(colData), col.Ft.GetCollate())
case mysql.TypeNewDecimal:
_, dec, precision, frac, err := codec.DecodeDecimal(colData)
if err != nil {
return d, err
}
d.SetMysqlDecimal(dec)
d.SetLength(precision)
d.SetFrac(frac)
case mysql.TypeDate, mysql.TypeDatetime, mysql.TypeTimestamp:
var t types.Time
t.SetType(col.Ft.GetType())
t.SetFsp(col.Ft.GetDecimal())
err := t.FromPackedUint(decodeUint(colData))
if err != nil {
return d, err
}
if col.Ft.GetType() == mysql.TypeTimestamp && !t.IsZero() {
err = t.ConvertTimeZone(time.UTC, decoder.loc)
if err != nil {
return d, err
}
}
d.SetMysqlTime(t)
case mysql.TypeDuration:
var dur types.Duration
dur.Duration = time.Duration(decodeInt(colData))
dur.Fsp = col.Ft.GetDecimal()
d.SetMysqlDuration(dur)
case mysql.TypeEnum:
// ignore error deliberately, to read empty enum value.
enum, err := types.ParseEnumValue(col.Ft.GetElems(), decodeUint(colData))
if err != nil {
enum = types.Enum{}
}
d.SetMysqlEnum(enum, col.Ft.GetCollate())
case mysql.TypeSet:
set, err := types.ParseSetValue(col.Ft.GetElems(), decodeUint(colData))
if err != nil {
return d, err
}
d.SetMysqlSet(set, col.Ft.GetCollate())
case mysql.TypeBit:
byteSize := (col.Ft.GetFlen() + 7) >> 3
d.SetMysqlBit(types.NewBinaryLiteralFromUint(decodeUint(colData), byteSize))
case mysql.TypeJSON:
var j types.BinaryJSON
j.TypeCode = colData[0]
j.Value = colData[1:]
d.SetMysqlJSON(j)
default:
return d, errors.Errorf("unknown type %d", col.Ft.GetType())
}
return d, nil
}
// ChunkDecoder decodes the row to chunk.Chunk.
type ChunkDecoder struct {
decoder
defDatum func(i int, chk *chunk.Chunk) error
}
// NewChunkDecoder creates a NewChunkDecoder.
func NewChunkDecoder(columns []ColInfo, handleColIDs []int64, defDatum func(i int, chk *chunk.Chunk) error, loc *time.Location) *ChunkDecoder {
return &ChunkDecoder{
decoder: decoder{
columns: columns,
handleColIDs: handleColIDs,
loc: loc,
},
defDatum: defDatum,
}
}
// DecodeToChunk decodes a row to chunk.
func (decoder *ChunkDecoder) DecodeToChunk(rowData []byte, handle kv.Handle, chk *chunk.Chunk) error {
err := decoder.fromBytes(rowData)
if err != nil {
return err
}
for colIdx := range decoder.columns {
col := &decoder.columns[colIdx]
// fill the virtual column value after row calculation
if col.VirtualGenCol {
chk.AppendNull(colIdx)
continue
}
if col.ID == model.ExtraRowChecksumID {
if v := decoder.row.getChecksumInfo(); len(v) > 0 {
chk.AppendString(colIdx, v)
} else {
chk.AppendNull(colIdx)
}
continue
}
idx, isNil, notFound := decoder.row.findColID(col.ID)
if !notFound && !isNil {
colData := decoder.getData(idx)
err := decoder.decodeColToChunk(colIdx, col, colData, chk)
if err != nil {
return err
}
continue
}
// Only try to decode handle when there is no corresponding column in the value.
// This is because the information in handle may be incomplete in some cases.
// For example, prefixed clustered index like 'primary key(col1(1))' only store the leftmost 1 char in the handle.
if decoder.tryAppendHandleColumn(colIdx, col, handle, chk) {
continue
}
if isNil {
chk.AppendNull(colIdx)
continue
}
if decoder.defDatum == nil {
chk.AppendNull(colIdx)
continue
}
err := decoder.defDatum(colIdx, chk)
if err != nil {
return err
}
}
return nil
}
func (decoder *ChunkDecoder) tryAppendHandleColumn(colIdx int, col *ColInfo, handle kv.Handle, chk *chunk.Chunk) bool {
if handle == nil {
return false
}
if handle.IsInt() && col.ID == decoder.handleColIDs[0] {
chk.AppendInt64(colIdx, handle.IntValue())
return true
}
for i, id := range decoder.handleColIDs {
if col.ID == id {
if types.NeedRestoredData(col.Ft) {
return false
}
coder := codec.NewDecoder(chk, decoder.loc)
_, err := coder.DecodeOne(handle.EncodedCol(i), colIdx, col.Ft)
return err == nil
}
}
return false
}
func (decoder *ChunkDecoder) decodeColToChunk(colIdx int, col *ColInfo, colData []byte, chk *chunk.Chunk) error {
switch col.Ft.GetType() {
case mysql.TypeLonglong, mysql.TypeLong, mysql.TypeInt24, mysql.TypeShort, mysql.TypeTiny:
if mysql.HasUnsignedFlag(col.Ft.GetFlag()) {
chk.AppendUint64(colIdx, decodeUint(colData))
} else {
chk.AppendInt64(colIdx, decodeInt(colData))
}
case mysql.TypeYear:
chk.AppendInt64(colIdx, decodeInt(colData))
case mysql.TypeFloat:
_, fVal, err := codec.DecodeFloat(colData)
if err != nil {
return err
}
chk.AppendFloat32(colIdx, float32(fVal))
case mysql.TypeDouble:
_, fVal, err := codec.DecodeFloat(colData)
if err != nil {
return err
}
chk.AppendFloat64(colIdx, fVal)
case mysql.TypeVarString, mysql.TypeVarchar, mysql.TypeString,
mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:
chk.AppendBytes(colIdx, colData)
case mysql.TypeNewDecimal:
_, dec, _, frac, err := codec.DecodeDecimal(colData)
if err != nil {
return err
}
if col.Ft.GetDecimal() != types.UnspecifiedLength && frac > col.Ft.GetDecimal() {
to := new(types.MyDecimal)
err := dec.Round(to, col.Ft.GetDecimal(), types.ModeHalfUp)
if err != nil {
return errors.Trace(err)
}
dec = to
}
chk.AppendMyDecimal(colIdx, dec)
case mysql.TypeDate, mysql.TypeDatetime, mysql.TypeTimestamp:
var t types.Time
t.SetType(col.Ft.GetType())
t.SetFsp(col.Ft.GetDecimal())
err := t.FromPackedUint(decodeUint(colData))
if err != nil {
return err
}
if col.Ft.GetType() == mysql.TypeTimestamp && decoder.loc != nil && !t.IsZero() {
err = t.ConvertTimeZone(time.UTC, decoder.loc)
if err != nil {
return err
}
}
chk.AppendTime(colIdx, t)
case mysql.TypeDuration:
var dur types.Duration
dur.Duration = time.Duration(decodeInt(colData))
dur.Fsp = col.Ft.GetDecimal()
chk.AppendDuration(colIdx, dur)
case mysql.TypeEnum:
// ignore error deliberately, to read empty enum value.
enum, err := types.ParseEnumValue(col.Ft.GetElems(), decodeUint(colData))
if err != nil {
enum = types.Enum{}
}
chk.AppendEnum(colIdx, enum)
case mysql.TypeSet:
set, err := types.ParseSetValue(col.Ft.GetElems(), decodeUint(colData))
if err != nil {
return err
}
chk.AppendSet(colIdx, set)
case mysql.TypeBit:
byteSize := (col.Ft.GetFlen() + 7) >> 3
chk.AppendBytes(colIdx, types.NewBinaryLiteralFromUint(decodeUint(colData), byteSize))
case mysql.TypeJSON:
var j types.BinaryJSON
j.TypeCode = colData[0]
j.Value = colData[1:]
chk.AppendJSON(colIdx, j)
default:
return errors.Errorf("unknown type %d", col.Ft.GetType())
}
return nil
}
// BytesDecoder decodes the row to old datums bytes.
type BytesDecoder struct {
decoder
defBytes func(i int) ([]byte, error)
}
// NewByteDecoder creates a BytesDecoder.
// defBytes: provided default value bytes in old datum format(flag+colData).
func NewByteDecoder(columns []ColInfo, handleColIDs []int64, defBytes func(i int) ([]byte, error), loc *time.Location) *BytesDecoder {
return &BytesDecoder{
decoder: decoder{
columns: columns,
handleColIDs: handleColIDs,
loc: loc,
},
defBytes: defBytes,
}
}
func (decoder *BytesDecoder) decodeToBytesInternal(outputOffset map[int64]int, handle kv.Handle, value []byte, cacheBytes []byte) ([][]byte, error) {
var r row
err := r.fromBytes(value)
if err != nil {
return nil, err
}
values := make([][]byte, len(outputOffset))
for i := range decoder.columns {
col := &decoder.columns[i]
tp := fieldType2Flag(col.Ft.GetType(), col.Ft.GetFlag()&mysql.UnsignedFlag == 0)
colID := col.ID
offset := outputOffset[colID]
idx, isNil, notFound := r.findColID(colID)
if !notFound && !isNil {
val := r.getData(idx)
values[offset] = decoder.encodeOldDatum(tp, val)
continue
}
// Only try to decode handle when there is no corresponding column in the value.
// This is because the information in handle may be incomplete in some cases.
// For example, prefixed clustered index like 'primary key(col1(1))' only store the leftmost 1 char in the handle.
if decoder.tryDecodeHandle(values, offset, col, handle, cacheBytes) {
continue
}
if isNil {
values[offset] = []byte{NilFlag}
continue
}
if decoder.defBytes != nil {
defVal, err := decoder.defBytes(i)
if err != nil {
return nil, err
}
if len(defVal) > 0 {
values[offset] = defVal
continue
}
}
values[offset] = []byte{NilFlag}
}
return values, nil
}
func (decoder *BytesDecoder) tryDecodeHandle(values [][]byte, offset int, col *ColInfo,
handle kv.Handle, cacheBytes []byte) bool {
if handle == nil {
return false
}
if types.NeedRestoredData(col.Ft) {
return false
}
if col.IsPKHandle || col.ID == model.ExtraHandleID {
handleData := cacheBytes
if mysql.HasUnsignedFlag(col.Ft.GetFlag()) {
handleData = append(handleData, UintFlag)
handleData = codec.EncodeUint(handleData, uint64(handle.IntValue()))
} else {
handleData = append(handleData, IntFlag)
handleData = codec.EncodeInt(handleData, handle.IntValue())
}
values[offset] = handleData
return true
}
var handleData []byte
for i, hid := range decoder.handleColIDs {
if col.ID == hid {
handleData = append(handleData, handle.EncodedCol(i)...)
}
}
if len(handleData) > 0 {
values[offset] = handleData
return true
}
return false
}
// DecodeToBytesNoHandle decodes raw byte slice to row data without handle.
func (decoder *BytesDecoder) DecodeToBytesNoHandle(outputOffset map[int64]int, value []byte) ([][]byte, error) {
return decoder.decodeToBytesInternal(outputOffset, nil, value, nil)
}
// DecodeToBytes decodes raw byte slice to row data.
func (decoder *BytesDecoder) DecodeToBytes(outputOffset map[int64]int, handle kv.Handle, value []byte, cacheBytes []byte) ([][]byte, error) {
return decoder.decodeToBytesInternal(outputOffset, handle, value, cacheBytes)
}
func (*BytesDecoder) encodeOldDatum(tp byte, val []byte) []byte {
buf := make([]byte, 0, 1+binary.MaxVarintLen64+len(val))
switch tp {
case BytesFlag:
buf = append(buf, CompactBytesFlag)
buf = codec.EncodeCompactBytes(buf, val)
case IntFlag:
buf = append(buf, VarintFlag)
buf = codec.EncodeVarint(buf, decodeInt(val))
case UintFlag:
buf = append(buf, VaruintFlag)
buf = codec.EncodeUvarint(buf, decodeUint(val))
default:
buf = append(buf, tp)
buf = append(buf, val...)
}
return buf
}
// fieldType2Flag transforms field type into kv type flag.
func fieldType2Flag(tp byte, signed bool) (flag byte) {
switch tp {
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong:
if signed {
flag = IntFlag
} else {
flag = UintFlag
}
case mysql.TypeFloat, mysql.TypeDouble:
flag = FloatFlag
case mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob,
mysql.TypeString, mysql.TypeVarchar, mysql.TypeVarString:
flag = BytesFlag
case mysql.TypeDatetime, mysql.TypeDate, mysql.TypeTimestamp:
flag = UintFlag
case mysql.TypeDuration:
flag = IntFlag
case mysql.TypeNewDecimal:
flag = DecimalFlag
case mysql.TypeYear:
flag = IntFlag
case mysql.TypeEnum, mysql.TypeBit, mysql.TypeSet:
flag = UintFlag
case mysql.TypeJSON:
flag = JSONFlag
case mysql.TypeNull:
flag = NilFlag
default:
panic(fmt.Sprintf("unknown field type %d", tp))
}
return
}
|
package four
type DayList struct {
days map[string]*Day
}
func NewDayList() DayList {
days := make(map[string]*Day)
return DayList{days: days}
}
func (d DayList) checkAndAppend(date string) *Day {
dayPtr, exists := d.days[date]
if !exists {
day := NewDay()
dayPtr = &day
d.days[date] = dayPtr
}
return dayPtr
}
|
package podstore
import (
"testing"
"time"
podstore_protos "github.com/square/p2/pkg/grpc/podstore/protos"
"github.com/square/p2/pkg/grpc/testutil"
"github.com/square/p2/pkg/launch"
"github.com/square/p2/pkg/manifest"
"github.com/square/p2/pkg/store/consul"
"github.com/square/p2/pkg/store/consul/consulutil"
"github.com/square/p2/pkg/store/consul/podstore"
"github.com/square/p2/pkg/store/consul/podstore/podstoretest"
"github.com/square/p2/pkg/store/consul/statusstore"
"github.com/square/p2/pkg/store/consul/statusstore/podstatus"
"github.com/square/p2/pkg/store/consul/statusstore/statusstoretest"
"github.com/square/p2/pkg/types"
context "golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
func TestSchedulePod(t *testing.T) {
fakePodStore, server := setupServerWithFakePodStore()
req := &podstore_protos.SchedulePodRequest{
Manifest: validManifestString(),
NodeName: "test_node",
}
resp, err := server.SchedulePod(context.Background(), req)
if err != nil {
t.Fatalf("Unexpected error from SchedulePod: %s", err)
}
// check that the key we got back actually returns an entry from the store
pod, err := fakePodStore.ReadPod(types.PodUniqueKey(resp.PodUniqueKey))
if err != nil {
t.Fatalf("Unexpected error reading pod out of store after scheduling: %s", err)
}
if pod.Manifest.ID() != "test_app" {
t.Errorf("Scheduled pod manifest had wrong ID, expected %q but got %q", "test_app", pod.Manifest.ID())
}
if pod.Node != "test_node" {
t.Errorf("Scheduled node didn't match expectation, expected %q but got %q", "test_node", pod.Node)
}
}
func TestSchedulePodFailsNoNodeName(t *testing.T) {
_, server := setupServerWithFakePodStore()
req := &podstore_protos.SchedulePodRequest{
Manifest: validManifestString(),
NodeName: "", // MISSING
}
_, err := server.SchedulePod(context.Background(), req)
if err == nil {
t.Fatal("Expected an error when the request is missing node name, but didn't get one")
}
if grpc.Code(err) != codes.InvalidArgument {
t.Errorf("Expected error to be %s but was %s", codes.InvalidArgument.String(), grpc.ErrorDesc(err))
}
}
func TestSchedulePodFailsNoManifest(t *testing.T) {
_, server := setupServerWithFakePodStore()
req := &podstore_protos.SchedulePodRequest{
Manifest: "", // MISSING
NodeName: "test_node",
}
_, err := server.SchedulePod(context.Background(), req)
if err == nil {
t.Fatal("Expected an error when the request is missing manifest, but didn't get one")
}
if grpc.Code(err) != codes.InvalidArgument {
t.Errorf("Expected error to be %s but was %s", codes.InvalidArgument.String(), grpc.ErrorDesc(err))
}
}
func TestUnschedulePod(t *testing.T) {
store, server := setupServerWithFakePodStore()
key, err := store.Schedule(validManifest(), "some_node")
if err != nil {
t.Fatalf("could not seed pod store with a pod to unschedule: %s", err)
}
req := &podstore_protos.UnschedulePodRequest{
PodUniqueKey: key.String(),
}
resp, err := server.UnschedulePod(context.Background(), req)
if err != nil {
t.Errorf("unexpected error unscheduling pod: %s", err)
}
if resp == nil {
t.Error("expected non-nil response on successful pod unschedule")
}
}
func TestUnschedulePodNotFound(t *testing.T) {
_, server := setupServerWithFakePodStore()
// unschedule a random key that doesn't exist in the store
req := &podstore_protos.UnschedulePodRequest{
PodUniqueKey: types.NewPodUUID().String(),
}
resp, err := server.UnschedulePod(context.Background(), req)
if err == nil {
t.Error("expected error unscheduling nonexistent pod")
}
if grpc.Code(err) != codes.NotFound {
t.Errorf("expected not found error when unscheduling a nonexistent pod, but error was %s", err)
}
if resp != nil {
t.Error("expected nil response when attempting to unschedule a nonexistent pod")
}
}
func TestUnscheduleError(t *testing.T) {
// Create a server with a failing pod store so we can test what happens when
// a failure is encountered
server := store{
scheduler: podstoretest.NewFailingPodStore(),
}
req := &podstore_protos.UnschedulePodRequest{
PodUniqueKey: types.NewPodUUID().String(),
}
resp, err := server.UnschedulePod(context.Background(), req)
if err == nil {
t.Fatal("expected an error unscheduling a pod using a failing pod store")
}
if grpc.Code(err) != codes.Unavailable {
t.Fatalf("expected an unavailable error when unscheduling from store fails but got %s", err)
}
if resp != nil {
t.Fatal("expected nil response when encountering an unscheduling error")
}
}
func validManifestString() string {
return "id: test_app"
}
func validManifest() manifest.Manifest {
builder := manifest.NewBuilder()
builder.SetID("test_app")
return builder.GetManifest()
}
// implements podstore_protos.PodStore_WatchPodStatusServer
type WatchPodStatusStream struct {
*testutil.FakeServerStream
ResponseCh chan *podstore_protos.PodStatusResponse
}
// Records responses sent on the stream
func (w *WatchPodStatusStream) Send(resp *podstore_protos.PodStatusResponse) error {
w.ResponseCh <- resp
return nil
}
func TestWatchPodStatus(t *testing.T) {
respCh := make(chan *podstore_protos.PodStatusResponse)
stream := &WatchPodStatusStream{
FakeServerStream: testutil.NewFakeServerStream(context.Background()),
ResponseCh: respCh,
}
podStatusStore, server := setupServerWithFakePodStatusStore()
podUniqueKey := types.NewPodUUID()
req := &podstore_protos.WatchPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
PodUniqueKey: podUniqueKey.String(),
WaitForExists: true,
}
watchErrCh := make(chan error)
defer close(watchErrCh)
go func() {
err := server.WatchPodStatus(req, stream)
if err != nil {
watchErrCh <- err
}
}()
expectedTime := time.Now()
expectedManifest := `id: "test_app"`
expectedPodState := podstatus.PodLaunched
expectedLaunchableID := launch.LaunchableID("nginx")
expectedEntryPoint := "launch"
expectedExitCode := 3
expectedExitStatus := 4
setStatusErrCh := make(chan error)
defer close(setStatusErrCh)
go func() {
err := podStatusStore.Set(podUniqueKey, podstatus.PodStatus{
Manifest: expectedManifest,
PodStatus: expectedPodState,
ProcessStatuses: []podstatus.ProcessStatus{
{
LaunchableID: expectedLaunchableID,
EntryPoint: expectedEntryPoint,
LastExit: &podstatus.ExitStatus{
ExitTime: expectedTime,
ExitCode: expectedExitCode,
ExitStatus: expectedExitStatus,
},
},
},
})
if err != nil {
setStatusErrCh <- err
}
}()
select {
case <-time.After(5 * time.Second):
t.Fatal("Didn't receive value after 5 seconds")
case err := <-setStatusErrCh:
t.Fatalf("Error setting status to trigger watch: %s", err)
case err := <-watchErrCh:
t.Fatalf("Unexpected error watching for status: %s", err)
case resp := <-respCh:
if resp.Manifest != expectedManifest {
t.Errorf("Manifest didn't match expected, wanted %q got %q", expectedManifest, resp.Manifest)
}
if resp.PodState != expectedPodState.String() {
t.Errorf("PodState didn't match expcted, wanted %q got %q", expectedPodState, resp.PodState)
}
if len(resp.ProcessStatuses) != 1 {
t.Fatalf("Expected 1 process status in pod status but got %d", len(resp.ProcessStatuses))
}
processStatus := resp.ProcessStatuses[0]
if processStatus.LaunchableId != expectedLaunchableID.String() {
t.Errorf("Expected process status for launchable %q but found %q", expectedLaunchableID, processStatus.LaunchableId)
}
if processStatus.EntryPoint != expectedEntryPoint {
t.Errorf("Expected process status for entry point %q but found %q", expectedEntryPoint, processStatus.EntryPoint)
}
if processStatus.LastExit == nil {
t.Fatal("Expected exit information for process")
}
lastExit := processStatus.LastExit
if lastExit.ExitTime != expectedTime.Unix() {
t.Error("Exit time for process in status didn't match expected")
}
if lastExit.ExitCode != int64(expectedExitCode) {
t.Errorf("Expected exit code %d but got %d", expectedExitCode, lastExit.ExitCode)
}
if lastExit.ExitStatus != int64(expectedExitStatus) {
t.Errorf("Expected exit status %d but got %d", expectedExitStatus, lastExit.ExitStatus)
}
}
}
func TestListPodStatus(t *testing.T) {
statusStore, server := setupServerWithFakePodStatusStore()
results, err := server.ListPodStatus(context.Background(), &podstore_protos.ListPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
})
if err != nil {
t.Errorf("error listing pod status: %s", err)
}
if len(results.PodStatuses) != 0 {
t.Fatalf("expected no results when listing pod status from empty store but got %d", len(results.PodStatuses))
}
key := types.NewPodUUID()
err = statusStore.Set(key, podstatus.PodStatus{
PodStatus: podstatus.PodLaunched,
})
if err != nil {
t.Fatalf("unable to seed status store with a pod status: %s", err)
}
results, err = server.ListPodStatus(context.Background(), &podstore_protos.ListPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
})
if err != nil {
t.Errorf("error listing pod status: %s", err)
}
if len(results.PodStatuses) != 1 {
t.Fatalf("expected one status record but there were %d", len(results.PodStatuses))
}
val, ok := results.PodStatuses[key.String()]
if !ok {
t.Fatalf("expected a record for pod %s but there wasn't", key)
}
if val.PodState != podstatus.PodLaunched.String() {
t.Errorf("expected pod status of status record to be %q but was %q", podstatus.PodLaunched, val.PodState)
}
}
func TestDeletePodStatus(t *testing.T) {
statusStore, server := setupServerWithFakePodStatusStore()
key := types.NewPodUUID()
err := statusStore.Set(key, podstatus.PodStatus{
PodStatus: podstatus.PodLaunched,
})
if err != nil {
t.Fatalf("unable to seed status store with a pod status: %s", err)
}
// confirm that there is one entry
results, err := server.ListPodStatus(context.Background(), &podstore_protos.ListPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
})
if err != nil {
t.Errorf("error listing pod status: %s", err)
}
if len(results.PodStatuses) != 1 {
t.Fatalf("expected one status record but there were %d", len(results.PodStatuses))
}
// now delete it
_, err = server.DeletePodStatus(context.Background(), &podstore_protos.DeletePodStatusRequest{
PodUniqueKey: key.String(),
})
if err != nil {
t.Fatalf("error deleting pod status: %s", err)
}
// confirm that there are now no entries
results, err = server.ListPodStatus(context.Background(), &podstore_protos.ListPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
})
if err != nil {
t.Errorf("error listing pod status: %s", err)
}
if len(results.PodStatuses) != 0 {
t.Fatalf("expected no status records but there were %d", len(results.PodStatuses))
}
}
// Tests the convenience function that converts from the protobuf definition of
// pod status to the raw type.
func TestPodStatusResposeToPodStatus(t *testing.T) {
in := podstore_protos.PodStatusResponse{
PodState: "removed",
Manifest: "id: foobar",
ProcessStatuses: []*podstore_protos.ProcessStatus{
{
LaunchableId: "whatever",
EntryPoint: "some_entry_point",
LastExit: &podstore_protos.ExitStatus{
ExitTime: 10000,
ExitCode: 24,
ExitStatus: 1800,
},
},
},
}
out := PodStatusResponseToPodStatus(in)
if out.PodStatus.String() != in.PodState {
t.Errorf("expected pod status to be %q but was %q", in.PodState, out.PodStatus)
}
if out.Manifest != in.Manifest {
t.Errorf("expected manifest to be %q but was %q", in.Manifest, out.Manifest)
}
if len(out.ProcessStatuses) != len(in.ProcessStatuses) {
t.Fatalf("expected %d process status(es) but got %d", len(in.ProcessStatuses), len(out.ProcessStatuses))
}
inPS := in.ProcessStatuses[0]
outPS := out.ProcessStatuses[0]
if outPS.LaunchableID.String() != inPS.LaunchableId {
t.Errorf("expected launchable id to be %q but was %q", inPS.LaunchableId, outPS.LaunchableID)
}
if outPS.EntryPoint != inPS.EntryPoint {
t.Errorf("expected entry point to be %q but was %q", inPS.EntryPoint, outPS.EntryPoint)
}
inLE := inPS.LastExit
outLE := outPS.LastExit
if outLE == nil {
t.Fatal("expected non-nil last exit")
}
if outLE.ExitTime.Unix() != inLE.ExitTime {
t.Errorf("expected last exit time to be %d but was %d", inLE.ExitTime, outLE.ExitTime.Unix())
}
if outLE.ExitCode != int(inLE.ExitCode) {
t.Errorf("expected exit code to be %d but was %d", inLE.ExitCode, outLE.ExitCode)
}
if outLE.ExitStatus != int(inLE.ExitStatus) {
t.Errorf("expected exit status to be %d but was %d", inLE.ExitStatus, outLE.ExitStatus)
}
}
func TestMarkPodFailed(t *testing.T) {
fixture := consulutil.NewFixture(t)
defer fixture.Stop()
statusStore := podstatus.NewConsul(statusstore.NewConsul(fixture.Client), consul.PreparerPodStatusNamespace)
server := store{
podStatusStore: statusStore,
consulClient: fixture.Client,
}
key := types.NewPodUUID()
err := statusStore.Set(key, podstatus.PodStatus{
PodStatus: podstatus.PodLaunched,
})
if err != nil {
t.Fatalf("unable to seed status store with a pod status: %s", err)
}
// mark it as failed
_, err = server.MarkPodFailed(context.Background(), &podstore_protos.MarkPodFailedRequest{
PodUniqueKey: key.String(),
})
if err != nil {
t.Fatalf("error marking pod failed: %s", err)
}
// confirm that the record is now failed
resp, err := server.ListPodStatus(context.Background(), &podstore_protos.ListPodStatusRequest{
StatusNamespace: consul.PreparerPodStatusNamespace.String(),
})
if err != nil {
t.Fatalf("could not list pod status to confirm marking pod as failed: %s", err)
}
val, ok := resp.PodStatuses[key.String()]
if !ok {
t.Fatal("no status record found for the pod we marked failed")
}
if val.PodState != podstatus.PodFailed.String() {
t.Errorf("expected pod to be marked %q but was %q", podstatus.PodFailed, val.PodState)
}
}
func setupServerWithFakePodStore() (podstore.Store, store) {
fakePodStore := podstore.NewConsul(consulutil.NewFakeClient().KV_)
server := store{
scheduler: fakePodStore,
}
return fakePodStore, server
}
// augment PodStatusStore interface so we can do some test setup
type testPodStatusStore interface {
PodStatusStore
Set(key types.PodUniqueKey, status podstatus.PodStatus) error
}
func setupServerWithFakePodStatusStore() (testPodStatusStore, store) {
fakePodStatusStore := podstatus.NewConsul(statusstoretest.NewFake(), consul.PreparerPodStatusNamespace)
return fakePodStatusStore, store{
podStatusStore: fakePodStatusStore,
}
}
|
package main
type tableInfo struct {
name string
columns []*columnInfo
}
type columnInfo struct {
field string
typeName string
isNull bool
key string
defaultVal *string
extra string
}
|
package neunet2
import (
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
var Colours = []string{
"FF0000",
"FFFF00",
"00FF00",
"00FFFF",
"0000FF",
"FF00FF",
}
type Chart struct {
Title string
Datasets [][]float32
}
func NewChart() (chart *Chart) {
chart = new(Chart)
chart.Datasets = make([][]float32, 0)
return chart
}
func (chart *Chart) Data() (data url.Values) {
data = make(url.Values)
data.Add("cht", "lxy")
data.Add("chs", "300x400")
data.Add("chtt", chart.Title)
data.Add("chds", "a")
nextColour := 0
strcols := make([]string, len(chart.Datasets))
strsets := make([]string, len(chart.Datasets))
for j, dataset := range chart.Datasets {
strset := make([]string, len(dataset))
for i := 0; i < len(dataset); i++ {
strset[i] = strconv.FormatFloat(float64(dataset[i]), 'f', -1, 32)
}
strcols[j] = Colours[nextColour]
strsets[j] = strings.Join(strset, ",")
nextColour = (nextColour + 1) % len(Colours)
}
data.Add("chco", strings.Join(strcols, ","))
data.Add("chd", "t:"+strings.Join(strsets, "|"))
return data
}
func (chart *Chart) URL() (url string) {
return "https://chart.googleapis.com/chart?" + chart.Data().Encode()
}
func (chart *Chart) Download(fname string) (err error) {
f, err := os.Create(fname)
if err != nil {
return err
}
defer f.Close()
resp, err := http.Get(chart.URL())
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(f, resp.Body)
return nil
}
|
package pdexv3
import (
"encoding/json"
"incognito-chain/common"
metadataCommon "incognito-chain/metadata/common"
"incognito-chain/privacy"
)
type AddLiquidityRequest struct {
poolPairID string // only "" for the first contribution of pool
pairHash string
otaReceiver string // refund pToken
otaReceivers map[common.Hash]privacy.OTAReceiver // receive tokens
tokenID string
AccessOption
tokenAmount uint64
amplifier uint // only set for the first contribution
metadataCommon.MetadataBase
}
func NewAddLiquidity() *AddLiquidityRequest {
return &AddLiquidityRequest{}
}
func (request *AddLiquidityRequest) MarshalJSON() ([]byte, error) {
data, err := json.Marshal(struct {
PoolPairID string `json:"PoolPairID"` // only "" for the first contribution of pool
PairHash string `json:"PairHash"`
OtaReceiver string `json:"OtaReceiver,omitempty"` // receive pToken
OtaReceivers map[common.Hash]privacy.OTAReceiver `json:"OtaReceivers,omitempty"`
TokenID string `json:"TokenID"`
AccessOption
TokenAmount uint64 `json:"TokenAmount"`
Amplifier uint `json:"Amplifier"` // only set for the first contribution
metadataCommon.MetadataBase
}{
PoolPairID: request.poolPairID,
PairHash: request.pairHash,
OtaReceiver: request.otaReceiver,
TokenID: request.tokenID,
TokenAmount: request.tokenAmount,
Amplifier: request.amplifier,
AccessOption: request.AccessOption,
MetadataBase: request.MetadataBase,
OtaReceivers: request.otaReceivers,
})
if err != nil {
return []byte{}, err
}
return data, nil
}
func (request *AddLiquidityRequest) UnmarshalJSON(data []byte) error {
temp := struct {
PoolPairID string `json:"PoolPairID"` // only "" for the first contribution of pool
PairHash string `json:"PairHash"`
OtaReceiver string `json:"OtaReceiver,omitempty"` // receive pToken
OtaReceivers map[common.Hash]privacy.OTAReceiver `json:"OtaReceivers,omitempty"`
TokenID string `json:"TokenID"`
AccessOption
TokenAmount metadataCommon.Uint64Reader `json:"TokenAmount"`
Amplifier uint `json:"Amplifier"` // only set for the first contribution
metadataCommon.MetadataBase
}{}
err := json.Unmarshal(data, &temp)
if err != nil {
return err
}
request.poolPairID = temp.PoolPairID
request.pairHash = temp.PairHash
request.otaReceiver = temp.OtaReceiver
request.tokenID = temp.TokenID
request.AccessOption = temp.AccessOption
request.tokenAmount = uint64(temp.TokenAmount)
request.amplifier = temp.Amplifier
request.MetadataBase = temp.MetadataBase
request.AccessOption = temp.AccessOption
request.otaReceivers = temp.OtaReceivers
return nil
}
func (request *AddLiquidityRequest) PoolPairID() string {
return request.poolPairID
}
func (request *AddLiquidityRequest) PairHash() string {
return request.pairHash
}
func (request *AddLiquidityRequest) OtaReceiver() string {
return request.otaReceiver
}
func (request *AddLiquidityRequest) TokenID() string {
return request.tokenID
}
func (request *AddLiquidityRequest) TokenAmount() uint64 {
return request.tokenAmount
}
func (request *AddLiquidityRequest) Amplifier() uint {
return request.amplifier
}
|
package main
import (
_ "./api/"
api_ctrl "./api/controllers"
"./pkg"
pkg_model "./pkg/models"
// "./statistics"
// stat_model "./statistics/models"
"./notify"
trans "./transfer"
trans_model "./transfer/models"
"./transfer/task"
"./utils"
"./utils/cache"
"./utils/db"
"fmt"
"github.com/astaxie/beego"
clog "github.com/cihub/seelog"
"github.com/go-ini/ini"
"time"
)
const (
VERSION = "0.2.1"
)
const (
PROFILE = "/opt/cydex/etc/ts.d/profile.ini"
CFGFILE = "/opt/cydex/config/ts.ini"
)
var (
ws_server *trans.WSServer
http_addr string
beego_loglevel int
)
func initLog() {
cfgfiles := []string{
"/opt/cydex/etc/ts.d/seelog.xml",
"seelog.xml",
}
for _, file := range cfgfiles {
logger, err := clog.LoggerFromConfigAsFile(file)
if err != nil {
println(err.Error())
continue
}
clog.ReplaceLogger(logger)
break
}
}
func setupUserDB(cfg *ini.File) (err error) {
// 连接User数据库
clog.Info("setup user db")
sec, err := cfg.GetSection("user_db")
if err != nil {
return err
}
driver := sec.Key("driver").String()
source := sec.Key("source").String()
show_sql := sec.Key("show_sql").MustBool()
clog.Infof("[setup db] url:'%s %s' show_sql:%t", driver, source, show_sql)
if err = db.CreateUserEngine(driver, source, show_sql); err != nil {
return
}
return
}
func setupDB(cfg *ini.File) (err error) {
// 创建数据库
clog.Info("setup db")
sec, err := cfg.GetSection("db")
if err != nil {
return err
}
driver := sec.Key("driver").String()
source := sec.Key("source").String()
show_sql := sec.Key("show_sql").MustBool()
clog.Infof("[setup db] url:'%s %s' show_sql:%t", driver, source, show_sql)
if err = db.CreateEngine(driver, source, show_sql); err != nil {
return
}
// 同步表结构
var tables []interface{}
tables = append(tables, pkg_model.Tables...)
tables = append(tables, trans_model.Tables...)
// tables = append(tables, stat_model.Tables...)
if err = db.SyncTables(tables); err != nil {
return
}
// 设置cache
var caches []interface{}
caches = append(caches, pkg_model.Caches...)
caches = append(caches, trans_model.Caches...)
// caches = append(caches, stat_model.Caches...)
db.MapCache(caches)
// migrate db and data
clog.Infof("[setup db] migrate...")
pkg.JobMgr.JobsSyncState()
clog.Infof("[setup db] migrate ok")
return
}
func setupRedis(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("redis")
if err != nil {
return err
}
url := sec.Key("url").String()
max_idles := sec.Key("max_idles").MustInt(3)
idle_timeout := sec.Key("idle_timeout").MustInt(240)
clog.Infof("[setup cache] url:'%s' max_idle:%d idle_timeout:%d", url, max_idles, idle_timeout)
cache.Init(url, max_idles, idle_timeout)
// test cache first
err = cache.Ping()
if err != nil {
return err
}
return
}
func setupWebsocketService(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("websocket")
if err != nil {
return err
}
url := sec.Key("url").String()
port := sec.Key("port").RangeInt(-1, 0, 65535)
if url == "" || port == -1 {
err = fmt.Errorf("Invalid websocket url:%s or port:%d", url, port)
return
}
ssl := sec.Key("ssl").MustBool(false)
cert_file := sec.Key("cert_file").MustString("")
key_file := sec.Key("key_file").MustString("")
idle_timeout := sec.Key("idle_timeout").MustUint(10)
keepalive_interval := sec.Key("keepalive_interval").MustUint(180)
notify_interval := sec.Key("notify_interval").MustUint(3)
ws_cfg := &trans.WSServerConfig{
UseSSL: ssl,
CertFile: cert_file,
KeyFile: key_file,
ConnDeadline: time.Duration(idle_timeout) * time.Second,
KeepaliveInterval: keepalive_interval,
TransferNotifyInterval: notify_interval,
}
clog.Infof("[setup websocket] listen port:%d, ssl:%t with config [%d, %d, %d]", port, ssl, idle_timeout, keepalive_interval, notify_interval)
ws_server = trans.NewWSServer(url, port, ws_cfg)
return
}
func setupPkg(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("pkg")
if err != nil {
return err
}
file_slice := sec.Key("file_slice").MustBool(true)
pkg.SetUsingFileSlice(file_slice)
var unpacker pkg.Unpacker
unpacker_str := sec.Key("unpacker").MustString("default")
clog.Infof("[setup pkg] unpacker: %s, file slice: %t", unpacker_str, file_slice)
switch unpacker_str {
case "default":
sec_unpacker, err := cfg.GetSection("default_unpacker")
if err != nil {
return err
}
min_seg_size := utils.ConfigGetSize(sec_unpacker.Key("min_seg_size").String())
if min_seg_size == 0 {
err = fmt.Errorf("Invalid min_seg_size:%d", min_seg_size)
return err
}
max_seg_cnt, err := sec_unpacker.Key("max_seg_cnt").Uint()
if err != nil {
return err
}
clog.Infof("[setup pkg] default unpacker: %d, %d", min_seg_size, max_seg_cnt)
unpacker = pkg.NewDefaultUnpacker(uint64(min_seg_size), max_seg_cnt)
default:
err = fmt.Errorf("Unsupport unpacker name:%s", unpacker)
return
}
pkg.SetUnpacker(unpacker)
return
}
func setupTask(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("task")
if err != nil {
return err
}
var restrict_mode int
restrict_str := sec.Key("restrict_mode").MustString("pid")
clog.Infof("[setup task] restrict_mode: %s", restrict_str)
switch restrict_str {
case "pid":
restrict_mode = task.TASK_RESTRICT_BY_PID
case "fid":
restrict_mode = task.TASK_RESTRICT_BY_FID
default:
err = fmt.Errorf("Unknow restrict mode %s", restrict_str)
return
}
scheduler_str := sec.Key("scheduler").MustString("default")
clog.Infof("[setup task] scheduler:%s", scheduler_str)
switch scheduler_str {
case "default":
task.TaskMgr.SetScheduler(task.NewDefaultScheduler(restrict_mode))
default:
err = fmt.Errorf("Unsupport task scheduler name:%s", scheduler_str)
return
}
cache_timeout, err := sec.Key("cache_timeout").Int()
if err != nil {
return err
}
clog.Infof("[setup task] task cache timeout:%d", cache_timeout)
task.TaskMgr.SetCacheTimeout(cache_timeout)
return
}
func setupHttp(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("http")
if err != nil {
return err
}
addr := sec.Key("addr").String()
if addr == "" {
err = fmt.Errorf("Http addr can't be empty!")
return
}
show_req := sec.Key("show_req").MustBool(false)
show_rsp := sec.Key("show_rsp").MustBool(false)
clog.Infof("[setup http] addr:'%s', show: [%t, %t]", addr, show_req, show_rsp)
http_addr = addr
api_ctrl.SetupBodyShow(show_req, show_rsp)
fake_api := sec.Key("fake_api").MustBool(false)
if fake_api {
clog.Infof("Enable fake api for standalone running")
EnableFakeApi()
}
beego_loglevel = sec.Key("beego_loglevel").MustInt(beego.LevelInformational)
return
}
func setupNotificationEmailHandler(cfg *ini.File, sec *ini.Section) error {
enable := sec.Key("enable").MustBool(false)
smtp_label := sec.Key("smtp_server").MustString("default")
contact_name := sec.Key("contact_name").String()
templates_dir := sec.Key("templates_dir").String()
smtp_sec, err := cfg.GetSection(fmt.Sprintf("smtp_server.%s", smtp_label))
if err != nil {
return err
}
smtp_server := notify.SmtpServer{
Label: smtp_label,
Host: smtp_sec.Key("host").String(),
Port: smtp_sec.Key("port").MustInt(0),
Account: smtp_sec.Key("account").String(),
Password: smtp_sec.Key("password").String(),
UseTLS: smtp_sec.Key("use_tls").MustBool(false),
}
notify.Email.SetEnable(enable)
notify.Email.SetContactName(contact_name)
notify.Email.SetSmtpServer(&smtp_server)
notify.Email.SetTemplateBaseDir(templates_dir)
// load templates
if err := notify.Email.LoadTemplates(); err != nil {
return err
}
return nil
}
func setupNotification(cfg *ini.File) (err error) {
sec, err := cfg.GetSection("notification")
if err != nil {
return err
}
enable := sec.Key("enable").MustBool(false)
notify.Manage.SetEnable(enable)
handlers := sec.Key("handlers").Strings(utils.CFG_SEP)
for _, handler := range handlers {
handler_sec, err := cfg.GetSection(fmt.Sprintf("notification.%s", handler))
if err != nil {
continue
}
switch handler {
case "email":
if err := setupNotificationEmailHandler(cfg, handler_sec); err != nil {
return err
}
}
}
return nil
}
func setupApplication(cfg *ini.File) (err error) {
if err = setupDB(cfg); err != nil {
return
}
if err = setupUserDB(cfg); err != nil {
return
}
if err = setupRedis(cfg); err != nil {
return
}
if err = setupPkg(cfg); err != nil {
return
}
if err = setupTask(cfg); err != nil {
return
}
if err = setupWebsocketService(cfg); err != nil {
return
}
if err = setupHttp(cfg); err != nil {
return
}
if err = setupNotification(cfg); err != nil {
return
}
return
}
func run() {
// setup version
ws_server.SetVersion(VERSION)
// task add observer for job
task.TaskMgr.AddObserver(pkg.JobMgr)
// task add observer for statistics
// task.TaskMgr.AddObserver(statistics.TransferMgr)
// 从数据库导入track
pkg.JobMgr.LoadTracks()
// job add observer for notification
pkg.JobMgr.AddJobObserver(notify.Manage)
go task.TaskMgr.TaskStateRoutine()
go ws_server.Serve()
clog.Info("Notification start")
go notify.Manage.Serve()
clog.Info("Notification email handler start")
notify.Email.Start()
beego.SetLevel(beego_loglevel)
go beego.Run(http_addr)
clog.Info("Run...")
}
func main() {
initLog()
clog.Infof("Start cydex transfer service, version:%s", VERSION)
config := utils.NewConfig(PROFILE, CFGFILE)
if config == nil {
clog.Critical("new config failed")
return
}
utils.MakeDefaultConfig(config)
cfg, err := config.Load()
if err != nil {
clog.Critical(err)
return
}
if err = setupApplication(cfg); err != nil {
clog.Critical(err)
return
}
run()
for {
time.Sleep(10 * time.Minute)
}
}
|
package gorasp
import (
"errors"
"math/bits"
)
// struct that will implement the RankSelect interface.
type RankSelectFast struct {
packedArray []uint64
partialRanks []uint
partialSelects []uint32
n int
}
func (self *RankSelectFast) At(index int) int {
if index >= self.n {
return 0 // return an error or just pretend everything beyond n is 0?
}
return int(getBit(self.packedArray, index))
}
func (self *RankSelectFast) getWordIndexOfWordWithKthOneBit(k int) (rank, wordIdx int) {
bitIdx := self.partialSelects[k/64]
tmpWordIdx := bitIdx / 64
rankSoFar := int(self.partialRanks[tmpWordIdx])
for wordIdx := bitIdx / 64; wordIdx < uint32(len(self.packedArray)); wordIdx++ {
word := self.packedArray[wordIdx]
onesCount := bits.OnesCount64(word)
if rankSoFar+onesCount >= k {
return rankSoFar, int(wordIdx)
}
rankSoFar += onesCount
}
rank = -1
wordIdx = -1
return
}
func (self *RankSelectFast) IndexWithRank(rank int) (int, error) {
bitIdx := self.partialSelects[rank/64]
if bitIdx == uint32(self.n+1) {
return -1, errors.New("No element with thank rank.")
}
rankOfIdx := (rank / 64) * 64
if rankOfIdx == rank {
return int(bitIdx), nil
}
// find the word that has the 'rank'th 1-bit.
rankExcludingWordIdx, wordIdx := self.getWordIndexOfWordWithKthOneBit(rank)
if wordIdx == -1 {
return -1, errors.New("No element with that rank.")
}
bitOffset := selectInWord(self.packedArray[wordIdx], rank-rankExcludingWordIdx)
return wordIdx*64 + bitOffset, nil
}
// find the first bit in word with rank ones before it.
func selectInWord(word uint64, rank int) int {
rankCurr := int(0)
for i := uint(0); i < 64; i += 1 {
if rankCurr == rank {
return int(i)
}
bitVal := (word & (1 << i)) >> i
rankCurr += int(bitVal)
}
return 64
}
// helper method to build the lookup table used when answer select(i) queries.
// This function comptues the table select(i) for i = 64k, k = 0..n/64
func (self *RankSelectFast) computePartialSelects() {
allSelects := self.computeAllSelects()
self.partialSelects = make([]uint32, computePackedLength(self.n))
for i := 0; i < self.n; i += 64 {
self.partialSelects[i/64] = allSelects[i]
}
}
// helper method to build the lookup table used when answer select(i) queries.
// this function computes the table select(i) for 0 <= i <= n.
func (self *RankSelectFast) computeAllSelects() []uint32 {
result := make([]uint32, self.n+1)
result[0] = 0
next := int(1)
for i, _ := range self.packedArray {
for j := 0; j < 64; j += 1 {
bitValue := getBit(self.packedArray, i*64+j)
if bitValue == 1 {
result[next] = uint32(i*64 + j + 1)
next = next + 1
}
}
}
for i := next; i < self.n; i += 1 {
result[i] = uint32(self.n + 1)
}
return result
}
func (self *RankSelectFast) RankOfIndex(index int) uint {
if index >= self.n {
lastPartial := self.partialRanks[len(self.partialRanks)-1]
lastWord := self.packedArray[len(self.packedArray)-1]
return lastPartial + uint(bits.OnesCount64(lastWord))
}
partialRank := self.partialRanks[index/64]
if index%64 == 0 {
return partialRank
}
word := self.packedArray[index/64]
mask := uint64(1) << (uint(index % 64))
mask = mask - 1
return partialRank + uint(bits.OnesCount64(word&mask))
}
// helper method for building the lookup tables used when answering rank(i) queries.
func (self *RankSelectFast) computePartialRanks() {
self.partialRanks = make([]uint, computePackedLength(self.n))
sum := uint(0)
for i := 0; i < self.n; i += 1 {
if i%64 == 0 {
self.partialRanks[i/64] = sum
}
bitValue := getBit(self.packedArray, i)
sum += bitValue
}
}
// helper method for accessing individual bits in a 'packed array'
// index refers to the bit-index, i.e. the first word stores bits for indices 0-63.
func getBit(array []uint64, index int) uint {
wordIndex := index / 64
bitIndex := index % 64
word := array[wordIndex]
mask := uint64(1) << uint(bitIndex)
val := uint((word & mask) >> uint(bitIndex))
return val
}
// helper method for setting bits in a packed array.
// index refers to the bit-index, i.e. the first word stores bits for indices 0-63.
func setBit(array []uint64, index, value int) {
wordIndex := index / 64
bitIndex := index % 64
word := array[wordIndex]
mask := uint64(1) << uint(bitIndex)
if value == 0 {
mask = ^uint64(0) ^ mask
word = word & mask
} else {
word = word | mask
}
array[wordIndex] = word
}
// constructor for RankSelectFast.
// this function computes all the necessary tables, so the structure is ready for querying when this returns.
// array is not a packed array, i.e. every bit is in its own int.
func NewRankSelectFast(array []int) *RankSelectFast {
result := new(RankSelectFast)
packedArrayLength := computePackedLength(len(array))
packedArray := make([]uint64, packedArrayLength)
for index, bitValue := range array {
setBit(packedArray, index, bitValue)
}
result.packedArray = packedArray
result.n = len(array)
result.computePartialRanks()
result.computePartialSelects()
return result
}
func computePackedLength(n int) int {
if n == 0 {
return 0
}
return (n-1)/64 + 1
}
|
package main
import (
"fmt"
"math/rand"
"time"
log "github.com/sirupsen/logrus"
)
var Games = make(map[int]*Game, 0)
type Game struct {
Id int
Players *Players
EventsQueue *EventQueue
EventsHistory *EventHistory
Event IEvent
Iteration int
Winner int
}
func NewGame() *Game {
return &Game{
Id: rand.Intn(99),
Players: NewPlayers(),
EventsQueue: NewEventQueue(),
EventsHistory: NewEventHistory(),
Iteration: 1,
Event: NewGameEvent(),
}
}
func (game *Game) Run() {
go game.EventLoop()
}
func (game *Game) isOver() bool {
if game.Event.Name() == EVENT_GAME ||
game.Event.Name() == EVENT_GAME_START ||
game.Event.Name() == EVENT_GREET_CITIZENS ||
game.Event.Name() == EVENT_GREET_MAFIA {
return false
}
mafia := len(game.Players.FindByRole(ROLE_MAFIA))
citizens := len(game.Players.FindByRole(ROLE_CITIZEN))
sheriff := len(game.Players.FindByRole(ROLE_SHERIFF))
girl := len(game.Players.FindByRole(ROLE_GIRL))
doctor := len(game.Players.FindByRole(ROLE_DOCTOR))
if citizens+sheriff+girl+doctor == 0 {
game.Winner = ROLE_MAFIA
}
if mafia == 0 {
game.Winner = ROLE_CITIZEN
}
return game.Winner != 0
}
func (game *Game) SetNextEvent() error {
if game.EventsQueue.Len() == 0 {
game.initEventQueue()
}
event := game.EventsQueue.Pop()
if event != nil {
game.EventsHistory.Push(game.Event)
game.Event = event
return nil
}
return fmt.Errorf("Can not get next event")
}
func (game *Game) initEventQueue() error {
queue := game.EventsQueue
eventName := game.Event.Name()
for {
if game.isOver() {
queue.Push(NewGameOverEvent(game.Iteration, game.Winner))
return nil
}
switch eventName {
case EVENT_GAME:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GAME_START, ACTION_START))
return nil
case EVENT_GAME_START:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GREET_CITIZENS, ACTION_START))
queue.Push(NewGreetCitizensEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GREET_CITIZENS, ACTION_END))
return nil
case EVENT_GREET_CITIZENS:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_NIGHT, ACTION_START))
return nil
case EVENT_NIGHT:
if game.Iteration == 1 {
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GREET_MAFIA, ACTION_START))
queue.Push(NewGreetMafiaEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GREET_MAFIA, ACTION_END))
return nil
}
queue.Push(NewAcceptEvent(game.Iteration, EVENT_MAFIA, ACTION_START))
queue.Push(NewMafiaEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_MAFIA, ACTION_END))
return nil
case EVENT_GREET_MAFIA:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_DAY, ACTION_START))
return nil
case EVENT_MAFIA:
if game.Players.FindOneByRole(ROLE_DOCTOR) != nil {
queue.Push(NewAcceptEvent(game.Iteration, EVENT_DOCTOR, ACTION_START))
queue.Push(NewDoctorEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_DOCTOR, ACTION_END))
return nil
}
eventName = EVENT_DOCTOR
break
case EVENT_DOCTOR:
if game.Players.FindOneByRole(ROLE_SHERIFF) != nil {
queue.Push(NewAcceptEvent(game.Iteration, EVENT_SHERIFF, ACTION_START))
queue.Push(NewSheriffEvent(game.Iteration))
queue.Push(NewSheriffResultEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_SHERIFF, ACTION_END))
return nil
}
eventName = EVENT_SHERIFF
break
case EVENT_SHERIFF:
if game.Players.FindOneByRole(ROLE_GIRL) != nil {
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GIRL, ACTION_START))
queue.Push(NewGirlEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_GIRL, ACTION_END))
return nil
}
eventName = EVENT_GIRL
break
case EVENT_GIRL:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_DAY, ACTION_START))
return nil
case EVENT_DAY:
if game.Iteration != 1 {
queue.Push(NewNightResultEvent(game.Iteration))
return nil
}
eventName = EVENT_NIGHT_RESULT
break
case EVENT_NIGHT_RESULT:
queue.Push(NewAcceptEvent(game.Iteration, EVENT_COURT, ACTION_START))
queue.Push(NewCourtEvent(game.Iteration))
queue.Push(NewCourtResultEvent(game.Iteration))
queue.Push(NewAcceptEvent(game.Iteration, EVENT_COURT, ACTION_END))
return nil
case EVENT_COURT:
game.Iteration++
queue.Push(NewAcceptEvent(game.Iteration, EVENT_NIGHT, ACTION_START))
return nil
}
}
return nil
}
func (game *Game) EventLoop() {
ticker := time.NewTicker(1 * time.Millisecond)
for range ticker.C {
switch game.Event.Status() {
case NOT_IN_PROCESS:
err := game.Event.Process(game.Players, game.EventsHistory)
if err != nil {
log.Warningf("Event: %s, err: %v", game.Event.Name(), err)
}
break
case PROCESSED:
game.SetNextEvent()
break
}
}
}
|
package ethclient
import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
"github.com/sirupsen/logrus"
hdwallet "github.com/miguelmota/go-ethereum-hdwallet"
"github.com/Secured-Finance/dione/config"
"github.com/Secured-Finance/dione/contracts/dioneDispute"
"github.com/Secured-Finance/dione/contracts/dioneOracle"
"github.com/Secured-Finance/dione/contracts/dioneStaking"
stakingContract "github.com/Secured-Finance/dione/contracts/dioneStaking"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/event"
)
type ethereumClient struct {
client *ethclient.Client
ethAddress *common.Address
authTransactor *bind.TransactOpts
dioneStaking *stakingContract.DioneStakingSession
disputeContract *dioneDispute.DioneDisputeSession
dioneOracle *dioneOracle.DioneOracleSession
}
type EthereumSideAPI interface {
SubmitRequestAnswer(reqID *big.Int, data []byte) error
BeginDispute(miner common.Address, requestID *big.Int) error
VoteDispute(dhash [32]byte, voteStatus bool) error
FinishDispute(dhash [32]byte) error
SubscribeOnOracleEvents(ctx context.Context) (chan *dioneOracle.DioneOracleNewOracleRequest, event.Subscription, error)
SubscribeOnNewDisputes(ctx context.Context) (chan *dioneDispute.DioneDisputeNewDispute, event.Subscription, error)
SubscribeOnNewSubmissions(ctx context.Context) (chan *dioneOracle.DioneOracleSubmittedOracleRequest, event.Subscription, error)
GetEthAddress() *common.Address
GetTotalStake() (*big.Int, error)
GetMinerStake(minerAddress common.Address) (*big.Int, error)
}
func NewEthereumClient(cfg *config.Config) (EthereumSideAPI, error) {
c := ðereumClient{}
client, err := ethclient.Dial(cfg.Ethereum.GatewayAddress)
if err != nil {
return nil, err
}
c.client = client
key, err := c.getPrivateKey(cfg)
if err != nil {
return nil, err
}
authTransactor, err := bind.NewKeyedTransactorWithChainID(key, big.NewInt(int64(cfg.Ethereum.ChainID)))
if err != nil {
return nil, err
}
c.authTransactor = authTransactor
c.ethAddress = &c.authTransactor.From
stakingContract, err := dioneStaking.NewDioneStaking(common.HexToAddress(cfg.Ethereum.DioneStakingContractAddress), client)
if err != nil {
return nil, err
}
oracleContract, err := dioneOracle.NewDioneOracle(common.HexToAddress(cfg.Ethereum.DioneOracleContractAddress), client)
if err != nil {
return nil, err
}
disputeContract, err := dioneDispute.NewDioneDispute(common.HexToAddress(cfg.Ethereum.DisputeContractAddress), client)
if err != nil {
return nil, err
}
c.dioneStaking = &dioneStaking.DioneStakingSession{
Contract: stakingContract,
CallOpts: bind.CallOpts{
Pending: true,
From: authTransactor.From,
Context: context.Background(),
},
TransactOpts: bind.TransactOpts{
From: authTransactor.From,
Signer: authTransactor.Signer,
GasLimit: 0, // 0 automatically estimates gas limit
GasPrice: nil, // nil automatically suggests gas price
Context: context.Background(),
},
}
c.disputeContract = &dioneDispute.DioneDisputeSession{
Contract: disputeContract,
CallOpts: bind.CallOpts{
Pending: true,
From: authTransactor.From,
Context: context.Background(),
},
TransactOpts: bind.TransactOpts{
From: authTransactor.From,
Signer: authTransactor.Signer,
GasLimit: 0, // 0 automatically estimates gas limit
GasPrice: nil, // nil automatically suggests gas price
Context: context.Background(),
},
}
c.dioneOracle = &dioneOracle.DioneOracleSession{
Contract: oracleContract,
CallOpts: bind.CallOpts{
Pending: true,
From: authTransactor.From,
Context: context.Background(),
},
TransactOpts: bind.TransactOpts{
From: authTransactor.From,
Signer: authTransactor.Signer,
GasLimit: 0, // 0 automatically estimates gas limit
GasPrice: nil, // nil automatically suggests gas price
Context: context.Background(),
},
}
logrus.WithField("ethAddress", c.GetEthAddress().Hex()).Info("Ethereum client has been initialized!")
return c, nil
}
func (c *ethereumClient) getPrivateKey(cfg *config.Config) (*ecdsa.PrivateKey, error) {
if cfg.Ethereum.PrivateKey != "" {
key, err := crypto.HexToECDSA(cfg.Ethereum.PrivateKey)
return key, err
}
if cfg.Ethereum.MnemonicPhrase != "" {
wallet, err := hdwallet.NewFromMnemonic(cfg.Ethereum.MnemonicPhrase)
if err != nil {
return nil, err
}
path := hdwallet.DefaultBaseDerivationPath
if cfg.Ethereum.HDDerivationPath != "" {
parsedPath, err := hdwallet.ParseDerivationPath(cfg.Ethereum.HDDerivationPath)
if err != nil {
return nil, err
}
path = parsedPath
}
account, err := wallet.Derive(path, true)
if err != nil {
return nil, err
}
key, err := wallet.PrivateKey(account)
if err != nil {
return nil, err
}
return key, nil
}
return nil, fmt.Errorf("private key or mnemonic phrase isn't specified")
}
func (c *ethereumClient) GetEthAddress() *common.Address {
return c.ethAddress
}
func (c *ethereumClient) SubscribeOnOracleEvents(ctx context.Context) (chan *dioneOracle.DioneOracleNewOracleRequest, event.Subscription, error) {
resChan := make(chan *dioneOracle.DioneOracleNewOracleRequest)
requestsFilter := c.dioneOracle.Contract.DioneOracleFilterer
subscription, err := requestsFilter.WatchNewOracleRequest(&bind.WatchOpts{
Start: nil, //last block
Context: ctx,
}, resChan)
if err != nil {
return nil, nil, err
}
return resChan, subscription, err
}
func (c *ethereumClient) SubmitRequestAnswer(reqID *big.Int, data []byte) error {
_, err := c.dioneOracle.SubmitOracleRequest(reqID, data)
if err != nil {
return err
}
return nil
}
func (c *ethereumClient) BeginDispute(miner common.Address, requestID *big.Int) error {
_, err := c.disputeContract.BeginDispute(miner, requestID)
if err != nil {
return err
}
return nil
}
func (c *ethereumClient) VoteDispute(dhash [32]byte, voteStatus bool) error {
_, err := c.disputeContract.Vote(dhash, voteStatus)
if err != nil {
return err
}
return nil
}
func (c *ethereumClient) FinishDispute(dhash [32]byte) error {
_, err := c.disputeContract.FinishDispute(dhash)
if err != nil {
return err
}
return nil
}
func (c *ethereumClient) SubscribeOnNewDisputes(ctx context.Context) (chan *dioneDispute.DioneDisputeNewDispute, event.Subscription, error) {
resChan := make(chan *dioneDispute.DioneDisputeNewDispute)
requestsFilter := c.disputeContract.Contract.DioneDisputeFilterer
subscription, err := requestsFilter.WatchNewDispute(&bind.WatchOpts{
Start: nil, //last block
Context: ctx,
}, resChan, nil, nil)
if err != nil {
return nil, nil, err
}
return resChan, subscription, err
}
func (c *ethereumClient) SubscribeOnNewSubmissions(ctx context.Context) (chan *dioneOracle.DioneOracleSubmittedOracleRequest, event.Subscription, error) {
resChan := make(chan *dioneOracle.DioneOracleSubmittedOracleRequest)
requestsFilter := c.dioneOracle.Contract.DioneOracleFilterer
subscription, err := requestsFilter.WatchSubmittedOracleRequest(&bind.WatchOpts{
Start: nil, // last block
Context: ctx,
}, resChan)
if err != nil {
return nil, nil, err
}
return resChan, subscription, err
}
|
package template
import (
"github.com/spf13/cobra"
)
func NewTemplateCommand() *cobra.Command {
var command = &cobra.Command{
Use: "template",
Short: "manipulate workflow templates",
Run: func(cmd *cobra.Command, args []string) {
cmd.HelpFunc()(cmd, args)
},
}
command.AddCommand(NewGetCommand())
command.AddCommand(NewListCommand())
command.AddCommand(NewCreateCommand())
command.AddCommand(NewDeleteCommand())
command.AddCommand(NewLintCommand())
return command
}
|
package plugins
import (
"time"
"github.com/afex/hystrix-go/hystrix/metric_collector"
"github.com/prometheus/client_golang/prometheus"
)
var promAttempts = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_attempts_total",
Help: "Hytrix attemps",
},
[]string{"circuit_name"},
)
var promErrors = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_error_total",
Help: "Hytrix errors",
},
[]string{"circuit_name"},
)
var promFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_failure_total",
Help: "Hytrix failures",
},
[]string{"circuit_name"},
)
var promRejects = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_rejects_total",
Help: "Hytrix rejects",
},
[]string{"circuit_name"},
)
var promShortCircuits = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_short_circuits_total",
Help: "Hytrix short circuits",
},
[]string{"circuit_name"},
)
var promTimeouts = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_timeouts_total",
Help: "Hytrix timeouts",
},
[]string{"circuit_name"},
)
var promFallbackSuccesses = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_fallback_success_total",
Help: "Hytrix fallback successes",
},
[]string{"circuit_name"},
)
var promFallbackFailures = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_fallback_failures_total",
Help: "Hytrix fallback failures",
},
[]string{"circuit_name"},
)
var promSuccesses = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_success_total",
Help: "Hytrix success",
},
[]string{"circuit_name"},
)
var promTotalDuration = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "hystrix_total_duration_seconds",
Help: "Hystric total duration",
},
[]string{"circuit_name"},
)
var promRunDuration = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "hystrix_run_duration_seconds",
Help: "Hystric run duration",
},
[]string{"circuit_name"},
)
type PrometheusCollector struct {
circuitName string
}
func NewPrometheusCollector() func(string) metricCollector.MetricCollector {
prometheus.MustRegister(
promAttempts, promErrors, promFailures,
promRejects, promShortCircuits, promTimeouts,
promFallbackSuccesses, promFallbackFailures,
promSuccesses, promTotalDuration, promRunDuration,
)
return func(name string) metricCollector.MetricCollector {
return &PrometheusCollector{
circuitName: name,
}
}
}
// IncrementAttempts increments the number of calls to this circuit.
func (c *PrometheusCollector) IncrementAttempts() {
promAttempts.WithLabelValues(c.circuitName).Inc()
}
// IncrementErrors increments the number of unsuccessful attempts.
// Attempts minus Errors will equal successes within a time range.
// Errors are any result from an attempt that is not a success.
func (c *PrometheusCollector) IncrementErrors() {
promErrors.WithLabelValues(c.circuitName).Inc()
}
// IncrementSuccesses increments the number of requests that succeed.
func (c *PrometheusCollector) IncrementSuccesses() {
promSuccesses.WithLabelValues(c.circuitName).Inc()
}
// IncrementFailures increments the number of requests that fail.
func (c *PrometheusCollector) IncrementFailures() {
promFailures.WithLabelValues(c.circuitName).Inc()
}
// IncrementRejects increments the number of requests that are rejected.
func (c *PrometheusCollector) IncrementRejects() {
promRejects.WithLabelValues(c.circuitName).Inc()
}
// IncrementShortCircuits increments the number of requests that short circuited
// due to the circuit being open.
func (c *PrometheusCollector) IncrementShortCircuits() {
promShortCircuits.WithLabelValues(c.circuitName).Inc()
}
// IncrementTimeouts increments the number of timeouts that occurred in the
// circuit breaker.
func (c *PrometheusCollector) IncrementTimeouts() {
promTimeouts.WithLabelValues(c.circuitName).Inc()
}
// IncrementFallbackSuccesses increments the number of successes that occurred
// during the execution of the fallback function.
func (c *PrometheusCollector) IncrementFallbackSuccesses() {
promFallbackSuccesses.WithLabelValues(c.circuitName).Inc()
}
// IncrementFallbackFailures increments the number of failures that occurred
// during the execution of the fallback function.
func (c *PrometheusCollector) IncrementFallbackFailures() {
promFallbackFailures.WithLabelValues(c.circuitName).Inc()
}
// UpdateTotalDuration updates the internal counter of how long we've run for.
func (c *PrometheusCollector) UpdateTotalDuration(timeSinceStart time.Duration) {
promTotalDuration.WithLabelValues(c.circuitName).Set(timeSinceStart.Seconds())
}
// UpdateRunDuration updates the internal counter of how long the last run took.
func (c *PrometheusCollector) UpdateRunDuration(runDuration time.Duration) {
promRunDuration.WithLabelValues(c.circuitName).Add(runDuration.Seconds())
}
// Reset is a noop operation in this collector.
func (c *PrometheusCollector) Reset() {}
|
package main
import "fmt"
func main() {
// map deve ser inicializado !!!
mapAprovados := make(map[int]string) //map[key]value
mapAprovados[123] = "Maria"
mapAprovados[456] = "Pedro"
fmt.Println(mapAprovados)
fmt.Println("")
for cpf, nome := range mapAprovados {
fmt.Printf("nome: %s , cpf: %d \n", nome, cpf)
}
fmt.Println(mapAprovados[123])
//Maria
delete(mapAprovados, 123)
for cpf, nome := range mapAprovados {
fmt.Printf("nome: %s , cpf: %d \n", nome, cpf)
}
}
|
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"gorm_project/modules"
)
func main() {
connStr := "root:Kaka@2019@/gorm_project?charset=utf8&parseTime=True&loc=Local"
db, err := gorm.Open("mysql", connStr)
if err != nil {
panic(err)
}
defer db.Close()
// 增
//db.Create(&modules.User{Id: 1, Name: "张三", Age: 18, Address: "xxx", Pic: "/static/upload/pic11.jpg", Phone: "11111111111"})
// 查
var user modules.User
db.First(&user, 1)
fmt.Println(user)
db.First(&user, "name=?", "张三").Update("phone", "1234567890")
fmt.Println(user)
// 改
db.Model(&user).Update("age", 20).Update("address", "yyy-zs")
//db.Model(&user).Update("address", "xxx-zs")
// 删除
db.First(&user, 1).Delete(&user)
//db.Delete(&user)
}
|
package kubectl
import (
"fmt"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest"
"github.com/devspace-cloud/devspace/pkg/util/log"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"os/exec"
"regexp"
"strings"
)
// Builder is the manifest builder interface
type Builder interface {
Build(manifest string, executor RunCommand) ([]*unstructured.Unstructured, error)
}
type RunCommand func(path string, args []string) ([]byte, error)
type kustomizeBuilder struct {
path string
config *latest.DeploymentConfig
log log.Logger
}
func NewKustomizeBuilder(path string, config *latest.DeploymentConfig, log log.Logger) Builder {
return &kustomizeBuilder{
path: path,
config: config,
log: log,
}
}
func (k *kustomizeBuilder) Build(manifest string, cmd RunCommand) ([]*unstructured.Unstructured, error) {
args := []string{"build", manifest}
args = append(args, k.config.Kubectl.KustomizeArgs...)
// Execute command
k.log.Infof("Render manifests with 'kustomize %s'", strings.Join(args, " "))
output, err := cmd(k.path, args)
if err != nil {
exitError, ok := err.(*exec.ExitError)
if ok {
return nil, errors.New(string(exitError.Stderr))
}
return nil, err
}
return stringToUnstructuredArray(string(output))
}
type kubectlBuilder struct {
path string
config *latest.DeploymentConfig
context string
namespace string
}
// NewKubectlBuilder creates a new kubectl manifest builder
func NewKubectlBuilder(path string, config *latest.DeploymentConfig, context, namespace string) Builder {
return &kubectlBuilder{
path: path,
config: config,
context: context,
namespace: namespace,
}
}
func (k *kubectlBuilder) Build(manifest string, cmd RunCommand) ([]*unstructured.Unstructured, error) {
args := []string{"create"}
if k.context != "" {
args = append(args, "--context", k.context)
}
if k.namespace != "" {
args = append(args, "--namespace", k.namespace)
}
args = append(args, "--dry-run", "--output", "yaml", "--validate=false")
if k.config.Kubectl.Kustomize != nil && *k.config.Kubectl.Kustomize == true {
args = append(args, "--kustomize", manifest)
} else {
args = append(args, "--filename", manifest)
}
// Add extra args
args = append(args, k.config.Kubectl.CreateArgs...)
// Execute command
output, err := cmd(k.path, args)
if err != nil {
exitError, ok := err.(*exec.ExitError)
if ok {
return nil, errors.New(string(exitError.Stderr))
}
return nil, err
}
return stringToUnstructuredArray(prepareResources(string(output)))
}
var diffSeparator = regexp.MustCompile(`\n---`)
var oldDiffSeparator = regexp.MustCompile(`\napiVersion`)
func prepareResources(out string) string {
parts := diffSeparator.Split(out, -1)
for i, part := range parts {
oldParts := oldDiffSeparator.Split(part, -1)
if len(oldParts) > 1 {
parts[i] = strings.Join(oldParts, "\n---\napiVersion")
}
}
return strings.Join(parts, "\n---")
}
// stringToUnstructuredArray splits a YAML file into unstructured objects. Returns a list of all unstructured objects
func stringToUnstructuredArray(out string) ([]*unstructured.Unstructured, error) {
parts := diffSeparator.Split(out, -1)
var objs []*unstructured.Unstructured
var firstErr error
for _, part := range parts {
var objMap map[string]interface{}
err := yaml.Unmarshal([]byte(part), &objMap)
if err != nil {
if firstErr == nil {
firstErr = fmt.Errorf("failed to unmarshal manifest: %v", err)
}
continue
}
if len(objMap) == 0 {
// handles case where theres no content between `---`
continue
}
var obj unstructured.Unstructured
err = yaml.Unmarshal([]byte(part), &obj)
if err != nil {
if firstErr == nil {
firstErr = fmt.Errorf("failed to unmarshal manifest: %v", err)
}
continue
}
objs = append(objs, &obj)
}
return objs, firstErr
}
|
package dictionary
import "errors"
// Dictionary Type
type Dictionary map[string]string
var errNotFound = errors.New("Not found")
var errWordExist = errors.New("That word already exists")
var errWordCantUpdate = errors.New("That word cannot be updated")
var errWordCantDelete = errors.New("That word does not exist")
func (d Dictionary) Search(word string) (string, error) {
value, exists := d[word]
if exists {
return value, nil
}
return "", errNotFound
}
// Add a word to the dictionary
func (d Dictionary) Add(word, def string) error {
_, err := d.Search(word)
switch err {
case errNotFound:
d[word] = def
case nil:
return errWordExist
}
return nil
}
func (d Dictionary) Update(word, def string) error {
_, err := d.Search(word)
switch err {
case errNotFound:
return errWordCantUpdate
case nil:
d[word] = def
}
return nil
}
func (d Dictionary) Delete(word string) error {
_, err := d.Search(word)
switch err {
case errNotFound:
return errWordCantDelete
case nil:
delete(d, word)
}
return nil
} |
package main
import (
"fmt"
"math/rand"
"time"
)
const FILEPATH = "inputs/2"
const CHECK = 19690720
func part1() int {
n, _ := LoadIntoMemory(FILEPATH)
// restore 1202 program alarm
n[1] = 12
n[2] = 2
return RunIntcode(n, false)
}
func part2() int {
var noun int
var verb int
rand.Seed(time.Now().Unix())
for true {
noun = rand.Intn(99)
verb = rand.Intn(99)
ints, _ := LoadIntoMemory(FILEPATH)
ints[1] = noun
ints[2] = verb
ret := RunIntcode(ints, false)
if ret == CHECK {
return 100*noun + verb
break
}
}
return -1
}
func main() {
fmt.Println("part 1:", part1())
fmt.Println("part 2:", part2())
}
|
package main
import (
"log"
"net"
"github.com/jeckbjy/nio"
)
func StartClient() {
log.Printf("start client")
selector, err := nio.New()
if err != nil {
panic(err)
}
conn, err := net.Dial("tcp", "localhost:6789")
if err != nil {
panic(err)
}
selector.Add(conn, nio.OP_READ, nil)
conn.Write([]byte("ping"))
for {
log.Printf("wait\n")
keys, err := selector.Select()
if err != nil {
break
}
for _, key := range keys {
switch {
case key.Readable():
bytes := make([]byte, 1024)
n, err := key.Read(bytes)
if err != nil {
log.Printf("read: fd=%+v, err=%+v\n", key.Fd(), err)
//continue
} else {
log.Printf("%s:%+v\n", bytes[:n], key.Fd())
}
_, err = key.Write([]byte("ping"))
if err != nil {
log.Printf("write: fd=%+v, err=%+v\n", key.Fd(), err)
}
}
}
}
}
|
package singleton
import "testing"
func TestGetInstance(t *testing.T) {
firstInstance := GetInstance()
if firstInstance.NumberOfCreations() != 1 {
t.Error("expected just one number of creations")
}
secondInstance := GetInstance()
if firstInstance != secondInstance {
t.Error("expected same instance")
}
thirdInstance := GetInstance()
if thirdInstance.NumberOfCalls() != 3 {
t.Error("expected three calls")
}
if firstInstance.NumberOfCreations() != 1 {
t.Error("expected just one number of creations")
}
}
|
package cmd
import (
"fmt"
"github.com/twatzl/webdav-downloader/downloader"
"log"
"os"
"strings"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var server string
var deltaFlags = map[string]string{
downloader.DELTA_FLAG_SIZE: "copy file if size is different",
downloader.DELTA_FLAG_DATE: "copy file if last modified date is different",
}
var rootCmd = &cobra.Command{
Use: "webdav-downloader",
Short: "webdav-downloader is a small utility for downloading directories from webdav servers (i.e. Nextcloud)",
Long: `TODO`,
Run: func(cmd *cobra.Command, args []string) {
remoteDir := viper.GetString("remoteDir")
cfg := downloader.Config{
Protocol: viper.GetString("protocol"),
Host: viper.GetString("host"),
BaseDir: viper.GetString("baseDir"),
LocalDir: viper.GetString("localDir"),
User: viper.GetString("user"),
Pass: viper.GetString("pass"),
DeltaMode: viper.GetBool("delta"),
InteraciveMode: false, // TODO: coming soon
}
parseDeltaFlags(viper.GetString("df"), &cfg)
if cfg.Host == "" {
log.Fatal("host is required")
}
if cfg.Protocol != "http" && cfg.Protocol != "https" {
log.Fatal("protocol must be http or https")
}
downloader.DownloadDir(&cfg, remoteDir)
},
}
func parseDeltaFlags(flags string, config *downloader.Config) {
config.DeltaFlags = map[string]bool{}
flagValues := strings.Split(flags, ",")
for _, f := range flagValues {
if f != "" {
config.DeltaFlags[f] = true
}
}
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
const PROTOCOL = "protocol"
const HOST = "host"
const BASE_DIR = "baseDir"
const REMOTE_DIR = "remoteDir"
const LOCAL_DIR = "localDir"
const DELTA = "delta"
const DELTA_FLAGS = "df"
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.webdav-downloader.yaml)")
rootCmd.PersistentFlags().StringP(PROTOCOL, "", "http", "protocol to use")
rootCmd.PersistentFlags().StringP(HOST, "", "", "webdav host")
rootCmd.PersistentFlags().StringP(BASE_DIR, "", "", "base dir (e.g. /remote.php/webdav)")
rootCmd.PersistentFlags().StringP(REMOTE_DIR, "", "", "path which will be appended to the remote path (e.g. /some/dir)")
rootCmd.PersistentFlags().StringP(LOCAL_DIR, "", "", "path which will be used on the local machine (e.g. /some/other/dir)")
rootCmd.PersistentFlags().BoolP(DELTA, "", false, fmt.Sprintf("use delta mode. downloads only files which do not exist. criteria can be set using %s", DELTA_FLAGS))
rootCmd.PersistentFlags().StringP(DELTA_FLAGS, "", "", fmt.Sprintf("delta mode flags. determine what criteria is used for downloading.\navailable flags:\n%s", getDeltaFlagsString()))
_ = viper.BindPFlag(PROTOCOL, rootCmd.PersistentFlags().Lookup(PROTOCOL))
_ = viper.BindPFlag(HOST, rootCmd.PersistentFlags().Lookup(HOST))
_ = viper.BindPFlag(BASE_DIR, rootCmd.PersistentFlags().Lookup(BASE_DIR))
_ = viper.BindPFlag(REMOTE_DIR, rootCmd.PersistentFlags().Lookup(REMOTE_DIR))
_ = viper.BindPFlag(LOCAL_DIR, rootCmd.PersistentFlags().Lookup(LOCAL_DIR))
_ = viper.BindPFlag(DELTA, rootCmd.PersistentFlags().Lookup(DELTA))
_ = viper.BindPFlag(DELTA_FLAGS, rootCmd.PersistentFlags().Lookup(DELTA_FLAGS))
}
func initConfig() {
// Don't forget to read config either from cfgFile or from home directory!
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".webdav-downloader" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".webdav-downloader")
}
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Can't read config:", err)
//os.Exit(1)
}
}
func getDeltaFlagsString() string {
var descriptions []string
for key, desc := range deltaFlags {
descriptions = append(descriptions, fmt.Sprintf("%s: %s", key, desc))
}
return strings.Join(descriptions, "\n")
}
|
package assert
import (
"fmt"
"strings"
)
//go:generate go run type_assert.gen.go
type Assertion struct {
Message string
KVs map[string]interface{}
}
func (a Assertion) String() string {
sb := strings.Builder{}
sb.WriteString(a.Message)
for k, v := range a.KVs {
sb.WriteString("\n\t* ")
sb.WriteString(k)
sb.WriteByte('=')
sb.WriteString(fmt.Sprintf("%v", v))
}
return sb.String()
}
func Assert(assert bool, message string, kvs map[string]interface{}, opts ...ViolationOpt) {
if assert {
return
}
violation := Violation{
Position: lineNumFmt(lineNum(1, false)),
Assertion: Assertion{
Message: message,
KVs: kvs,
},
}
for _, opt := range opts {
if opt == nil {
continue
}
opt(&violation)
}
panic(violation)
}
func Catch(handlers ...func(Violation)) {
if p := recover(); p != nil {
if violation, ok := p.(Violation); ok {
for _, handler := range handlers {
if handler == nil {
continue
}
handler(violation)
}
return
}
panic(p)
}
}
|
package filter
import (
"gocherry-api-gateway/components/log_client"
"gocherry-api-gateway/proxy/enum"
"math/rand"
"time"
)
/**
记录日志id和记录时间
*/
type TraceFilter struct {
Filter
}
func (f *TraceFilter) Init(proxyContext *ProxyContext) {
}
func (f *TraceFilter) Name(proxyContext *ProxyContext) string {
return TraceF
}
//设置trace_id相关 放到header传到下游
func (f *TraceFilter) Pre(proxyContext *ProxyContext) (statusCode int, err string) {
nowTime := time.Now().Unix()
//trace_id 应该需要记录手机号或者用户id 好排查问题
proxyContext.TraceId = int64(rand.Intn(500)) + nowTime + 2 + int64(rand.Intn(1000))
return enum.STATUS_CODE_OK, ""
}
func (f *TraceFilter) AfterDo(proxyContext *ProxyContext) (statusCode int, err string) {
proxyContext.EndTime = time.Now().Unix()
log_client.LogInfo(proxyContext.RequestContext, map[string]interface{}{
"start_time": proxyContext.StartTime,
"end_time": proxyContext.EndTime,
"log_time": time.Now().Unix() - proxyContext.StartTime,
"trace_id": proxyContext.TraceId,
"url": proxyContext.Url.Path,
"app_name": proxyContext.AppName,
})
return enum.STATUS_CODE_OK, ""
}
|
package config
import (
"github.com/robfig/config"
)
type Reader struct {
config *config.Config
}
// filepath E.g. ""/etc/someconfig.cfg"
func NewReader(filepath string) (reader *Reader, err error) {
config, err := config.ReadDefault(filepath)
if err != nil {
return nil, err
}
return &Reader{config: config}, nil
}
func (reader *Reader) Bool(section string, option string) (value bool, err error) {
return reader.config.Bool(section, option)
}
/*
Return default value if config option no found.
*/
func (reader *Reader) BoolDefault(section string, option string, def bool) (value bool) {
value, err := reader.Bool(section, option)
if err != nil {
return def
}
return value
}
func (reader *Reader) Int(section string, option string) (value int, err error) {
return reader.config.Int(section, option)
}
/*
Return default value if config option no found.
*/
func (reader *Reader) IntDefault(section string, option string, def int) (value int) {
value, err := reader.Int(section, option)
if err != nil {
return def
}
return value
}
func (reader *Reader) String(section string, option string) (value string, err error) {
return reader.config.String(section, option)
}
/*
Return default value if config option no found.
*/
func (reader *Reader) StringDefault(section string, option string, def string) (value string) {
value, err := reader.String(section, option)
if err != nil {
return def
}
return value
}
func (reader *Reader) Float(section string, option string) (value float64, err error) {
return reader.config.Float(section, option)
}
/*
Return default value if config option no found.
*/
func (reader *Reader) FloatDefault(section string, option string, def float64) (value float64) {
value, err := reader.Float(section, option)
if err != nil {
return def
}
return value
}
|
package core
import (
"testing"
)
func Test_NewBoolean(t *testing.T) {
values := []bool{false, true}
for _, value := range values {
node := NewBoolean(value)
if !node.CompareBoolean(value) {
t.Error("NewBoolean() failed.")
}
}
}
func Test_IsBoolean(t *testing.T) {
node := &Type{}
if node.IsBoolean() {
t.Error("IsBoolean() failed: wrong return value.")
}
values := []bool{false, true}
for _, value := range values {
node := &Type{Boolean: &value}
if !node.IsBoolean() {
t.Error("IsBoolean() failed: wrong return value.")
}
}
}
func Test_AsBoolean(t *testing.T) {
node := NewBoolean(false)
if node.AsBoolean() != false {
t.Error("AsBoolean() failed: wrong return value.")
}
node = NewBoolean(true)
if node.AsBoolean() != true {
t.Error("AsBoolean() failed: wrong return value.")
}
node = &Type{}
if node.AsBoolean() != false {
t.Error("AsBoolean() failed: wrong return value.")
}
}
func Test_CompareBoolean(t *testing.T) {
values := []bool{false, true}
for _, value := range values {
node := &Type{Boolean: &value}
if !node.CompareBoolean(value) {
t.Error("CompareBoolean() failed: wrong return value.")
}
}
node := &Type{}
if node.CompareBoolean(false) || node.CompareBoolean(true) {
t.Error("CompareBoolean() failed: wrong return value.")
}
}
|
package main
import "fmt"
func main(){
msg:= make(chan int, 4)
msg <- 100
msg <- 110
msg <- 120
msg <- 130
p := fmt.Println
p(<-msg)
p(<-msg)
p(<-msg)
p(<-msg)
}
|
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/pwang347/cs304/server/common"
"github.com/pwang347/cs304/server/queries"
)
const (
// DefaultServerPort represents the default port number for server
DefaultServerPort = 4000
// ErrorNotFound represents the error for URL not found
ErrorNotFound = "not-found"
)
var (
db *sql.DB
accessGroupQueries = map[string]query{
"create": queries.CreateAccessGroup,
"delete": queries.DeleteAccessGroup,
"addUser": queries.AddUserToAccessGroup,
"removeUser": queries.RemoveUserFromAccessGroup,
"listOrganization": queries.QueryAccessGroupOrganization,
"listUsersForOrganization": queries.QueryAccessGroupUserPairsOrganization,
}
baseImageQueries = map[string]query{
"list": queries.QueryAllBaseImages,
}
creditCardQueries = map[string]query{
"create": queries.CreateCreditCard,
"delete": queries.DeleteCreditCard,
"addToOrganization": queries.AddCreditCardToOrganization,
"removeFromOrganization": queries.RemoveCreditCardFromOrganization,
"listCreditCards": queries.ListAllCreditCards,
}
metricsQueries = map[string]query{
"organizationsServed": queries.QueryNumberOfOrganizationsForService,
"countInstances": queries.QueryNumberOfInstancesPerRegion,
"countVirtualMachines": queries.QueryNumberOfVirtualMachinesPerRegion,
"purchasesWeekly": queries.QueryWeeklyPurchasesForService,
}
organizationQueries = map[string]query{
"create": queries.CreateOrganization,
"delete": queries.DeleteOrganization,
"addUser": queries.AddUserToOrganization,
"removeUser": queries.RemoveUserFromOrganization,
"listUser": queries.QueryUserOrganizations,
"listUsersInOrganization": queries.QueryOrganizationUsers,
"listUserNotInOrganization": queries.QueryUserNotInOrganization,
"listUsersInOrganizationNotInGroup": queries.QueryOrganizationUsersNotInGroup,
"updateAdmin": queries.UpdateUserOrganizationPairs,
}
regionQueries = map[string]query{
"list": queries.QueryAllRegions,
}
serviceQueries = map[string]query{
"list": queries.QueryAllServices,
"listSubscriptions": queries.GetServiceSubscriptions,
"listServiceTypes": queries.GetServiceTypes,
"listWithAllTypes": queries.GetAllServicesWithAllTypes,
}
serviceInstanceQueries = map[string]query{
"create": queries.CreateServiceInstance,
"delete": queries.DeleteServiceInstance,
"listServiceOrganization": queries.QueryServiceInstanceOrganization,
}
serviceInstanceConfigurationQueries = map[string]query{
"create": queries.CreateServiceInstanceConfiguration,
"delete": queries.DeleteServiceInstanceConfiguration,
"update": queries.UpdateServiceInstanceConfiguration,
"listForServiceInstance": queries.QueryServiceInstanceConfigurations,
}
serviceInstanceKeyQueries = map[string]query{
"create": queries.CreateServiceInstanceKey,
"delete": queries.DeleteServiceInstanceKey,
"update": queries.UpdateServiceInstanceKey,
"listForServiceInstance": queries.QueryServiceInstanceKeys,
}
serviceSubscriptionQueries = map[string]query{
"create": queries.CreateServiceSubscriptionTransaction,
"delete": queries.DeleteServiceSubscriptionTransactionByTransaction,
"listActiveSubscriptions": queries.ListAllActiveServiceSubscriptionTransactions,
"listTransactions": queries.ListAllCompletedTransactions,
"listCurrentMonthTransactions": queries.GetTransactionsForCurrentMonth,
"listExpiredSubscriptions": queries.GetExpiredServiceSubscriptions,
}
virtualMachineQueries = map[string]query{
"create": queries.CreateVirtualMachine,
"delete": queries.DeleteVirtualMachine,
"listOrganization": queries.QueryVirtualMachineOrganization,
"listServiceOrganization": queries.QueryVirtualMachineServiceOrganization,
"update": queries.UpdateVirtualMachine,
"updateState": queries.UpdateVirtualMachineState,
}
userQueries = map[string]query{
"create": queries.CreateUser,
"delete": queries.DeleteUser,
"isAdmin": queries.UserIsAdminForOrganization,
"select": queries.SelectUser,
"update": queries.UpdateUser,
"login": queries.UserLogin,
}
eventLogQueries = map[string]query{
"byVirtualMachine": queries.QueryEventLogsForVirtualMachine,
}
virtualMachineAccessGroupPermissionQueries = map[string]query{
"create": queries.CreateVirtualMachineAccessGroupPermission,
"delete": queries.DeleteVirtualMachineAccessGroupPermission,
"byVirtualMachine": queries.QueryVirtualMachineAccessGroupPermissions,
}
)
type (
query func(db *sql.DB, params url.Values) ([]byte, error)
errorResponse struct {
Error string `json:"error"`
}
)
func mapJSONEndpoints(queries map[string]query) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
vars := mux.Vars(r)
if cmd, ok := queries[vars["query"]]; ok {
var (
data []byte
err error
)
w.Header().Set("Content-Type", "application/json")
data, err = cmd(db, r.URL.Query())
if err != nil {
if err.Error() == ErrorNotFound {
http.NotFound(w, r)
return
}
data, _ = json.Marshal(errorResponse{Error: err.Error()})
w.WriteHeader(http.StatusInternalServerError)
w.Write(data)
return
}
w.WriteHeader(http.StatusOK)
w.Write(data)
return
}
http.NotFound(w, r)
}
}
func main() {
var (
port = flag.Int("port", DefaultServerPort, "webserver port")
mysqlUser = flag.String("user", common.DefaultMySQLUser, "mysql user")
mysqlPassword = flag.String("password", common.DefaultMySQLPassword, "mysql password")
mysqlHost = flag.String("mysqlHost", common.DefaultMySQLHost, "mysql host")
mysqlPort = flag.Int("mysqlPort", common.DefaultMySQLPort, "mysql port")
mysqlDbName = flag.String("dbName", common.DefaultMySQLDbName, "mysql database name")
err error
)
flag.Parse()
if len(*mysqlPassword) > 0 {
*mysqlPassword = ":" + *mysqlPassword
}
mySQLConnectionString := fmt.Sprintf(
"%s%s@tcp(%s:%d)/%s",
*mysqlUser,
*mysqlPassword,
*mysqlHost,
*mysqlPort,
*mysqlDbName)
if db, err = sql.Open("mysql", mySQLConnectionString); err != nil {
panic(err)
}
defer db.Close()
r := mux.NewRouter()
r.HandleFunc("/api/accessGroup/{query}", mapJSONEndpoints(accessGroupQueries))
r.HandleFunc("/api/baseImage/{query}", mapJSONEndpoints(baseImageQueries))
r.HandleFunc("/api/creditCard/{query}", mapJSONEndpoints(creditCardQueries))
r.HandleFunc("/api/metrics/{query}", mapJSONEndpoints(metricsQueries))
r.HandleFunc("/api/organization/{query}", mapJSONEndpoints(organizationQueries))
r.HandleFunc("/api/region/{query}", mapJSONEndpoints(regionQueries))
r.HandleFunc("/api/service/{query}", mapJSONEndpoints(serviceQueries))
r.HandleFunc("/api/serviceInstance/{query}", mapJSONEndpoints(serviceInstanceQueries))
r.HandleFunc("/api/serviceInstanceConfiguration/{query}", mapJSONEndpoints(serviceInstanceConfigurationQueries))
r.HandleFunc("/api/serviceInstanceKey/{query}", mapJSONEndpoints(serviceInstanceKeyQueries))
r.HandleFunc("/api/serviceSubscriptionTransaction/{query}", mapJSONEndpoints(serviceSubscriptionQueries))
r.HandleFunc("/api/virtualMachine/{query}", mapJSONEndpoints(virtualMachineQueries))
r.HandleFunc("/api/user/{query}", mapJSONEndpoints(userQueries))
r.HandleFunc("/api/eventLogs/{query}", mapJSONEndpoints(eventLogQueries))
r.HandleFunc("/api/virtualMachineAccessGroupPermissions/{query}", mapJSONEndpoints(virtualMachineAccessGroupPermissionQueries))
http.Handle("/", r)
fmt.Println(fmt.Sprintf("Starting webserver at http://0.0.0.0:%d...", *port))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), handlers.LoggingHandler(os.Stdout, r)))
}
|
package main
import (
"fmt"
"net/http"
"log"
"database/sql"
_ "github.com/lib/pq"
"text/template"
)
var (
db *sql.DB
createTable = `CREATE TABLE IF NOT EXISTS users(
name character varying(100) NOT NULL,
email character varying(100) NOT NULL,
description character varying(500) NOT NULL
);`
)
const (
DB_USER = "am5o2vnbg6cqec8o"
DB_PASSWORD = "ajlfa0hb0cmz6jyx0h0n0hb6yhmj1sco"
DB_NAME = "demo_db"
DB_PORT = "43251"
DB_HOST = "192.168.3.241"
)
type User struct {
Name string
Email string
Description string
}
func setupDB() *sql.DB {
dbInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME )
db, err := sql.Open("postgres", dbInfo)
PanicIf(err)
return db
}
func PanicIf(err error) {
if err != nil {
fmt.Println("Error: ", err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request ) {
fmt.Println("In indexHandler")
rows, err := db.Query("SELECT * FROM users")
PanicIf(err)
fmt.Println("Rows:",rows)
users := []User{}
for rows.Next() {
user := User{}
err := rows.Scan(&user.Name, &user.Email, &user.Description)
PanicIf(err)
users = append(users, user)
}
t := template.New("new.html")
t, err = template.ParseFiles("templates/index.html")
PanicIf(err)
t.Execute(w, users)
}
func newHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("In newHandler")
t := template.New("new.index")
t, _ = template.ParseFiles("templates/new.html")
t.Execute(w, t)
}
func saveHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("In saveHanlder")
res, err := db.Exec("INSERT INTO users (name, email, description) VALUES ($1, $2, $3)",
r.FormValue("name"),
r.FormValue("email"),
r.FormValue("description"))
PanicIf(err)
fmt.Println(res)
http.Redirect(w, r, "/", http.StatusFound)
}
func main() {
db = setupDB()
defer db.Close()
ctble, err := db.Query(createTable)
PanicIf(err)
fmt.Println("Table created successfully", ctble)
http.HandleFunc("/", indexHandler)
http.HandleFunc("/new/", newHandler)
http.HandleFunc("/save/", saveHandler)
fmt.Println("Listening server......")
http.Handle("/public/css/", http.StripPrefix("/public/css/", http.FileServer(http.Dir("public/css"))))
http.Handle("/public/images/", http.StripPrefix("/public/images/", http.FileServer(http.Dir("public/images"))))
if err := http.ListenAndServe("0.0.0.0:3000", nil); err != nil {
log.Fatalf("Template Execution Error:", err)
}
}
|
package rest
import "fmt"
// Exec creates an API Client and uses its
// GetGoogle method, then prints the result
func Exec() error {
c := NewAPIClient("username", "password")
StatusCode, err := c.GetGoogle()
if err != nil {
return err
}
fmt.Println("Result of GetGoogle:", StatusCode)
return nil
}
|
package term
import (
"bytes"
"fmt"
"io"
"strconv"
"sync"
"text/template"
"unicode"
"unicode/utf8"
"github.com/k0kubun/go-ansi"
)
type attribute int
type icon struct {
color attribute
char string
}
const (
fGBold attribute = 1
fGFaint attribute = 2
fGItalic attribute = 3
fGUnderline attribute = 4
fGBlack attribute = 30
fGRed attribute = 31
fGGreen attribute = 32
fGYellow attribute = 33
fGBlue attribute = 94
fGMagenta attribute = 35
fGCyan attribute = 36
fGWhite attribute = 97
)
const (
bGBlack attribute = iota + 40
bGRed
bGGreen
bGYellow
bGBlue
bGMagenta
bGCyan
bGWhite
)
var funcMap = template.FuncMap{
"black": styler(fGBlack),
"red": styler(fGRed),
"green": styler(fGGreen),
"yellow": styler(fGYellow),
"blue": styler(fGBlue),
"magenta": styler(fGMagenta),
"cyan": styler(fGCyan),
"white": styler(fGWhite),
"bgBlack": styler(bGBlack),
"bgRed": styler(bGRed),
"bgGreen": styler(bGGreen),
"bgYellow": styler(bGYellow),
"bgBlue": styler(bGBlue),
"bgMagenta": styler(bGMagenta),
"bgCyan": styler(bGCyan),
"bgWhite": styler(bGWhite),
"bold": styler(fGBold),
"faint": styler(fGFaint),
"italic": styler(fGItalic),
"underline": styler(fGUnderline),
"iconQ": iconer(iconInitial),
"iconGood": iconer(iconGood),
"iconWarn": iconer(iconWarn),
"iconBad": iconer(iconBad),
"iconSel": iconer(iconSelect),
"iconChk": iconer(iconCheckboxCheck),
"iconBox": iconer(iconCheckbox),
}
func styler(attr attribute) func(interface{}) string {
return func(v interface{}) string {
s, ok := v.(string)
if ok && s == ">>" {
return fmt.Sprintf("\033[%sm", strconv.Itoa(int(attr)))
}
return fmt.Sprintf("\033[%sm%v%s", strconv.Itoa(int(attr)), v, "\033[0m")
}
}
func iconer(ic icon) func() string {
return func() string { return styler(ic.color)(ic.char) }
}
// Sprintf formats a string template and outputs console ready text
func Sprintf(in string, data interface{}) string {
return string(renderStringTemplate(in, data))
}
func renderStringTemplate(in string, data interface{}) []byte {
tpl, err := template.New("").Funcs(funcMap).Parse(in)
if err != nil {
panic(err)
}
var buf bytes.Buffer
err = tpl.Execute(&buf, data)
if err != nil {
panic(err)
}
return buf.Bytes()
}
// ScreenBuf is a convenient way to write to terminal screens. It creates,
// clears and, moves up or down lines as needed to write the output to the
// terminal using ANSI escape codes.
type ScreenBuf struct {
w io.Writer
buf *bytes.Buffer
mut sync.Mutex
}
// NewScreenBuf creates and initializes a new ScreenBuf.
func NewScreenBuf(w io.Writer) *ScreenBuf {
ansi.CursorHide()
return &ScreenBuf{buf: &bytes.Buffer{}, w: w}
}
func (s *ScreenBuf) reset() {
linecount := bytes.Count(s.buf.Bytes(), []byte("\n"))
s.buf.Reset()
ClearLines(s.buf, linecount)
}
// WriteTmpl will write a text/template out to the console, using a mutex so that
// only a single writer at a time can write. This prevents the buffer from losing
// sync with the newlines
func (s *ScreenBuf) WriteTmpl(in string, data interface{}) {
s.mut.Lock()
defer s.mut.Unlock()
s.reset()
defer s.flush()
termWidth := Width()
tmpl := ansiwrap(renderStringTemplate(in, data), termWidth)
if tmpl[len(tmpl)-1] != '\n' {
tmpl = append(tmpl, '\n')
}
s.buf.Write(tmpl)
}
// Done will show the cursor again and give back control
func (s *ScreenBuf) Done() {
ansi.CursorShow()
}
func (s *ScreenBuf) flush() {
io.Copy(s.w, bytes.NewBuffer(s.buf.Bytes()))
}
// ansiwrap will wrap a byte array (add linebreak) with awareness of
// ansi character widths
func ansiwrap(str []byte, width int) []byte {
output := []byte{}
currentChunk := []byte{}
currentLine := []byte{}
for _, s := range str {
if s == '\n' {
currentChunk = append(currentChunk, s)
currentLine = append(currentLine, currentChunk...)
output = append(output, currentLine...)
currentLine = []byte{}
currentChunk = []byte{}
continue
} else if s == ' ' {
linewidth := runeCount(append(currentLine, currentChunk...))
if linewidth > width {
output = append(output, append(currentLine, '\n')...)
currentLine = currentChunk
currentChunk = []byte{}
continue
}
currentLine = append(currentLine, currentChunk...)
currentChunk = []byte{}
}
currentChunk = append(currentChunk, s)
}
currentLine = append(currentLine, currentChunk...)
output = append(output, currentLine...)
return output
}
// copied from ansiwrap.
// https://github.com/manifoldco/ansiwrap/blob/master/ansiwrap.go#L193
// ansiwrap worked well but I needed a version the preserved
// spacing so I just copied this method over for acurate space counting.
// There is a major problem with this though. It is not able to count
// tab spaces
func runeCount(b []byte) int {
l := 0
inSequence := false
for len(b) > 0 {
if b[0] == '\033' {
inSequence = true
b = b[1:]
continue
}
r, rl := utf8.DecodeRune(b)
b = b[rl:]
if inSequence {
if r == 'm' {
inSequence = false
}
continue
}
if !unicode.IsPrint(r) {
continue
}
l++
}
return l
}
|
package main
const (
inf = 1000000000
)
func updateMatrix(matrix [][]int) [][]int {
if len(matrix) == 0 {
return matrix
}
m, n := len(matrix), len(matrix[0])
// 先把"1"赋值为inf,表示"1"到"0"的距离此时为无穷大
for i := 0; i < m; i++ {
for t := 0; t < n; t++ {
if matrix[i][t] == 1 {
matrix[i][t] = inf
}
}
}
// 从上到下、从左到右遍历
for i := 0; i < m; i++ {
for t := 0; t < n; t++ {
if i > 0 {
matrix[i][t] = min(matrix[i][t], matrix[i-1][t]+1)
}
if t > 0 {
matrix[i][t] = min(matrix[i][t], matrix[i][t-1]+1)
}
}
}
// 从下到上、从右到左遍历
for i := m - 1; i >= 0; i-- {
for t := n - 1; t >= 0; t-- {
if i < m-1 {
matrix[i][t] = min(matrix[i][t], matrix[i+1][t]+1)
}
if t < n-1 {
matrix[i][t] = min(matrix[i][t], matrix[i][t+1]+1)
}
}
}
return matrix
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
/*
总结
1. 这题目之前是采用BFS做的,其实也可以用DP做。
2. 思路如下:
(1) 由于"1"到"0"的最短距离取决于"1"的四周,于是可以得出
matrix[i][t] = min(matrix[i][t+1]+1, matrix[i][t+1]+1, matrix[i-1][t]+1 matrix[i][t-1]+1)
这里涉及了4个方向,于是我们分2次遍历,第一次从上到下、从左到右遍历,第二次从下到上、从右到左遍历
综合以上的遍历结果,就能正确的得出matrix[i][t]的值了。
(2) 详情看代码
*/
|
package grant
import (
"net/http"
"time"
"github.com/lyokato/goidc/bridge"
"github.com/lyokato/goidc/log"
oer "github.com/lyokato/goidc/oauth_error"
"github.com/lyokato/goidc/scope"
)
const TypeRefreshToken = "refresh_token"
func RefreshToken() *GrantHandler {
return &GrantHandler{
TypeRefreshToken,
func(r *http.Request, c bridge.Client, sdi bridge.DataInterface,
logger log.Logger, requestedTime time.Time) (*Response, *oer.OAuthError) {
rt := r.FormValue("refresh_token")
if rt == "" {
logger.Debug(log.TokenEndpointLog(TypeRefreshToken,
log.MissingParam,
map[string]string{
"param": "refresh_token",
"client_id": c.GetId(),
},
"'refresh_token' not found"))
return nil, oer.NewOAuthError(oer.ErrInvalidRequest,
"missing 'refresh_token' parameter")
}
old, err := sdi.FindOAuthTokenByRefreshToken(rt)
if err != nil {
if err.Type() == bridge.ErrFailed {
logger.Debug(log.TokenEndpointLog(TypeRefreshToken,
log.NoEnabledAccessToken,
map[string]string{
"method": "FindAccessTokenByRefreshToken",
"refresh_token": rt,
"client_id": c.GetId(),
},
"enabled access_token associated with the refresh_token not found."))
return nil, oer.NewOAuthSimpleError(oer.ErrInvalidGrant)
} else if err.Type() == bridge.ErrUnsupported {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceUnsupported,
map[string]string{"method": "FindAccessTokenByRefreshToken"},
"the method returns 'unsupported' error."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
} else {
logger.Warn(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceServerError,
map[string]string{
"method": "FindAccessTokenByRefreshToken",
"refresh_token": rt,
"client_id": c.GetId(),
},
"interface returned ServerError."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
} else {
if old == nil {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceError,
map[string]string{"method": "FindAccessTokenByRefreshToken"},
"the method returns (nil, nil)."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
}
if old.GetRefreshTokenExpiresIn()+old.GetCreatedAt() < requestedTime.Unix() {
logger.Info(log.TokenEndpointLog(TypeRefreshToken,
log.RefreshTokenConditionMismatch,
map[string]string{"client_id": c.GetId()},
"expired refresh_token"))
return nil, oer.NewOAuthError(oer.ErrInvalidGrant,
"expired 'refresh_token'")
}
info, err := sdi.FindActiveAuthInfoById(old.GetAuthId())
if err != nil {
if err.Type() == bridge.ErrFailed {
logger.Debug(log.TokenEndpointLog(TypeRefreshToken,
log.NoEnabledAuthInfo,
map[string]string{
"method": "FindActiveAuthInfoById",
"client_id": c.GetId(),
},
"enabled AuthInfo associated with the id not found."))
return nil, oer.NewOAuthSimpleError(oer.ErrInvalidGrant)
} else if err.Type() == bridge.ErrUnsupported {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceUnsupported,
map[string]string{"method": "FindActiveAuthInfoById"},
"the method returns 'unsupported' error."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
} else {
logger.Warn(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceServerError,
map[string]string{
"method": "FindActiveAuthInfoById",
"client_id": c.GetId(),
},
"interface returned ServerError."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
} else {
if info == nil {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceError,
map[string]string{"method": "FindActiveAuthInfoById"},
"the method returns (nil, nil)."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
}
if info.GetClientId() != c.GetId() {
logger.Info(log.TokenEndpointLog(TypeRefreshToken,
log.AuthInfoConditionMismatch,
map[string]string{"client_id": c.GetId()},
"'client_id' mismatch"))
return nil, oer.NewOAuthSimpleError(oer.ErrInvalidGrant)
}
scp := info.GetScope()
if !scope.IncludeOfflineAccess(scp) {
logger.Info(log.TokenEndpointLog(TypeRefreshToken,
log.ScopeConditionMismatch,
map[string]string{"client_id": c.GetId()},
"'offline_access' not found"))
return nil, oer.NewOAuthSimpleError(oer.ErrInvalidGrant)
}
token, err := sdi.RefreshAccessToken(info, old)
if err != nil {
if err.Type() == bridge.ErrFailed {
logger.Debug(log.TokenEndpointLog(TypeRefreshToken,
log.AccessTokenRefreshFailed,
map[string]string{
"method": "RefreshAccessToken",
"client_id": c.GetId(),
},
"failed refreshing access_token."))
return nil, oer.NewOAuthSimpleError(oer.ErrInvalidGrant)
} else if err.Type() == bridge.ErrUnsupported {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceUnsupported,
map[string]string{"method": "RefreshAccessToken"},
"the method returns 'unsupported' error."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
} else {
logger.Warn(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceServerError,
map[string]string{
"method": "RefreshAccessToken",
"client_id": c.GetId(),
},
"interface returned ServerError."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
} else {
if token == nil {
logger.Error(log.TokenEndpointLog(TypeRefreshToken,
log.InterfaceError,
map[string]string{"method": "RefreshAccessToken"},
"the method returns (nil, nil)."))
return nil, oer.NewOAuthSimpleError(oer.ErrServerError)
}
}
res := NewResponse(token.GetAccessToken(), token.GetAccessTokenExpiresIn())
if scp != "" {
res.Scope = scp
}
newRt := token.GetRefreshToken()
if newRt != "" {
res.RefreshToken = newRt
}
return res, nil
},
}
}
|
package heuristics
func linearConflicts(grid []int, size int, depth int) float32 {
conflicts := 0
for x1 := 0; x1 < size; x1++ {
for y1 := 0; y1 < size-1; y1++ {
if grid[get1d(x1, y1, size)] != 0 {
tmp := finalPos[grid[get1d(x1, y1, size)]]
targetx, targety := tmp[0], tmp[1]
if (x1 == targetx) != (y1 == targety) {
if (x1 == targetx) && (y1 < targety) {
// Case 1: my x is ok, my target in on my right
// I check the other ones in this line
for j := y1; j < size; j++ {
currPos := get1d(x1, j, size)
if grid[currPos] != 0 {
currGoalPos := finalPos[grid[currPos]]
// if his target is in this line and before mine
if currGoalPos[0] == x1 && currGoalPos[1] < targety {
conflicts++
}
}
}
}
if (y1 == targety) && (x1 < targetx) {
// Case 2: my y is ok, my target is under me
// I check the other ones in this col
for i := x1; i < size; i++ {
currPos := get1d(i, y1, size)
if grid[currPos] != 0 {
currGoalPos := finalPos[grid[currPos]]
// if his target is in this col and before mine
if currGoalPos[1] == y1 && currGoalPos[0] <= targetx {
conflicts++
}
}
}
}
}
}
}
}
return manhattan(grid, size, depth) + 2*float32(conflicts)
}
func linearConflictsA(grid []int, size int, depth int) float32 {
return linearConflicts(grid, size, depth) + float32(depth)
}
|
package log_test
import (
"bytes"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"opendev.org/airship/airshipctl/pkg/log"
)
var logFormatRegex = regexp.MustCompile(`^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} .*`)
const prefixLength = len("2001/02/03 16:05:06 ")
func TestLoggingPrintf(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
t.Run("Print", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(false, output)
log.Print("Print args ", 5)
actual := output.String()
expected := "Print args 5\n"
require.Regexp(logFormatRegex, actual)
actual = actual[prefixLength:]
assert.Equal(expected, actual)
})
t.Run("Printf", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(false, output)
log.Printf("%s %d", "Printf args", 5)
actual := output.String()
expected := "Printf args 5\n"
require.Regexp(logFormatRegex, actual)
actual = actual[prefixLength:]
assert.Equal(expected, actual)
})
}
func TestLoggingDebug(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
t.Run("DebugTrue", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(true, output)
log.Debug("DebugTrue args ", 5)
actual := output.String()
expected := "DebugTrue args 5\n"
require.Regexp(logFormatRegex, actual)
actual = actual[prefixLength:]
assert.Equal(expected, actual)
})
t.Run("DebugfTrue", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(true, output)
log.Debugf("%s %d", "DebugfTrue args", 5)
actual := output.String()
expected := "DebugfTrue args 5\n"
require.Regexp(logFormatRegex, actual)
actual = actual[prefixLength:]
assert.Equal(expected, actual)
})
t.Run("DebugFalse", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(false, output)
log.Debug("DebugFalse args ", 5)
assert.Equal("", output.String())
})
t.Run("DebugfFalse", func(t *testing.T) {
output := new(bytes.Buffer)
log.Init(false, output)
log.Debugf("%s %d", "DebugFalse args", 5)
assert.Equal("", output.String())
})
}
|
package quic
import (
"gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Buffer Pool", func() {
It("returns buffers of cap", func() {
buf := *getPacketBuffer()
Expect(buf).To(HaveCap(int(protocol.MaxReceivePacketSize)))
})
It("panics if wrong-sized buffers are passed", func() {
Expect(func() {
putPacketBuffer(&[]byte{0})
}).To(Panic())
})
})
|
package object
import (
"hash/fnv"
)
const (
STRING_OBJ = "STRING"
)
type String struct {
Value string
}
func (s *String) Type() Type {
return STRING_OBJ
}
func (s *String) Inspect() string {
return s.Value
}
func (s *String) MapKey() MapKey {
h := fnv.New64a()
_, _ = h.Write([]byte(s.Value))
mk := MapKey{
Type: s.Type(),
Value: h.Sum64(),
}
return mk
}
|
// Way to try to enqueue a Job and report back if queue is full and its rejected to add new Job
func TryEnqueue(job Job, jobChan <-chan Job) bool {
select {
case jobChan <- job:
return true
default:
return false
}
}
// Usage
if !TryEnqueue(job, chan) {
http.Error(w, "max capacity reached", 503)
return
}
|
package conf
import "strings"
const (
// ShortVersion 短版本号
ShortVersion = "droneDeploy 0.0.1"
)
// The value of variables come form `gb build -ldflags '-X "build.Build=xxxxx" -X "build.CommitID=xxxx"' `
var (
// Build build time
Build string
// Branch current git branch
Branch string
// Commit git commit id
Commit string
// Message last git commit message
Message string
Platform string
)
// BuildVersion 生成版本信息
func BuildVersion() string {
var buf strings.Builder
buf.WriteString(ShortVersion)
if Build != "" {
buf.WriteByte('\n')
buf.WriteString("build: ")
buf.WriteString(Build)
}
if Branch != "" {
buf.WriteByte('\n')
buf.WriteString("branch: ")
buf.WriteString(Branch)
}
if Commit != "" {
buf.WriteByte('\n')
buf.WriteString("commit: ")
buf.WriteString(Commit)
}
if Message != "" {
buf.WriteByte('\n')
buf.WriteString("message: ")
buf.WriteString(Message)
}
if Platform != "" {
buf.WriteByte('\n')
buf.WriteString("Platform: ")
buf.WriteString(Platform)
}
return buf.String()
}
|
// A basic HTTP server.
// By default, it serves the current working directory on port 8080.
package main
import (
"math/rand"
"sort"
"strings"
"time"
)
type slice struct {
sort.IntSlice
solutions [][]string
}
func (s slice) Swap(i, j int) {
s.IntSlice.Swap(i, j)
s.solutions[i], s.solutions[j] = s.solutions[j], s.solutions[i]
}
func contains(s []int, e int) (bool, int) {
for i, a := range s {
if a == e {
return true, i
}
}
return false, -1
}
func generateRandomSolution(length int, colors []string) []string {
states := []string{}
for i := 0; i < length; i++ {
randIndex := rand.Intn(len(colors))
color := colors[randIndex]
states = append(states, color)
}
return states
}
func fitnessFunction(neighbors [][]int, solution []string) int {
fitness := 0
for i := 0; i < len(neighbors); i++ {
for j := 0; j < len(neighbors[i]); j++ {
index := neighbors[i][j]
if strings.Compare(solution[i], solution[index]) == 0 {
fitness++
}
}
}
return fitness
}
func getBestHalf(solutions [][]string, neighbors [][]int) [][]string {
length := len(solutions)
fitnessArray := make([]int, 0, length)
for i := 0; i < length; i++ {
fitnessArray = append(fitnessArray, fitnessFunction(neighbors, solutions[i]))
}
s := &slice{IntSlice: sort.IntSlice(fitnessArray), solutions: solutions}
sort.Sort(s)
return s.solutions[:length/2]
}
func getBestSolution(solutions [][]string, neighbors [][]int) ([]string, int) {
best := 99999999
index := 0
for i := 0; i < len(solutions); i++ {
res := fitnessFunction(neighbors, solutions[i])
if res < best {
best = res
index = i
}
}
return solutions[index], best
}
func onePointCrossover(solutions [][]string, numNodes int, numGenerations int, neighbors [][]int, colors []string) ([][]string, time.Duration) {
start := time.Now()
mutationProbability := 0.1
newSolutions := make([][]string, len(solutions))
for i := range newSolutions {
newSolutions[i] = make([]string, len(solutions[i]))
copy(newSolutions[i], solutions[i])
}
for i := 0; i < numGenerations; i++ {
solutionsLength := len(newSolutions)
for j := 0; j < solutionsLength; j += 2 {
index := rand.Intn(numNodes)
parent1, parent2 := newSolutions[j], newSolutions[j+1]
child1, child2 := make([]string, numNodes), make([]string, numNodes)
copy(child1, parent1)
copy(child2, parent2)
child1[index], child2[index] = parent2[index], parent1[index]
child1Mutation := rand.Float64()
if child1Mutation < mutationProbability {
randIndex := rand.Intn(numNodes)
randColorIndex := rand.Intn(len(colors))
child1[randIndex] = colors[randColorIndex]
}
child2Mutation := rand.Float64()
if child2Mutation < mutationProbability {
randIndex := rand.Intn(numNodes)
randColorIndex := rand.Intn(len(colors))
child2[randIndex] = colors[randColorIndex]
}
newSolutions = append(newSolutions, child1)
newSolutions = append(newSolutions, child2)
}
newSolutions = getBestHalf(newSolutions, neighbors)
}
return newSolutions, time.Since(start)
}
func twoPointCrossover(solutions [][]string, numNodes int, numGenerations int, neighbors [][]int, colors []string) ([][]string, time.Duration) {
start := time.Now()
mutationProbability := 0.1
newSolutions := make([][]string, len(solutions))
for i := range newSolutions {
newSolutions[i] = make([]string, len(solutions[i]))
copy(newSolutions[i], solutions[i])
}
for i := 0; i < numGenerations; i++ {
solutionsLength := len(newSolutions)
for j := 0; j < solutionsLength; j += 2 {
fromIndex := rand.Intn(numNodes)
toIndex := fromIndex + rand.Intn(numNodes-fromIndex)
parent1, parent2 := newSolutions[j], newSolutions[j+1]
child1, child2 := make([]string, numNodes), make([]string, numNodes)
copy(child1, parent1)
copy(child2, parent2)
for index := fromIndex; index < toIndex; index++ {
child1[index], child2[index] = parent2[index], parent1[index]
}
child1Mutation := rand.Float64()
if child1Mutation < mutationProbability {
randIndex := rand.Intn(numNodes)
randColorIndex := rand.Intn(len(colors))
child1[randIndex] = colors[randColorIndex]
}
child2Mutation := rand.Float64()
if child2Mutation < mutationProbability {
randIndex := rand.Intn(numNodes)
randColorIndex := rand.Intn(len(colors))
child2[randIndex] = colors[randColorIndex]
}
newSolutions = append(newSolutions, child1)
newSolutions = append(newSolutions, child2)
}
newSolutions = getBestHalf(newSolutions, neighbors)
}
return newSolutions, time.Since(start)
}
func getRandomUniqueNeighborSlice(index int, numNodes int) []int {
neighbors := []int{}
for i := 0; i < numNodes; i++ {
rand := rand.Float64()
if rand < 0.05 && i != index {
neighbors = append(neighbors, i)
}
}
return neighbors
}
func generateRandomGraph(numNodes int) [][]int {
neighbors := make([][]int, numNodes)
for i := 0; i < numNodes; i++ {
neighbors[i] = getRandomUniqueNeighborSlice(i, numNodes)
}
return neighbors
}
var onePointSolutions = [][]string{}
var twoPointSolutions = [][]string{}
var randSolutions [][]string
var neighbors [][]int
var numNodes = 100
var numGenerations = 20
var colors = []string{"b", "w", "r"}
// Init the algorithm
func InitColoring(nodes int, generations int) [][]int {
numNodes = nodes
numGenerations = generations
rand.Seed(time.Now().UTC().UnixNano())
neighbors = generateRandomGraph(numNodes)
randSolutions = [][]string{}
for i := 0; i < numNodes; i++ {
randSolutions = append(randSolutions, generateRandomSolution(numNodes, colors))
}
return neighbors
}
// RUN ONE POINT
func RunOnePoint() ([]string, int, time.Duration) {
solutions, time := onePointCrossover(randSolutions, numNodes, numGenerations, neighbors, colors)
solution, fitness := getBestSolution(solutions, neighbors)
return solution, fitness, time
}
// RUN TWO POINT
func RunTwoPoint() ([]string, int, time.Duration) {
solutions, time := twoPointCrossover(randSolutions, numNodes, numGenerations, neighbors, colors)
solution, fitness := getBestSolution(solutions, neighbors)
return solution, fitness, time
}
|
package date
import "time"
func GetCurrentDateTime() string {
return time.Now().Format("2006-01-02 15:04:05")
}
func GetCurrentDate() string {
return time.Now().Format("2006-01-02")
}
func ParseDateTime(dateTime string) (time.Time, error) {
return time.ParseInLocation("2006-01-02 15:04:05", dateTime, time.Local)
}
func ParseDate(date string) (time.Time, error) {
return time.ParseInLocation("2006-01-02", date, time.Local)
}
func ParseDateMonth(date string) (time.Time, error) {
return time.ParseInLocation("2006-01", date, time.Local)
}
|
package quiz
import (
"testing"
)
func Test_BalanceOf(t *testing.T) {
p := NewPCM()
p.BalanceOf("0x03CDD0B4878BA94BF8bFadD6c2C2241759Fd158A")
if PrintLog {
t.Fail()
}
}
|
package main
import "fmt"
func main() {
// 位运算
fmt.Println(2 & 3) // 2
fmt.Println(2 | 3) // 3
fmt.Println(2 ^ 3) // 1
}
|
package dcp
import (
"reflect"
"testing"
)
func Test_insertManyQuery(t *testing.T) {
type args struct {
input []string
query string
}
tests := []struct {
name string
args args
want []string
}{
{"0", args{input: []string{}, query: "e"}, []string{}},
{"1", args{input: []string{" dog", " deer ", "deal"}, query: "de"}, []string{"deal", "deer"}},
{"2", args{input: []string{"edison", "fluxo laminar"}, query: "e"}, []string{"edison"}},
{"3", args{input: []string{"amélia"}, query: "amé"}, []string{"amélia"}},
{"4", args{input: []string{"fluxo laminar"}, query: "f"}, []string{"fluxo laminar"}},
{"5", args{input: []string{" dog", " deer ", "deal"}, query: "d"}, []string{"dog", "deal", "deer"}},
}
arrayContains := func(arr []string, item string) bool {
// this is also ugly code
for _, i := range arr {
if reflect.DeepEqual(i, item) || len(i) == 0 && len(item) == 0 {
return true
}
}
return false
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
root := &trieNode{}
root.initTrieNode('*')
root.insertMany(tt.args.input)
got := root.query(tt.args.query)
if len(got) != len(tt.want) {
t.Errorf("len(powerSet()) = %v, want %v", len(got), len(tt.want))
}
for _, i := range tt.want {
if !arrayContains(got, i) {
t.Errorf("powerSet() = %v, want %v", got, tt.want)
}
}
})
}
}
|
package main
import (
"fmt"
"log"
"os"
"strconv"
"../chord"
)
func main() {
//hostName := chord.GetOutboundIP() + ":" + "5678"
//hostName := "farm01"
//portNumber := 5678
kpubs := chord.GetKpubString(os.Args[2])
portNumber, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("invalid portNumber")
}
fmt.Printf("pub key str is %v\n", kpubs)
chord.CreateLastingRing(portNumber, kpubs)
}
|
package main
import (
"fmt"
"github.com/teploff/otus/hw_4/list"
)
func main() {
// Usage example
l := list.List{}
l.PushFront(0)
l.PushBack(1)
l.PushFront(2)
l.PushBack(3)
l.Remove(l.Last())
l.Remove(l.First())
l.Remove(l.Last())
l.Remove(l.First())
fmt.Println(l.Len())
}
|
package main
import (
"context"
"encoding/json"
"github.com/b2wdigital/goignite/pkg/config"
"github.com/b2wdigital/goignite/pkg/health"
"github.com/b2wdigital/goignite/pkg/log"
"github.com/b2wdigital/goignite/pkg/log/logrus/v1"
"github.com/b2wdigital/goignite/pkg/transport/client/redis/v7"
)
func main() {
config.Load()
logrus.NewLogger()
_, err := redis.NewDefaultClient(context.Background())
if err != nil {
log.Error(err)
}
all := health.CheckAll(context.Background())
j, _ := json.Marshal(all)
log.Info(string(j))
}
|
package helpers
// Yoinked from:
// https://leetcode.com/problems/iterator-for-combination/discuss/502469/
type combinationIterator struct {
Permutations *[][]int
offset int
}
// CombinationGenerator generates all possible combinations of length 'combinationLength' from int array 'values'
func CombinationGenerator(values []int, combinationLength int) combinationIterator {
permutations := make([][]int, 0)
helper(values, combinationLength, &permutations, make([]int, 0), 0)
return combinationIterator{Permutations: &permutations, offset: 0}
}
func helper(values []int, l int, per *[][]int, comb []int, start int) {
if len(comb) == l {
*per = append(*per, comb)
return
}
for i := start; i < len(values); i++ {
helper(values, l, per, append(comb, values[i]), i+1)
}
}
// Get the next iteration of combinations
func (iterator *combinationIterator) Next() []int {
next := (*iterator.Permutations)[iterator.offset]
iterator.offset++
return next
}
// Check if a next interation is available
func (iterator *combinationIterator) HasNext() bool {
return iterator.offset < len(*iterator.Permutations)
}
|
package kucoin
import "net/http"
// A FillModel represents the structure of fill.
type FillModel struct {
Symbol string `json:"symbol"`
TradeId string `json:"tradeId"`
OrderId string `json:"orderId"`
CounterOrderId string `json:"counterOrderId"`
Side string `json:"side"`
Liquidity string `json:"liquidity"`
ForceTaker bool `json:"forceTaker"`
Price string `json:"price"`
Size string `json:"size"`
Funds string `json:"funds"`
Fee string `json:"fee"`
FeeRate string `json:"feeRate"`
FeeCurrency string `json:"feeCurrency"`
Stop string `json:"stop"`
Type string `json:"type"`
CreatedAt int64 `json:"createdAt"`
TradeType string `json:"tradeType"`
}
// A FillsModel is the set of *FillModel.
type FillsModel []*FillModel
// Fills returns a list of recent fills.
func (as *ApiService) Fills(params map[string]string, pagination *PaginationParam) (*ApiResponse, error) {
pagination.ReadParam(params)
req := NewRequest(http.MethodGet, "/api/v1/fills", params)
return as.Call(req)
}
// RecentFills returns the recent fills of the latest transactions within 24 hours.
func (as *ApiService) RecentFills() (*ApiResponse, error) {
req := NewRequest(http.MethodGet, "/api/v1/limit/fills", nil)
return as.Call(req)
}
|
package bzr
import (
"context"
"testing"
"github.com/gobuffalo/plugins"
"github.com/stretchr/testify/require"
)
func Test_Bzr_Generalities(t *testing.T) {
r := require.New(t)
b := Versioner{}
r.Equal("bzr", b.PluginName(), "Name should be bzr")
r.Equal("Provides bzr related hooks to Buffalo applications.", b.Description(), "Description does not match")
}
func Test_Bzr_BuildVersion(t *testing.T) {
r := require.New(t)
vr := &commandRunner{
stdout: "123",
}
v := &Versioner{
pluginsFn: func() []plugins.Plugin {
return []plugins.Plugin{vr}
},
}
s, err := v.BuildVersion(context.Background(), "")
r.NoError(err)
r.Equal(vr.stdout, s)
r.NotNil(vr.cmd)
r.Equal([]string{"bzr", "revno"}, vr.cmd.Args)
}
|
package boilingcore
import (
"sort"
"testing"
"text/template"
)
func TestTemplateNameListSort(t *testing.T) {
t.Parallel()
templs := templateNameList{
"bob.tpl",
"all.tpl",
"struct.tpl",
"ttt.tpl",
}
expected := []string{"bob.tpl", "all.tpl", "struct.tpl", "ttt.tpl"}
for i, v := range templs {
if v != expected[i] {
t.Errorf("Order mismatch, expected: %s, got: %s", expected[i], v)
}
}
expected = []string{"struct.tpl", "all.tpl", "bob.tpl", "ttt.tpl"}
sort.Sort(templs)
for i, v := range templs {
if v != expected[i] {
t.Errorf("Order mismatch, expected: %s, got: %s", expected[i], v)
}
}
}
func TestTemplateList_Templates(t *testing.T) {
t.Parallel()
tpl := template.New("")
tpl.New("wat.tpl").Parse("hello")
tpl.New("que.tpl").Parse("there")
tpl.New("not").Parse("hello")
tplList := templateList{tpl}
foundWat, foundQue, foundNot := false, false, false
for _, n := range tplList.Templates() {
switch n {
case "wat.tpl":
foundWat = true
case "que.tpl":
foundQue = true
case "not":
foundNot = true
}
}
if !foundWat {
t.Error("want wat")
}
if !foundQue {
t.Error("want que")
}
if foundNot {
t.Error("don't want not")
}
}
|
package serial
import (
"fmt"
"io"
"log"
"github.com/EdlinOrg/prominentcolor"
"github.com/jacobsa/go-serial/serial"
)
type OpenOptions = serial.OpenOptions
func Connect(options OpenOptions) io.ReadWriteCloser {
connection, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open: %v", err)
}
return connection
}
func SendColor(port io.ReadWriteCloser, color prominentcolor.ColorRGB) {
b := []byte(fmt.Sprintf("%d,%d,%d;", color.R, color.G, color.B))
n, err := port.Write(b)
if err != nil {
log.Fatalf("port.Write: %v", err)
}
fmt.Println("Wrote", n, "bytes.")
}
|
// Copyright (c) 2018 KIDTSUNAMI
// Author: alex@kidtsunami.com
package util
import (
"sync"
"time"
)
// Example
//
// const format = "15:04:05.999999999Z"
//
// func main() {
// t := util.NewAlignedTicker(5 * time.Second)
// fmt.Printf("Start %s\n", time.Now().UTC().Format(format))
// for i := 0; i < 5; i++ {
// select {
// case now := <-t.C:
// fmt.Printf("Tick %s\n", now.Format(format))
// }
// }
// t.Stop()
// }
type AlignedTicker struct {
t *time.Ticker
C <-chan time.Time
c chan time.Time
sync.Once
}
func NewAlignedTicker(d time.Duration) *AlignedTicker {
now := time.Now().UTC()
wait := now.Add(d + time.Second).Truncate(d).Sub(now)
c := make(chan time.Time, 1)
t := &AlignedTicker{
C: c,
c: c,
}
go func() {
select {
case now := <-time.After(wait):
// prevent panic on early Stop (i.e. before wait is over)
select {
case c <- now:
default:
return
}
t.t = time.NewTicker(d)
t.C = t.t.C
}
}()
return t
}
func (t *AlignedTicker) Stop() {
// run only once
t.Do(func() {
if t.t != nil {
t.t.Stop()
}
close(t.c)
})
}
// More accurate Ticker from
// https://github.com/golang/go/issues/19810
type WallTicker struct {
C <-chan time.Time
align time.Duration
offset time.Duration
stop chan bool
c chan time.Time
skew float64
d time.Duration
last time.Time
tm *time.Timer
sync.Once
}
func NewWallTicker(align, offset time.Duration) *WallTicker {
w := &WallTicker{
align: align,
offset: offset,
stop: make(chan bool),
c: make(chan time.Time, 1),
skew: 1.0,
}
w.C = w.c
w.start()
return w
}
func (w *WallTicker) Stop() {
// run only once
w.Do(func() {
close(w.stop)
if w.tm != nil {
w.tm.Stop()
w.tm = nil
}
})
}
// const fakeAzure = false
func (w *WallTicker) start() {
now := time.Now()
d := time.Until(now.Add(-w.offset).Add(w.align * 4 / 3).Truncate(w.align).Add(w.offset))
d = time.Duration(float64(d) / w.skew)
w.d = d
w.last = now
// if fakeAzure {
// d = time.Duration(float64(d) * 99 / 101)
// }
w.tm = time.AfterFunc(d, w.tick)
}
func (w *WallTicker) tick() {
const α = 0.7 // how much weight to give past history
now := time.Now()
if now.After(w.last) {
w.skew = w.skew*α + (float64(now.Sub(w.last))/float64(w.d))*(1-α)
select {
case <-w.stop:
return
case w.c <- now:
// ok
default:
// client not keeping up, drop tick
}
}
w.start()
}
|
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"net/http"
)
type Book struct {
isbn string
title string
author string
price float32
}
var db *sql.DB
var err error
func main() {
db, err = sql.Open("postgres", "postgres://aman:password@localhost/test1?sslmode=disable")
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("You connected to your database.")
http.HandleFunc("/books",books)
http.Handle("/favicon.ico",http.NotFoundHandler())
http.ListenAndServe(":8000",nil)
}
func books(w http.ResponseWriter,r *http.Request){
isbn:="Jayne Austen"
rows, err := db.Query("SELECT * FROM books WHERE author = $1",isbn)
if err != nil {
panic(err)
}
defer rows.Close()
bks:=make([]Book,0)
for rows.Next() {
bk := Book{}
err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price) // order matters
if err != nil {
panic(err)
}
bks = append(bks, bk)
}
for _,v:=range bks{
fmt.Fprint(w,v.isbn)
fmt.Fprint(w,v.title)
fmt.Fprint(w,v.author)
fmt.Fprint(w,v.price)
fmt.Fprintln(w,"")
}
}
|
package main
import "fmt"
func main() {
// ตัวแปร x เก็บข้อมูลไว้ในอาร์เรย์ 5 หน่วย
var x [5]int
// กำหนดให้สมาชิกลำดับที่ 5 ของอาร์เรย์ x เป็น 100
x[4] = 100
fmt.Println(x)
//
test()
}
func test() {
// สร้างอาร์เรย์ความยาว 5 หน่วย แล้วกำหนดค่าของสมาชิกแต่ละตัว
var y [5]float64
y[0] = 98
y[1] = 93
y[2] = 77
y[3] = 82
y[4] = 83
var total float64 = 0
// i = 0 คือ ค่าเริ่มต้น
// len(y) = นับตามจำนวนค่าในอาร์เรย์
for i := 0; i < len(y); i++ {
total += y[i]
}
// แปลง len() ให้เป็น float64 เหมือนกับ total
fmt.Println(total / float64(len(y)))
}
// แบบที่ 2
func test2() {
var z [5]float64
z[0] = 98
z[1] = 93
z[2] = 77
z[3] = 82
z[4] = 83
var total float64 = 0
// value เปรียบเสมือน z[0]
// _ ใช้เป็นตัวแปรเพื่อบอกคอมไพเลอร์ว่า ไม่ต้องการตัวแปรนั้น
for _, value := range z {
total += value
}
fmt.Println(total / float64(len(z)))
}
|
package links
import (
"testing"
)
type entry struct {
srcAddress string
srcDisplay string
srcHypha string
kind LinkType
href string
display string
}
func TestLink(t *testing.T) {
// address — display — srchypha
mappings := []entry{
{"apple", "", "home",
LinkLocalHypha, "/hypha/apple", "apple"},
{"Apple", "Яблоко", "home",
LinkLocalHypha, "/hypha/apple", "Яблоко"},
{" apple ", "Pomme", "terra/incognita",
LinkLocalHypha, "/hypha/apple", "Pomme"},
{"./meme", "", "apple",
LinkLocalHypha, "/hypha/apple/meme", "./meme"},
{"https://app.le", "app.le website", "app_dot_le",
LinkExternal, "https://app.le", "app.le website"},
}
for _, mapping := range mappings {
var (
link = From(mapping.srcAddress, mapping.srcDisplay, mapping.srcHypha)
kind = link.kind
href = link.Href()
display = link.Display()
)
if kind != mapping.kind {
t.Errorf(`When parsing %s→%s@%s got wrong kind: %v`, mapping.srcAddress, mapping.srcDisplay, mapping.srcHypha, kind)
}
if href != mapping.href {
t.Errorf(`When parsing %s→%s@%s got wrong href: [%s], expected [%s]`, mapping.srcAddress, mapping.srcDisplay, mapping.srcHypha, href, mapping.href)
}
if display != mapping.display {
t.Errorf(`When parsing %s→%s@%s got wrong display: [%s], expected [%s]`, mapping.srcAddress, mapping.srcDisplay, mapping.srcHypha, display, mapping.display)
}
}
}
|
package main
import (
"fmt"
"testing"
)
func (e Constant) eq(e2 Constant) bool {
return e.cType == e2.cType && e.cValue == e2.cValue
}
func compareIndexExpression(e1, e2 Expression) (bool, string) {
if e1.isDirectlyAccessed() != e2.isDirectlyAccessed() {
return false, "Only one expression is accessed with index"
}
if e1.isDirectlyAccessed() {
e1Access := e1.getDirectAccess()
e2Access := e2.getDirectAccess()
if len(e1Access) != len(e2Access) {
return false, fmt.Sprintf("Expressions are indexed different times: %v != %v",
len(e1Access), len(e2Access),
)
}
for i, access := range e1Access {
if access.indexed {
if ok, err := compareExpression(access.indexExpression, e2Access[i].indexExpression); !ok {
return false, err
}
}
}
}
return true, ""
}
func compareVariable(v1, v2 Variable) (bool, string) {
ok1 := v1.vName == v2.vName && v1.vShadow == v2.vShadow && v1.vType == v2.vType
err1 := fmt.Sprintf("Variables are different: %v != %v", v1, v2)
ok2, err2 := compareIndexExpression(v1, v2)
return ok1 && ok2, err1 + err2
}
func compareFunCall(v1, v2 FunCall) (bool, string) {
if v1.funName != v2.funName {
return false, fmt.Sprintf("Function names are different: %v != %v", v1.funName, v2.funName)
}
ok1, err1 := compareExpressions(v1.args, v2.args)
ok2, err2 := compareTypes(v1.retTypes, v2.retTypes)
ok3, err3 := compareIndexExpression(v1, v2)
return ok1 && ok2 && ok3, err1 + err2 + err3
}
func compareArray(v1, v2 Array) (bool, string) {
if !equalType(v1.aType, v2.aType, true) {
return false, fmt.Sprintf("Arrays have different types: %v != %v", v1.aType, v2.aType)
}
if v1.aCount != v2.aCount {
return false, fmt.Sprintf("Arrays have different lengths: %v != %v", v1.aCount, v2.aCount)
}
ok1, err1 := compareExpressions(v1.aExpressions, v2.aExpressions)
ok2, err2 := compareIndexExpression(v1, v2)
return ok1 && ok2, err1 + err2
}
func compareExpression(e1, e2 Expression) (bool, string) {
switch v1 := e1.(type) {
case Constant:
if v2, ok := e2.(Constant); ok && v1.eq(v2) {
return true, ""
}
return false, fmt.Sprintf("%v != %v (Constant)", e1, e2)
case Variable:
if v2, ok := e2.(Variable); ok {
return compareVariable(v1, v2)
}
return false, fmt.Sprintf("%v != %v (Variable)", e1, e2)
case BinaryOp:
if v2, ok := e2.(BinaryOp); ok {
ok1, err1 := compareExpression(v1.leftExpr, v2.leftExpr)
ok2, err2 := compareExpression(v1.rightExpr, v2.rightExpr)
ok3 := v1.operator == v2.operator
return ok1 && ok2 && ok3, err1 + err2
}
return false, fmt.Sprintf("%v != %v (BinaryOp)", e1, e2)
case UnaryOp:
if v2, ok := e2.(UnaryOp); ok {
ok1, err1 := compareExpression(v1.expr, v2.expr)
return v1.operator == v2.operator && ok1, err1
}
return false, fmt.Sprintf("%v != %v (UnaryOp)", e1, e2)
case FunCall:
if v2, ok := e2.(FunCall); ok {
return compareFunCall(v1, v2)
}
case Array:
if v2, ok := e2.(Array); ok {
return compareArray(v1, v2)
}
}
return false, fmt.Sprintf("%v is not an expression", e1)
}
func compareExpressions(ee1, ee2 []Expression) (bool, string) {
if len(ee1) != len(ee2) {
return false, fmt.Sprintf("Different lengths: %v, %v", ee1, ee2)
}
for i, v1 := range ee1 {
if b, e := compareExpression(v1, ee2[i]); !b {
return false, e
}
}
return true, ""
}
// First time really where I have to say - **** generics (in - not having them!)
func compareVariables(vv1, vv2 []Variable) (bool, string) {
if len(vv1) != len(vv2) {
return false, fmt.Sprintf("Different lengths: %v, %v", vv1, vv2)
}
for i, v1 := range vv1 {
if ok, err := compareVariable(v1, vv2[i]); !ok {
return false, err
}
}
return true, ""
}
func compareTypes(tt1, tt2 []ComplexType) (bool, string) {
if len(tt1) != len(tt2) {
return false, fmt.Sprintf("Different lengths: %v, %v", tt1, tt2)
}
for i, t := range tt1 {
if !equalType(t, tt2[i], true) {
return false, fmt.Sprintf("Type comparison: %v != %v", t, tt2[i])
}
}
return true, ""
}
func compareStatement(s1, s2 Statement) (bool, string) {
switch v1 := s1.(type) {
case Assignment:
if v2, ok := s2.(Assignment); ok {
ok1, err1 := compareVariables(v1.variables, v2.variables)
ok2, err2 := compareExpressions(v1.expressions, v2.expressions)
return ok1 && ok2, err1 + err2
}
return false, fmt.Sprintf("%v not an Assignment", s2)
case Condition:
if v2, ok := s2.(Condition); ok {
ok1, err1 := compareExpression(v1.expression, v2.expression)
ok2, err2 := compareBlock(v1.block, v2.block)
ok3, err3 := compareBlock(v1.elseBlock, v2.elseBlock)
return ok1 && ok2 && ok3, err1 + err2 + err3
}
return false, fmt.Sprintf("%v not a Condition", s2)
case Loop:
if v2, ok := s2.(Loop); ok {
ok1, err1 := compareStatement(v1.assignment, v2.assignment)
ok2, err2 := compareExpressions(v1.expressions, v2.expressions)
ok3, err3 := compareStatement(v1.incrAssignment, v2.incrAssignment)
ok4, err4 := compareBlock(v1.block, v2.block)
return ok1 && ok2 && ok3 && ok4, err1 + err2 + err3 + err4
}
case Function:
if v2, ok := s2.(Function); ok {
if v1.fName != v2.fName {
return false, fmt.Sprintf("Function names are different: %v != %v", v1.fName, v2.fName)
}
ok1, err1 := compareVariables(v1.parameters, v2.parameters)
ok2, err2 := compareTypes(v1.returnTypes, v2.returnTypes)
ok3, err3 := compareBlock(v1.block, v2.block)
return ok1 && ok2 && ok3, err1 + err2 + err3
}
case Return:
if v2, ok := s2.(Return); ok {
return compareExpressions(v1.expressions, v2.expressions)
}
case FunCall:
if v2, ok := s2.(FunCall); ok {
return compareFunCall(v1, v2)
}
default:
return false, fmt.Sprintf("Unknown statement: %v", s1)
}
return false, fmt.Sprintf("Expected statement, got: %v", s1)
}
func compareBlock(ss1, ss2 Block) (bool, string) {
if len(ss1.statements) != len(ss2.statements) {
return false, fmt.Sprintf("Statement lists of different lengths: %v, %v", ss1, ss2)
}
for i, v1 := range ss1.statements {
if b, e := compareStatement(v1, ss2.statements[i]); !b {
return false, e
}
}
// TODO: Compare symbol table
return true, ""
}
func compareASTs(generated AST, expected AST) (bool, string) {
return compareBlock(generated.block, expected.block)
}
func testAST(code []byte, expected AST, t *testing.T) {
tokenChan := make(chan Token, 1)
lexerErr := make(chan error, 1)
go tokenize(code, tokenChan, lexerErr)
generated, err := parse(tokenChan)
select {
case e := <-lexerErr:
t.Errorf("Lexer error: %v", e.Error())
return
default:
}
if err != nil {
t.Errorf("Parsing error: %v", err)
}
if b, e := compareASTs(generated, expected); !b {
t.Errorf("Trees don't match: %v", e)
}
}
func newVar(value string, shadow bool) Variable {
return Variable{ComplexType{TYPE_UNKNOWN, "", nil}, value, shadow, nil, 0, 0}
}
func newIndexedVar(value string, e []DirectAccess) Variable {
return Variable{ComplexType{TYPE_UNKNOWN, "", nil}, value, false, e, 0, 0}
}
func newParam(t ComplexType, value string) Variable {
return Variable{t, value, true, nil, 0, 0}
}
func newConst(t Type, value string) Constant {
return Constant{t, value, 0, 0}
}
func newUnary(op Operator, e Expression) UnaryOp {
return UnaryOp{op, e, ComplexType{TYPE_UNKNOWN, "", nil}, 0, 0}
}
func newBinary(op Operator, eLeft, eRight Expression, fixed bool) BinaryOp {
return BinaryOp{op, eLeft, eRight, ComplexType{TYPE_UNKNOWN, "", nil}, fixed, 0, 0}
}
func newArray(t ComplexType, count int, exprs []Expression) Array {
return Array{t, count, exprs, nil, 0, 0}
}
func newAssignment(variables []Variable, expressions []Expression) Assignment {
return Assignment{variables, expressions, 0, 0}
}
func newCondition(e Expression, block, elseBlock Block) Condition {
return Condition{e, block, elseBlock, 0, 0}
}
func newLoop(a Assignment, exprs []Expression, incrA Assignment, b Block) Loop {
return Loop{a, exprs, incrA, b, 0, 0}
}
func newFunction(name string, params []Variable, returnTypes []ComplexType, b Block) Function {
return Function{name, params, returnTypes, b, 0, 0}
}
func newReturn(expressions []Expression) Return {
return Return{expressions, 0, 0}
}
func newFunCall(name string, exprs []Expression) FunCall {
return FunCall{name, false, exprs, []ComplexType{}, nil, 0, 0}
}
func newBlock(statements []Statement) Block {
return Block{statements, &SymbolTable{}, 0, 0}
}
func newAST(statements []Statement) AST {
return AST{newBlock(statements), &SymbolTable{}}
}
func newSimpleTypeList(ts []Type) (tcs []ComplexType) {
for _, t := range ts {
tcs = append(tcs, ComplexType{t, "", nil})
}
return
}
func addIndexAccess(e, indexExpression Expression) Expression {
row, col := indexExpression.startPos()
switch ne := e.(type) {
case Variable:
ne.directAccess = append(ne.directAccess, DirectAccess{true, indexExpression, "", 0, row, col})
return ne
case Array:
ne.directAccess = append(ne.directAccess, DirectAccess{true, indexExpression, "", 0, row, col})
return ne
case FunCall:
ne.directAccess = append(ne.directAccess, DirectAccess{true, indexExpression, "", 0, row, col})
return ne
default:
fmt.Println("This expression can not have indexed access")
}
return e
}
func TestParserExpression1(t *testing.T) {
var code []byte = []byte(`shadow a = 6 + 7 * variable / -(5 -- (8 * - 10000.1234))`)
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", true)},
[]Expression{
newBinary(
OP_PLUS, newConst(TYPE_INT, "6"), newBinary(
OP_MULT, newConst(TYPE_INT, "7"), newBinary(
OP_DIV, newVar("variable", false), newUnary(
OP_NEGATIVE, newBinary(
OP_MINUS, newConst(TYPE_INT, "5"), newUnary(
OP_NEGATIVE, newBinary(
OP_MULT,
newConst(TYPE_INT, "8"),
newUnary(OP_NEGATIVE, newConst(TYPE_FLOAT, "10000.1234")),
false,
),
), false,
),
), false,
), false,
), false,
),
},
),
},
)
testAST(code, expected, t)
}
func TestParserExpression2(t *testing.T) {
var code []byte = []byte(`a = a && b || (5 < false <= 8 && (false2 > variable >= 5.0) != true)`)
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{
newBinary(
OP_AND, newVar("a", false), newBinary(
OP_OR, newVar("b", false), newBinary(
OP_LESS, newConst(TYPE_INT, "5"), newBinary(
OP_LE, newConst(TYPE_BOOL, "false"), newBinary(
OP_AND, newConst(TYPE_INT, "8"), newBinary(
OP_NE, newBinary(
OP_GREATER,
newVar("false2", false),
newBinary(OP_GE, newVar("variable", false), newConst(TYPE_FLOAT, "5.0"), false),
false,
),
newConst(TYPE_BOOL, "true"),
false,
), false,
), false,
), false,
), false,
), false,
),
},
),
},
)
testAST(code, expected, t)
}
func TestParserIf(t *testing.T) {
var code []byte = []byte(`
if a == b {
a = 6
}
a = 1
`)
expected := newAST(
[]Statement{
newCondition(
newBinary(OP_EQ, newVar("a", false), newVar("b", false), false),
newBlock([]Statement{newAssignment([]Variable{newVar("a", false)}, []Expression{newConst(TYPE_INT, "6")})}),
newBlock([]Statement{}),
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newConst(TYPE_INT, "1")},
),
},
)
testAST(code, expected, t)
}
func TestParserIfElse(t *testing.T) {
var code []byte = []byte(`
if a == b {
a = 6
} else {
a = 1
}
`)
expected := newAST(
[]Statement{
newCondition(
newBinary(OP_EQ, newVar("a", false), newVar("b", false), false),
newBlock([]Statement{newAssignment([]Variable{newVar("a", false)}, []Expression{newConst(TYPE_INT, "6")})}),
newBlock([]Statement{newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newConst(TYPE_INT, "1")},
)}),
),
},
)
testAST(code, expected, t)
}
func TestParserAssignment1(t *testing.T) {
var code []byte = []byte(`
a = 1
a, b = 1, 2
a, b, c = 1, 2, 3
`)
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newConst(TYPE_INT, "1")},
),
newAssignment(
[]Variable{newVar("a", false), newVar("b", false)},
[]Expression{newConst(TYPE_INT, "1"), newConst(TYPE_INT, "2")},
),
newAssignment(
[]Variable{newVar("a", false), newVar("b", false), newVar("c", false)},
[]Expression{newConst(TYPE_INT, "1"), newConst(TYPE_INT, "2"), newConst(TYPE_INT, "3")},
),
},
)
testAST(code, expected, t)
}
func TestParserAssignment2(t *testing.T) {
var code []byte = []byte(`
a = 1
a++
a--
a *= 1
a /= 1
a -= 1
a += 1
`)
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newConst(TYPE_INT, "1")},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_PLUS, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_MINUS, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_MULT, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_DIV, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_MINUS, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_PLUS, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
},
)
testAST(code, expected, t)
}
func TestParserAssignmentChar(t *testing.T) {
var code []byte = []byte(`
b = 'b'
`)
expected := newAST(
[]Statement{
newAssignment([]Variable{newVar("b", false)}, []Expression{newConst(TYPE_CHAR, "'b'")}),
},
)
testAST(code, expected, t)
}
func TestParserFor1(t *testing.T) {
var code []byte = []byte(`
for ;; {
a = a+1
}
`)
expected := newAST(
[]Statement{
newLoop(
newAssignment([]Variable{}, []Expression{}),
[]Expression{},
newAssignment([]Variable{}, []Expression{}),
newBlock([]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newBinary(OP_PLUS, newVar("a", false), newConst(TYPE_INT, "1"), false)},
),
}),
),
},
)
testAST(code, expected, t)
}
func TestParserFor2(t *testing.T) {
var code []byte = []byte(`
for i = 5;; {
a = 0
}
`)
expected := newAST(
[]Statement{
newLoop(
newAssignment([]Variable{newVar("i", false)}, []Expression{newConst(TYPE_INT, "5")}),
[]Expression{},
newAssignment([]Variable{}, []Expression{}),
newBlock([]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newConst(TYPE_INT, "0")},
),
}),
),
},
)
testAST(code, expected, t)
}
func TestParserFor3(t *testing.T) {
var code []byte = []byte(`
for i, j = 0, 1; i < 10; i = i+1 {
if b == a {
for ;; {
c = 6
}
}
}
`)
expected := newAST(
[]Statement{
newLoop(
newAssignment(
[]Variable{newVar("i", false), newVar("j", false)},
[]Expression{newConst(TYPE_INT, "0"), newConst(TYPE_INT, "1")},
),
[]Expression{newBinary(OP_LESS, newVar("i", false), newConst(TYPE_INT, "10"), false)},
newAssignment(
[]Variable{newVar("i", false)},
[]Expression{newBinary(OP_PLUS, newVar("i", false), newConst(TYPE_INT, "1"), false)},
),
newBlock([]Statement{
newCondition(
newBinary(OP_EQ, newVar("b", false), newVar("a", false), false),
newBlock([]Statement{
newLoop(
newAssignment([]Variable{}, []Expression{}),
[]Expression{},
newAssignment([]Variable{}, []Expression{}),
newBlock([]Statement{
newAssignment(
[]Variable{newVar("c", false)},
[]Expression{newConst(TYPE_INT, "6")},
),
})),
}),
newBlock([]Statement{}),
),
}),
),
},
)
testAST(code, expected, t)
}
func TestParserFunction1(t *testing.T) {
var code []byte = []byte(`
fun abc() {
a = 1
}
`)
expected := newAST(
[]Statement{
newFunction("abc", []Variable{}, []ComplexType{}, newBlock(
[]Statement{newAssignment([]Variable{newVar("a", false)}, []Expression{newConst(TYPE_INT, "1")})},
)),
},
)
testAST(code, expected, t)
}
func TestParserFunction2(t *testing.T) {
var code []byte = []byte(`
fun abc(a int, b float, c bool, d char) {
a = 1
return
}
`)
expected := newAST(
[]Statement{
newFunction("abc", []Variable{
newParam(ComplexType{TYPE_INT, "", nil}, "a"),
newParam(ComplexType{TYPE_FLOAT, "", nil}, "b"),
newParam(ComplexType{TYPE_BOOL, "", nil}, "c"),
newParam(ComplexType{TYPE_CHAR, "", nil}, "d"),
}, []ComplexType{}, newBlock(
[]Statement{newAssignment([]Variable{newVar("a", false)}, []Expression{newConst(TYPE_INT, "1")}), newReturn(nil)},
)),
},
)
testAST(code, expected, t)
}
func TestParserFunction3(t *testing.T) {
var code []byte = []byte(`
fun abc() int, float, bool, char {
a = 1
b = 'b'
return a, 3.5, true, b
}
`)
expected := newAST(
[]Statement{
newFunction("abc", []Variable{}, newSimpleTypeList([]Type{TYPE_INT, TYPE_FLOAT, TYPE_BOOL, TYPE_CHAR}), newBlock(
[]Statement{
newAssignment([]Variable{newVar("a", false)}, []Expression{newConst(TYPE_INT, "1")}),
newAssignment([]Variable{newVar("b", false)}, []Expression{newConst(TYPE_CHAR, "'b'")}),
newReturn([]Expression{newVar("a", false), newConst(TYPE_FLOAT, "3.5"), newConst(TYPE_BOOL, "true"), newVar("b", false)}),
},
)),
},
)
testAST(code, expected, t)
}
func TestParserFunCall(t *testing.T) {
var code []byte = []byte(`
fun abc() int {
return 1
}
a = abc()
abc()
`)
expected := newAST(
[]Statement{
newFunction("abc", []Variable{}, newSimpleTypeList([]Type{TYPE_INT}), newBlock(
[]Statement{
newReturn([]Expression{newConst(TYPE_INT, "1")}),
},
)),
newAssignment([]Variable{newVar("a", false)}, []Expression{newFunCall("abc", nil)}),
newFunCall("abc", nil),
},
)
testAST(code, expected, t)
}
func TestParserArray1(t *testing.T) {
var code []byte = []byte(`
a = [1, 2, 3]
b = [](int, 3)
`)
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newArray(ComplexType{TYPE_UNKNOWN, "", nil}, 0, []Expression{
newConst(TYPE_INT, "1"), newConst(TYPE_INT, "2"), newConst(TYPE_INT, "3"),
})},
),
newAssignment(
[]Variable{newVar("b", false)},
[]Expression{newArray(ComplexType{TYPE_ARRAY, "", &ComplexType{TYPE_INT, "", nil}}, 3, []Expression{})},
),
},
)
testAST(code, expected, t)
}
func TestParserArray2(t *testing.T) {
var code []byte = []byte(`
a = [1, 2, 3]
b = [](int, 3)
b[1] = a[2]
`)
b := addIndexAccess(newVar("b", false), newConst(TYPE_INT, "1")).(Variable)
a := addIndexAccess(newVar("a", false), newConst(TYPE_INT, "2"))
expected := newAST(
[]Statement{
newAssignment(
[]Variable{newVar("a", false)},
[]Expression{newArray(ComplexType{TYPE_UNKNOWN, "", nil}, 0, []Expression{
newConst(TYPE_INT, "1"), newConst(TYPE_INT, "2"), newConst(TYPE_INT, "3"),
})},
),
newAssignment(
[]Variable{newVar("b", false)},
[]Expression{newArray(ComplexType{TYPE_ARRAY, "", &ComplexType{TYPE_INT, "", nil}}, 3, []Expression{})},
),
newAssignment(
[]Variable{b},
[]Expression{a},
),
},
)
testAST(code, expected, t)
}
|
// Copyright ©2019 The Gonum 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 product
import (
"sort"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/internal/ordered"
"gonum.org/v1/gonum/stat/combin"
)
// Node is a product of two graph nodes.
type Node struct {
UID int64
A, B graph.Node
}
// ID implements the graph.Node interface.
func (n Node) ID() int64 { return n.UID }
// Cartesian constructs the Cartesian product of a and b in dst.
//
// The Cartesian product of G₁ and G₂, G₁□G₂ has edges (u₁, u₂)~(v₁, v₂) when
// (u₁=v₁ and u₂~v₂) or (u₁~v₁ and u₂=v₂).
func Cartesian(dst graph.Builder, a, b graph.Graph) {
aNodes, bNodes, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
indexOfA := indexOf(aNodes)
indexOfB := indexOf(bNodes)
for _, p := range product {
dst.AddNode(p)
}
dims := []int{len(aNodes), len(bNodes)}
for i, uA := range aNodes {
for j, uB := range bNodes {
toB := b.From(uB.ID())
for toB.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{i, indexOfB[toB.Node().ID()]}, dims)],
))
}
toA := a.From(uA.ID())
for toA.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{indexOfA[toA.Node().ID()], j}, dims)],
))
}
}
}
}
// Tensor constructs the Tensor product of a and b in dst.
//
// The Tensor product of G₁ and G₂, G₁⨯G₂ has edges (u₁, u₂)~(v₁, v₂) when
// u₁~v₁ and u₂~v₂.
func Tensor(dst graph.Builder, a, b graph.Graph) {
aNodes, bNodes, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
indexOfA := indexOf(aNodes)
indexOfB := indexOf(bNodes)
for _, p := range product {
dst.AddNode(p)
}
dims := []int{len(aNodes), len(bNodes)}
for i, uA := range aNodes {
toA := a.From(uA.ID())
for toA.Next() {
j := indexOfA[toA.Node().ID()]
for k, uB := range bNodes {
toB := b.From(uB.ID())
for toB.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, k}, dims)],
product[combin.IdxFor([]int{j, indexOfB[toB.Node().ID()]}, dims)],
))
}
}
}
}
}
// Lexicographical constructs the Lexicographical product of a and b in dst.
//
// The Lexicographical product of G₁ and G₂, G₁·G₂ has edges (u₁, u₂)~(v₁, v₂) when
// u₁~v₁ or (u₁=v₁ and u₂~v₂).
func Lexicographical(dst graph.Builder, a, b graph.Graph) {
aNodes, bNodes, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
indexOfA := indexOf(aNodes)
indexOfB := indexOf(bNodes)
for _, p := range product {
dst.AddNode(p)
}
dims := []int{len(aNodes), len(bNodes)}
p := make([]int, 2)
for i, uA := range aNodes {
toA := a.From(uA.ID())
for toA.Next() {
j := indexOfA[toA.Node().ID()]
gen := combin.NewCartesianGenerator([]int{len(bNodes), len(bNodes)})
for gen.Next() {
p = gen.Product(p)
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, p[0]}, dims)],
product[combin.IdxFor([]int{j, p[1]}, dims)],
))
}
}
for j, uB := range bNodes {
toB := b.From(uB.ID())
for toB.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{i, indexOfB[toB.Node().ID()]}, dims)],
))
}
}
}
}
// Strong constructs the Strong product of a and b in dst.
//
// The Strong product of G₁ and G₂, G₁⊠G₂ has edges (u₁, u₂)~(v₁, v₂) when
// (u₁=v₁ and u₂~v₂) or (u₁~v₁ and u₂=v₂) or (u₁~v₁ and u₂~v₂).
func Strong(dst graph.Builder, a, b graph.Graph) {
aNodes, bNodes, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
indexOfA := indexOf(aNodes)
indexOfB := indexOf(bNodes)
for _, p := range product {
dst.AddNode(p)
}
dims := []int{len(aNodes), len(bNodes)}
for i, uA := range aNodes {
for j, uB := range bNodes {
toB := b.From(uB.ID())
for toB.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{i, indexOfB[toB.Node().ID()]}, dims)],
))
}
toA := a.From(uA.ID())
for toA.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{indexOfA[toA.Node().ID()], j}, dims)],
))
}
}
toA := a.From(uA.ID())
for toA.Next() {
for j, uB := range bNodes {
toB := b.From(uB.ID())
for toB.Next() {
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, j}, dims)],
product[combin.IdxFor([]int{indexOfA[toA.Node().ID()], indexOfB[toB.Node().ID()]}, dims)],
))
}
}
}
}
}
// CoNormal constructs the Co-normal product of a and b in dst.
//
// The Co-normal product of G₁ and G₂, G₁*G₂ has edges (u₁, u₂)~(v₁, v₂) when
// u₁~v₁ or u₂~v₂.
func CoNormal(dst graph.Builder, a, b graph.Graph) {
aNodes, bNodes, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
indexOfA := indexOf(aNodes)
indexOfB := indexOf(bNodes)
for _, p := range product {
dst.AddNode(p)
}
dims := []int{len(aNodes), len(bNodes)}
p := make([]int, 2)
for i, u := range aNodes {
to := a.From(u.ID())
for to.Next() {
j := indexOfA[to.Node().ID()]
gen := combin.NewCartesianGenerator([]int{len(bNodes), len(bNodes)})
for gen.Next() {
p = gen.Product(p)
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{i, p[0]}, dims)],
product[combin.IdxFor([]int{j, p[1]}, dims)],
))
}
}
}
for i, u := range bNodes {
to := b.From(u.ID())
for to.Next() {
j := indexOfB[to.Node().ID()]
gen := combin.NewCartesianGenerator([]int{len(aNodes), len(aNodes)})
for gen.Next() {
p = gen.Product(p)
dst.SetEdge(dst.NewEdge(
product[combin.IdxFor([]int{p[0], i}, dims)],
product[combin.IdxFor([]int{p[1], j}, dims)],
))
}
}
}
}
// Modular constructs the Modular product of a and b in dst.
//
// The Modular product of G₁ and G₂ has edges (u₁, u₂)~(v₁, v₂) when
// (u₁~v₁ and u₂~v₂) or (u₁≁v₁ and u₂≁v₂), and (u₁≠v₁ and u₂≠v₂).
//
// Modular is O(n^2) where n is the order of the Cartesian product
// of a and b.
func Modular(dst graph.Builder, a, b graph.Graph) {
_, _, product := cartesianNodes(a, b)
if len(product) == 0 {
return
}
for _, p := range product {
dst.AddNode(p)
}
_, aUndirected := a.(graph.Undirected)
_, bUndirected := b.(graph.Undirected)
undirected := aUndirected && bUndirected
n := len(product)
if undirected {
n--
}
for i, u := range product[:n] {
var m int
if undirected {
m = i + 1
}
for _, v := range product[m:] {
if u.A.ID() == v.A.ID() || u.B.ID() == v.B.ID() {
// No self-loops.
continue
}
inA := a.Edge(u.A.ID(), v.A.ID()) != nil
inB := b.Edge(u.B.ID(), v.B.ID()) != nil
if inA == inB {
dst.SetEdge(dst.NewEdge(u, v))
}
}
}
}
// cartesianNodes returns the Cartesian product of the nodes in a and b.
func cartesianNodes(a, b graph.Graph) (aNodes, bNodes []graph.Node, product []Node) {
aNodes = lexicalNodes(a)
bNodes = lexicalNodes(b)
lens := []int{len(aNodes), len(bNodes)}
product = make([]Node, combin.Card(lens))
gen := combin.NewCartesianGenerator(lens)
p := make([]int, 2)
for id := int64(0); gen.Next(); id++ {
p = gen.Product(p)
product[id] = Node{UID: id, A: aNodes[p[0]], B: bNodes[p[1]]}
}
return aNodes, bNodes, product
}
// lexicalNodes returns the nodes in g sorted lexically by node ID.
func lexicalNodes(g graph.Graph) []graph.Node {
nodes := graph.NodesOf(g.Nodes())
sort.Sort(ordered.ByID(nodes))
return nodes
}
func indexOf(nodes []graph.Node) map[int64]int {
idx := make(map[int64]int, len(nodes))
for i, n := range nodes {
idx[n.ID()] = i
}
return idx
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.