text
stringlengths 11
4.05M
|
|---|
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
homedir "github.com/mitchellh/go-homedir"
)
var (
errAlreadyExists = errors.New("store: word already exists")
errDoesntExist = errors.New("store: word does not exist")
errNoData = errors.New("entry: contains no data")
errInvalidData = errors.New("entry: invalid data given")
)
type store struct {
file *os.File
entries []entry
}
type entry struct {
word string
desc string
tags []string
}
func newStore(filename string) (*store, error) {
expandedFilename, err := homedir.Expand(filename)
if err != nil {
return nil, err
}
file, err := os.OpenFile(expandedFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
return &store{
file: file,
}, nil
}
func (s *store) load() error {
if s.entries != nil {
return nil
}
s.entries = []entry{}
var (
scanner = bufio.NewScanner(s.file)
e entry
)
for i := 0; scanner.Scan(); i++ {
line := scanner.Text()
switch i % 3 {
case 0:
e.word = line
case 1:
e.desc = line
case 2:
e.tags = strings.Split(line, ",")
s.entries = append(s.entries, e)
e = entry{}
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("store: failed to load: %v", err)
}
return nil
}
func (s *store) add(e entry) error {
for i := range s.entries {
if s.entries[i].word == e.word {
return errAlreadyExists
}
}
if e.word == "" {
return errInvalidData
}
s.file.WriteString(e.word + "\n")
s.file.WriteString(e.desc + "\n")
s.file.WriteString(strings.Join(e.tags, ",") + "\n")
return nil
}
func (s *store) search(term string) (entry, error) {
return entry{}, nil
}
func (s *store) remove(e entry) error {
return nil
}
func (s *store) close() {
s.file.Close()
}
const (
commandAdd = "add"
commandSearch = "search"
commandRemove = "remove"
commandHelp = "help"
)
const (
helpRoot = `Wordy is a personal collection of words that you find interesting or useful in writing.
It helps you keep track of the words you add, intelligently filter through the existing
words, and also tag the words to seperate them into different categories.
Usage: wordy [command]
Commands:
add
Add a new word
search
Search existing words
remove
Remove existing word
help
Displays help
`
helpAdd = `Add a new word
Usage: wordy add
Flags:
-file
File to save to (default: ~/.wordy)
`
helpSearch = `Search existing words
Usage: wordy search
Flags:
-file
File to save to (default: ~/.wordy)
`
helpRemove = `Remove existing word
Usage: wordy remove
Flags:
-file
File to save to (default: ~/.wordy)
-confirm
Confirm before removing (default: true)
`
)
type add struct {
filename string
}
func (add *add) run() {
store, err := newStore(add.filename)
if err != nil {
fmt.Printf("\nError: %v\nFailed!\n", err)
os.Exit(1)
}
defer store.close()
if err := store.load(); err != nil {
fmt.Printf("\nError: %v\nFailed!\n", err)
os.Exit(1)
}
var (
e entry
r = bufio.NewReader(os.Stdin)
)
fmt.Print("Word: ")
e.word = strings.TrimSpace(readLine(r))
fmt.Print("Description: ")
e.desc = strings.TrimSpace(readLine(r))
fmt.Print("Tag(s): ")
e.tags = strings.Split(readLine(r), ",")
for i := range e.tags {
e.tags[i] = strings.TrimSpace(e.tags[i])
}
if err := store.add(e); err != nil {
fmt.Printf("\nError: %v\nFailed!\n", err)
os.Exit(1)
}
}
func readLine(r *bufio.Reader) string {
line, _, err := r.ReadLine()
if err != nil {
fmt.Printf("\nError: %v\nFailed!\n", err)
os.Exit(1)
}
return string(line)
}
type search struct {
filename string
}
func (search *search) run() {
}
type remove struct {
filename string
confirm bool
}
func (remove *remove) run() {
}
func help(args []string) {
if len(args) == 0 {
fmt.Println(helpRoot)
os.Exit(2)
}
switch args[0] {
case commandAdd:
fmt.Println(helpAdd)
case commandSearch:
fmt.Println(helpSearch)
case commandRemove:
fmt.Println(helpRemove)
case commandHelp:
fmt.Println(helpRoot)
default:
fmt.Println(helpRoot)
os.Exit(2)
}
os.Exit(0)
}
func main() {
rootFlagSet := flag.CommandLine
rootFlagSet.SetOutput(ioutil.Discard)
rootFlagSet.Usage = func() {
fmt.Println(helpRoot)
}
add := new(add)
addFlagSet := flag.NewFlagSet(commandAdd, flag.ExitOnError)
addFlagSet.SetOutput(ioutil.Discard)
addFlagSet.Usage = func() {
fmt.Println(helpAdd)
}
addFlagSet.StringVar(&add.filename, "file", "~/.wordy", "")
search := new(search)
searchFlagSet := flag.NewFlagSet(commandSearch, flag.ExitOnError)
searchFlagSet.SetOutput(ioutil.Discard)
searchFlagSet.Usage = func() {
fmt.Println(helpSearch)
}
remove := new(remove)
removeFlagSet := flag.NewFlagSet(commandRemove, flag.ExitOnError)
removeFlagSet.SetOutput(ioutil.Discard)
removeFlagSet.Usage = func() {
fmt.Println(helpRemove)
}
if len(os.Args) < 2 {
fmt.Println(helpRoot)
os.Exit(2)
}
switch os.Args[1] {
case commandAdd:
addFlagSet.Parse(os.Args[2:])
add.run()
case commandSearch:
searchFlagSet.Parse(os.Args[2:])
search.run()
case commandRemove:
removeFlagSet.Parse(os.Args[2:])
remove.run()
case commandHelp:
help(os.Args[2:])
default:
fmt.Println(helpRoot)
os.Exit(2)
}
}
|
/*
Package vugu provides core functionality including vugu->go codegen and in-browser DOM syncing running in WebAssembly. See http://www.vugu.org/
Since Vugu projects can have both client-side (running in WebAssembly) as well as server-side functionality many of the
items in this package are available in both environments. Some however are either only available or only generally useful
in one environment.
Common functionality includes the ComponentType interface, and ComponentInst struct corresponding to an instantiated componnet.
VGNode and related structs are used to represent a virtual Document Object Model. It is based on golang.org/x/net/html but
with additional fields needed for Vugu. Data hashing is performed by ComputeHash() and can be customized by implementing
the DataHasher interface.
Client-side code uses JSEnv to maintain a render loop and regenerate virtual DOM and efficiently synchronize it with
the browser as needed. DOMEvent is a wrapper around events from the browser and EventEnv is used to synchronize data
access when writing event handler code that spawns goroutines. Where appropriate, server-side stubs are available
so components can be compiled for both client (WebAssembly) and server (server-side rendering and testing).
Server-side code can use ParserGo and ParserGoPkg to parse .vugu files and code generate a corresponding .go file.
StaticHTMLEnv can be used to generate static HTML, similar to the output of JSEnv but can be run on the server.
Supported features are approximately the same minus event handling, unapplicable to static output.
*/
package vugu
/*
old notes:
Common
Components and Registration...
VGNode and friends for virtual DOM:
<b>Data hashing is perfomed with the ComputeHash() function.<b> <em>It walks your data structure</en> and hashes the information as it goes.
It uses xxhash internally and returns a uint64. It is intended to be both fast and have good hash distribution to avoid
collision-related bugs.
someData := &struct{A string}{A:"test"}
hv := ComputeHash(someData)
If the DataHasher interface is implemented by a particular type then ComputeHash will just called it and hash it's return
into the calculation. Otherwise ComputeHash walks the data and finds primitive values and hashes them byte by bytes.
Nil interfaces and nil pointers are skipped.
Effective hashing is an important part of achieving good performance in Vugu applications, since the question "is this different
than it was before" needs to be asked frequently. The current experiment is to rely entirely on data hashing for change detection
rather than implementing a data-binding system.
*/
|
package main
import (
"github.com/gomodule/redigo/redis"
)
const LuaScript string = `
local ticket_key = KEYS[1]
local ticket_total_key = ARGV[1]
local ticket_sold_key = ARGV[2]
local ticket_total_nums = tonumber(redis.call('HGET', ticket_key, ticket_total_key))
local ticket_sold_nums = tonumber(redis.call('HGET', ticket_key, ticket_sold_key))
-- 查看是否有余票, 增加订单数量, 返回结果值
if (ticket_sold_nums > ticket_total_nums) then
return redis.call('HINCRBY', ticket_key, ticket_sold_key, 1)
end
return 0
`
// 远程订单存储 key
type RemoteSpikeKeys struct {
SpikeOrderHashKey string // redis 秒杀订单 hash 结构 key
TotalInventoryKey string // hash 结构中总订单库存 key
QuantityOfOrderKey string // hash 结构中已有订单数量 key
}
// 远端统一扣库存
func (remoteSpikeKeys *RemoteSpikeKeys) RemoteDeductionStock(conn redis.Conn) bool {
lua := redis.NewScript(1, LuaScript)
if result, err := redis.Int(lua.Do(conn, remoteSpikeKeys.SpikeOrderHashKey, remoteSpikeKeys.TotalInventoryKey, remoteSpikeKeys.QuantityOfOrderKey)); err != nil {
return false
} else {
return result != 0
}
}
// 初始化 redis 连接池
func NewPool() *redis.Pool {
return &redis.Pool{
Dial: func() (conn redis.Conn, err error) {
if conn, err = redis.Dial("tcp", ":6379"); err != nil {
panic(err.Error())
}
return
},
MaxIdle: 10000,
MaxActive: 12000,
}
}
|
package routingproxy
import (
"bytes"
"io/ioutil"
"net/http"
"regexp"
"strconv"
)
// RequestModifier defines a request and response modifying functions
// and the regex for the paths for which it should be applied
type RequestModifier struct {
MatchingPath string
DisableEncoding bool
RequestModifier func(*http.Request)
ResponseModifier func(*http.Response) error
ResponseBodyModifier func(*http.Response, []byte) []byte
pathRegex *regexp.Regexp
}
// MatchesPath evaluates a given path against the MatchingPath
func (rm *RequestModifier) matchesPath(p string) bool {
return rm.pathRegex.MatchString(p)
}
// ModifyRequest modifies a request if the path matches MatchingPath
func (rm *RequestModifier) modifyRequest(r *http.Request) {
if rm.RequestModifier != nil && rm.matchesPath(r.URL.Path) {
rm.RequestModifier(r)
}
if rm.DisableEncoding {
r.Header.Set("Accept-Encoding", "")
}
}
// ModifyResponse modifies a request if the path matches MatchingPath
func (rm *RequestModifier) modifyResponse(r *http.Response) error {
if rm.matchesPath(r.Request.URL.Path) {
if rm.ResponseModifier != nil {
if err := rm.ResponseModifier(r); err != nil {
return err
}
}
if rm.ResponseBodyModifier != nil {
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
err = r.Body.Close()
if err != nil {
return err
}
bodyBytes = rm.ResponseBodyModifier(r, bodyBytes)
r.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
bodyLength := len(bodyBytes)
r.ContentLength = int64(bodyLength)
r.Header.Set("Content-Length", strconv.Itoa(bodyLength))
}
}
return nil
}
|
package blockingreader
import (
"io"
"strings"
"testing"
"time"
"github.com/rwool/ex/test/helpers/goroutinechecker"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBlockingReader_Cancel(t *testing.T) {
defer goroutinechecker.New(t)()
h := strings.NewReader("hello")
br := NewBlockingReader(3*time.Second, h)
start := time.Now()
buf := make([]byte, 20)
read, err := br.Read(buf)
elapsed := time.Since(start)
require.NoError(t, err)
assert.True(t, elapsed > 3*time.Second && elapsed < 5*time.Second,
"read blocked for wrong amount of time")
assert.Equal(t, "hello", string(buf[:read]), "unexpected output")
read, err = br.Read(buf)
assert.EqualError(t, err, io.EOF.Error())
assert.Equal(t, 0, read)
}
|
package user
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"google.golang.org/grpc"
"net"
"strconv"
"strings"
)
type userServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewUserServer(port int) *userServer {
log.NewPrivateLog("user")
return &userServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImUserName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *userServer) Run() {
log.Info("", "", "rpc user init....")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.InfoByArgs("listen network failed,err=%s", err.Error())
return
}
log.Info("", "", "listen network success, address = %s", registerAddress)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbUser.RegisterUserServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.ErrorByArgs("register rpc token to etcd failed,err=%s", err.Error())
return
}
err = srv.Serve(listener)
if err != nil {
log.ErrorByArgs("listen token failed,err=%s", err.Error())
return
}
log.Info("", "", "rpc token init success")
}
func (s *userServer) GetUserInfo(ctx context.Context, req *pbUser.GetUserInfoReq) (*pbUser.GetUserInfoResp, error) {
log.InfoByKv("rpc get_user_info is server", req.OperationID)
var userInfoList []*pbUser.UserInfo
//Obtain user information according to userID
if len(req.UserIDList) > 0 {
for _, userID := range req.UserIDList {
var userInfo pbUser.UserInfo
user, err := im_mysql_model.FindUserByUID(userID)
if err != nil {
log.ErrorByKv("search userinfo failed", req.OperationID, "userID", userID, "err=%s", err.Error())
continue
}
userInfo.Uid = user.UID
userInfo.Icon = user.Icon
userInfo.Name = user.Name
userInfo.Gender = user.Gender
userInfo.Mobile = user.Mobile
userInfo.Birth = user.Birth
userInfo.Email = user.Email
userInfo.Ex = user.Ex
userInfoList = append(userInfoList, &userInfo)
}
} else {
return &pbUser.GetUserInfoResp{ErrorCode: 999, ErrorMsg: "uidList is nil"}, nil
}
log.InfoByKv("rpc get userInfo return success", req.OperationID, "token", req.Token)
return &pbUser.GetUserInfoResp{
ErrorCode: 0,
ErrorMsg: "",
Data: userInfoList,
}, nil
}
|
package rest_test
import (
"net/http"
"net/http/httptest"
"net/url"
"github.com/go-chi/chi/v5"
"github.com/go-playground/errors"
"github.com/phogolabs/rest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Decode", func() {
var request *http.Request
Describe("JSON", func() {
BeforeEach(func() {
contact := &Contact{Phone: "+188123451"}
request = NewJSONRequest(contact)
})
It("decodes a form request successfully", func() {
entity := Contact{}
Expect(rest.Decode(request, &entity)).To(Succeed())
Expect(entity.Phone).To(Equal("+188123451"))
})
})
Describe("XML", func() {
var contact *Contact
BeforeEach(func() {
contact = &Contact{Phone: "+188123451"}
})
JustBeforeEach(func() {
request = NewXMLRequest(contact)
})
It("decodes a form request successfully", func() {
entity := Contact{}
Expect(rest.Decode(request, &entity)).To(Succeed())
Expect(entity.Phone).To(Equal("+188123451"))
})
Context("when the validation fails", func() {
BeforeEach(func() {
contact = &Contact{Phone: "088HIPPO"}
})
It("returns an error", func() {
entity := Contact{}
err := rest.Decode(request, &entity)
Expect(err).To(HaveOccurred())
err = errors.Cause(err)
Expect(err).To(MatchError("Key: 'Contact.phone' Error:Field validation for 'phone' failed on the 'phone' tag"))
})
})
})
Describe("FORM", func() {
BeforeEach(func() {
v := url.Values{}
v.Add("name", "John")
v.Add("age", "22")
request = NewFormRequest(v)
})
It("decodes a form request successfully", func() {
entity := Person{}
Expect(rest.Decode(request, &entity)).To(Succeed())
Expect(entity.Name).To(Equal("John"))
Expect(entity.Age).To(BeEquivalentTo(22))
})
})
Context("when the Content-Tyoe is UNKNOWN", func() {
BeforeEach(func() {
contact := &Contact{Phone: "+188123451"}
request = NewGobRequest(contact)
})
It("returns an error", func() {
entity := Contact{}
err := rest.Decode(request, &entity)
Expect(err).To(HaveOccurred())
})
})
})
var _ = Describe("DecodePath", func() {
var request *http.Request
type User struct {
ID int `path:"id"`
}
BeforeEach(func() {
request = httptest.NewRequest("POST", "http://example.com/users/1", nil)
})
It("decodes the request successfully", func() {
router := chi.NewMux()
router.Mount("/users/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := User{}
Expect(rest.DecodePath(r, &user)).To(Succeed())
Expect(user.ID).To(Equal(1))
}))
router.ServeHTTP(httptest.NewRecorder(), request)
})
Context("when the types are incompatible", func() {
BeforeEach(func() {
request = httptest.NewRequest("POST", "http://example.com/users/root", nil)
})
It("returns an error", func() {
router := chi.NewMux()
router.Mount("/users/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := User{}
Expect(rest.DecodePath(r, &user)).To(MatchError("Field Namespace:id ERROR:Invalid Integer Value 'root' Type 'int' Namespace 'id'"))
}))
router.ServeHTTP(httptest.NewRecorder(), request)
})
})
})
var _ = Describe("DecodeQuery", func() {
var request *http.Request
type User struct {
ID int `query:"id"`
}
BeforeEach(func() {
request = httptest.NewRequest("POST", "http://example.com/?id=1", nil)
})
It("decodes the request successfully", func() {
user := User{}
Expect(rest.DecodeQuery(request, &user)).To(Succeed())
Expect(user.ID).To(Equal(1))
})
Context("when the types are incompatible", func() {
BeforeEach(func() {
request = httptest.NewRequest("POST", "http://example.com/?id=root", nil)
})
It("returns an error", func() {
user := User{}
Expect(rest.DecodeQuery(request, &user)).To(MatchError("Field Namespace:id ERROR:Invalid Integer Value 'root' Type 'int' Namespace 'id'"))
})
})
})
var _ = Describe("DecodeHeader", func() {
var request *http.Request
type User struct {
ID int `header:"X-User-Id"`
}
BeforeEach(func() {
request = httptest.NewRequest("POST", "http://example.com", nil)
request.Header.Set("X-User-Id", "1")
})
It("decodes the request successfully", func() {
user := User{}
Expect(rest.DecodeHeader(request, &user)).To(Succeed())
Expect(user.ID).To(Equal(1))
})
Context("when the types are incompatible", func() {
BeforeEach(func() {
request.Header.Set("X-User-Id", "root")
})
It("returns an error", func() {
user := User{}
Expect(rest.DecodeHeader(request, &user)).To(MatchError("Field Namespace:X-User-Id ERROR:Invalid Integer Value 'root' Type 'int' Namespace 'X-User-Id'"))
})
})
})
|
package main
import (
"fmt"
)
func main() {
data := map[int]string{1: "go", 2: "java", 3: "javascript"}
// 循环遍历元素,返回第一个元素为键,第二元素为值
for key, value := range data {
fmt.Printf("%d ---> %s\n", key, value)
}
// 判断某一个键是否存在
value, ok := data[2]
if ok {
fmt.Println("键存在,并且值为:", value)
} else {
fmt.Println("不存在的键")
}
// 删除元素
delete(data, 3)
fmt.Println("data = ", data)
// 结果为:
// 1 ---> go
// 2 ---> java
// 3 ---> javascript
// 键存在,并且值为: java
// data = map[2:java 1:go]
}
|
package etcd
import (
"testing"
"github.com/quilt/quilt/db"
"github.com/stretchr/testify/assert"
)
func TestRunLabelOnce(t *testing.T) {
t.Parallel()
store := newTestMock()
conn := db.New()
err := runLabelOnce(conn, store)
assert.Error(t, err)
err = store.Set(labelPath, "", 0)
assert.NoError(t, err)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
etcd := view.InsertEtcd()
etcd.Leader = true
view.Commit(etcd)
label := view.InsertLabel()
label.Label = "Robot"
label.IP = "1.2.3.5"
view.Commit(label)
return nil
})
err = runLabelOnce(conn, store)
assert.NoError(t, err)
str, err := store.Get(labelPath)
assert.NoError(t, err)
expStr := `[
{
"Label": "Robot",
"IP": "1.2.3.5",
"ContainerIPs": null
}
]`
assert.Equal(t, expStr, str)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
etcd := view.SelectFromEtcd(nil)[0]
etcd.Leader = false
view.Commit(etcd)
label := view.SelectFromLabel(nil)[0]
label.IP = "1.2.3.4"
view.Commit(label)
return nil
})
err = runLabelOnce(conn, store)
assert.NoError(t, err)
explabel := db.Label{
Label: "Robot",
IP: "1.2.3.5",
}
labels := conn.SelectFromLabel(nil)
assert.Len(t, labels, 1)
labels[0].ID = 0
assert.Equal(t, explabel, labels[0])
err = runLabelOnce(conn, store)
assert.NoError(t, err)
labels = conn.SelectFromLabel(nil)
assert.Len(t, labels, 1)
labels[0].ID = 0
assert.Equal(t, explabel, labels[0])
}
|
/*
Copyright TokenID 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
// PBM ChainCode Chaincode implementation
type passportChainCode struct {
}
type passport struct {
ProviderEnrollmentID string `json:"providerEnrollmentID"` //Mundane passport ID - passport Provider given
passportCode string `json:"passportCode"` //Issuer given passport ID
passportTypeCode string `json:"passportTypeCode"` //Virtual passport Type Code (Issuer defined) - gotten from TCert
IssuerID string `json:"issuerID"` //Virtual passport IssuerID - gotten from TCert
IssuerCode string `json:"issuerCode"` //Virtual passport Issuer Code - gotten from TCert
IssuerBorderManagement string `json:"issuerBorderManagement"` //Virtual passport Issuer Border Management - gotten from TCert or Ecert
EncryptedPayload string `json:"encryptedPayload"` // Encrypted Virtual passport (EVI) payload
EncryptedKey string `json:"encryptedKey"` //Symmetric encryption key for EVI payload encrypted with the public key
MetaData string `json:"metaData"` //Miscellanous passport Information - ONLY NON-SENSITIVE passport INFORMATION/ATTRIBUTES SHOULD BE ADDED
EncryptedAttachmentURI string `json:"encryptedAttachmentURI"` //Encrypted URIs to Virtual passport Document e.g. Scanned document image
CreatedBy string `json:"createdBy"` //passport Creator
CreatedOnTxTimestamp int64 `json:"createdOnTxTimestamp"` //Created on Timestamp - which is currently taken from the peer receiving the transaction. Note that this timestamp may not be the same with the other peers' time.
LastUpdatedBy string `json:"lastUpdatedBy"` //Last Updated By
LastUpdatedOnTxTimestamp int64 `json:"lastUpdatedOnTxTimestamp"` //Last Updated On Timestamp - which is currently taken from the peer receiving the transaction. Note that this timestamp may not be the same with the other peers' time.
IssuerVerified bool `json:"issuerVerified"` //passport verified by Issuer
}
type passportMin struct {
ProviderEnrollmentID string `json:"providerEnrollmentID"`
passportCode string `json:"passportCode"`
passportTypeCode string `json:"passportTypeCode"`
IssuerCode string `json:"issuerCode"`
IssuerID string `json:"issuerID"`
IssuerBorderManagement string `json:"issuerBorderManagement"`
CreatedBy string `json:"createdBy"`
CreatedOnTxTimestamp int64 `json:"createdOnTxTimestamp"`
LastUpdatedBy string `json:"lastUpdatedBy"`
LastUpdatedOnTxTimestamp int64 `json:"lastUpdatedOnTxTimestamp"`
IssuerVerified bool `json:"issuerVerified"`
}
//States key prefixes
const PUBLIC_KEY_PREFIX = "_PK"
const passport_TBL_PREFIX = "_TABLE"
const ISSUER_TBL_NAME = "ISSUERS_TABLE"
//"EVENTS"
const EVENT_NEW_passport_ENROLLED = "EVENT_NEW_passport_ENROLLED"
const EVENT_NEW_passport_ISSUED = "EVENT_NEW_passport_ISSUED"
const EVENT_NEW_ISSUER_ENROLLED = "EVENT_NEW_ISSUER_ENROLLED"
//ROLES
const ROLE_ISSUER = "Issuer"
const ROLE_PROVIDER = "Provider"
const ROLE_USER = "User"
var logger = shim.NewLogger("passportChaincode")
// ============================================================================================================================
// Main
// ============================================================================================================================
func main() {
err := shim.Start(new(passportChainCode))
if err != nil {
fmt.Printf("Error starting passport ChainCode: %s", err)
}
}
//=================================================================================================================================
// Ping Function
//=================================================================================================================================
// Pings the peer to keep the connection alive
//=================================================================================================================================
func (t *passportChainCode) Ping(stub shim.ChaincodeStubInterface) ([]byte, error) {
return []byte("Hi, I'm up!"), nil
}
//=================================================================================================================================
//Initializes chaincode when deployed
//=================================================================================================================================
func (t *passportChainCode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2 -> [providerEnrollmentID, passportPublicKey]")
}
//Create initial passport table
fmt.Println("Initializing passport for ->" + args[0])
val, err := t.Initpassport(stub, args, true)
if err != nil {
fmt.Println(err)
}
return val, err
}
//=================================================================================================================================
//Initializes the passport and sets the default states
//=================================================================================================================================
func (t *passportChainCode) Initpassport(stub shim.ChaincodeStubInterface, args []string, isDeploymentCall bool) ([]byte, error) {
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2 -> [providerEnrollmentID , passportPublicKey]")
}
//Check if user is provider
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
isProv := isProvider(callerDetails)
if isProv == false && isDeploymentCall == false { //If its a deployment call, TCert info will not be transmitted to other peers and the role won't be known
return nil, errors.New("Access Denied")
}
var providerEnrollmentID, passportPublicKey string
providerEnrollmentID = args[0]
passportPublicKey = args[1]
//Verify that Enrollment ID and Pubic key is not null
if providerEnrollmentID == "" || passportPublicKey == "" {
return nil, errors.New("Provider Enrollment ID or Public key cannot be null")
}
//Add Public key state
existingPKBytes, err := stub.GetState(providerEnrollmentID + PUBLIC_KEY_PREFIX)
if err == nil && existingPKBytes != nil {
return nil, fmt.Errorf("Public Key for " + providerEnrollmentID + " already exists ")
}
fmt.Println(passportPublicKey)
pkBytes := []byte(passportPublicKey)
//Validate Public key is PEM format
err = validatePublicKey(pkBytes)
if err != nil {
return nil, fmt.Errorf("Bad Public Key -> Public key must be in PEM format - [%v]", err)
}
//Set Public key state
err = stub.PutState(providerEnrollmentID+PUBLIC_KEY_PREFIX, pkBytes)
if err != nil {
return nil, fmt.Errorf("Failed inserting public key, [%v] -> "+providerEnrollmentID, err)
}
//Create passport Table
err = t.createpassportTable(stub, providerEnrollmentID)
if err != nil {
return nil, fmt.Errorf("Failed creating passport Table, [%v] -> "+providerEnrollmentID, err)
}
//Broadcast 'New Enrollment' Event with enrollment ID
err = stub.SetEvent(EVENT_NEW_passport_ENROLLED, []byte(providerEnrollmentID))
if err != nil {
return nil, fmt.Errorf("Failed to broadcast enrollment event, [%v] -> "+providerEnrollmentID, err)
}
return []byte("Enrollment Successful"), nil
}
//=================================================================================================================================
// Entry point to invoke a chaincode function
//=================================================================================================================================
func (t *passportChainCode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("invoke is running " + function)
var bytes []byte
var err error
fmt.Println("function -> " + function)
// Handle different functions
if function == "init" { //initialize the chaincode state, used as reset
bytes, err = t.Init(stub, "init", args)
} else if function == "addpassport" {
bytes, err = t.Addpassport(stub, args)
} else if function == "removepassport" {
bytes, err = t.Removepassport(stub, args)
} else {
fmt.Println("invoke did not find func: " + function) //error
return nil, errors.New("Received unknown function invocation: " + function)
}
if err != nil {
fmt.Println(err)
}
return bytes, err
}
//=================================================================================================================================
// Query is our entry point for queries
//=================================================================================================================================
func (t *passportChainCode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("query is running " + function)
// Handle different functions
var bytes []byte
var err error
fmt.Println("function -> " + function)
if function == "ping" {
bytes, err = t.Ping(stub)
} else if function == "getPassports" {
bytes, err = t.GetPassports(stub, args)
} else if function == "getpassport" {
bytes, err = t.Getpassport(stub, args)
} else if function == "getPublicKey" {
bytes, err = t.GetPublicKey(stub, args)
} else {
fmt.Println("query did not find func: " + function) //error
return nil, errors.New("Received unknown function query: " + function)
}
if err != nil {
fmt.Println(err)
}
return bytes, err
}
//=================================================================================================================================
// Create passport table
//=================================================================================================================================
//Create passport Table
func (t *passportChainCode) createpassportTable(stub shim.ChaincodeStubInterface, enrollmentID string) error {
var tableName string
tableName = enrollmentID + passport_TBL_PREFIX
// Create passport table
tableErr := stub.CreateTable(tableName, []*shim.ColumnDefinition{
&shim.ColumnDefinition{Name: "ProviderEnrollmentID", Type: shim.ColumnDefinition_STRING, Key: false},
&shim.ColumnDefinition{Name: "passportCode", Type: shim.ColumnDefinition_STRING, Key: true},
&shim.ColumnDefinition{Name: "passportTypeCode", Type: shim.ColumnDefinition_STRING, Key: true},
&shim.ColumnDefinition{Name: "EncryptedPayload", Type: shim.ColumnDefinition_BYTES, Key: false},
&shim.ColumnDefinition{Name: "IssuerCode", Type: shim.ColumnDefinition_STRING, Key: true},
&shim.ColumnDefinition{Name: "IssuerID", Type: shim.ColumnDefinition_STRING, Key: true},
&shim.ColumnDefinition{Name: "IssuerBorderManagement", Type: shim.ColumnDefinition_STRING, Key: false},
&shim.ColumnDefinition{Name: "EncryptedKey", Type: shim.ColumnDefinition_BYTES, Key: false},
&shim.ColumnDefinition{Name: "Metadata", Type: shim.ColumnDefinition_STRING, Key: false},
&shim.ColumnDefinition{Name: "IssuerVerified", Type: shim.ColumnDefinition_BOOL, Key: false},
&shim.ColumnDefinition{Name: "EncryptedAttachmentURI", Type: shim.ColumnDefinition_BYTES, Key: false},
&shim.ColumnDefinition{Name: "CreatedBy", Type: shim.ColumnDefinition_STRING, Key: false},
&shim.ColumnDefinition{Name: "CreatedOnTxTimeStamp", Type: shim.ColumnDefinition_INT64, Key: false},
&shim.ColumnDefinition{Name: "LastUpdatedBy", Type: shim.ColumnDefinition_STRING, Key: false},
&shim.ColumnDefinition{Name: "lastUpdatedOnTxTimeStamp", Type: shim.ColumnDefinition_INT64, Key: false},
})
if tableErr != nil {
return fmt.Errorf("Failed creating passportTable table, [%v] -> "+enrollmentID, tableErr)
}
return nil
}
//=================================================================================================================================
// Add New Issued passport
//=================================================================================================================================
func (t *passportChainCode) Addpassport(stub shim.ChaincodeStubInterface, passportParams []string) ([]byte, error) {
//Get Caller Details
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
//Check if Tcert has a valid role
validRoles := hasValidRoles(callerDetails)
if validRoles == false {
return nil, fmt.Errorf("Access denied. Unknown role in Tcert -> " + callerDetails.role)
}
if len(passportParams) < 10 {
return nil, errors.New("Incomplete number of arguments. Expected 10 -> [ProviderEnrollmentID, passportCode, passportTypeCode, EncryptedpassportPayload, EncryptionKey, IssuerID, MetaData, EncryptedAttachmentURI, IssuerCode, IssuerBorderManagement ]")
}
if strings.EqualFold(callerDetails.role, ROLE_ISSUER) == false && strings.EqualFold(callerDetails.role, ROLE_PROVIDER) == false {
return nil, errors.New("Access Denied. Not a provider or Issuer")
}
isProvider := isProvider(callerDetails)
var issuerCode, issuerBorderManagement, issuerID string
issuerVerified := false
//For providers, issuer details are required to be submitted
//Parameters should be in the order -> [ProviderEnrollmentID, passportCode, passportTypeCode, EncryptedpassportPayload, EncryptionKey, IssuerID, MetaData, EncryptedAttachmentURI, IssuerCode, IssuerBorderManagement ]
if isProvider == true {
//Check for empty mandatory fields (first 5 fields)
for i := 0; i < 6; i++ {
if passportParams[i] == "" {
return nil, errors.New("One or more mandatory fields is empty. Mandatory fields are the first 5 which are ProviderEnrollmentID, passportCode, passportTypeCode, passportPayload and IssuerID")
}
}
issuerID = passportParams[5]
issuerCode = passportParams[8]
issuerBorderManagement = passportParams[9]
} else {
//Issuer details are gotten from Transaction Certificate
//Check for empty mandatory fields
for i := 0; i < 5; i++ {
if passportParams[i] == "" {
return nil, errors.New("One or more mandatory fields is empty. Mandatory fields are the first 4 which are ProviderEnrollmentID, passportCode, passportTypeCode and passportPayload")
}
}
issuerID = callerDetails.issuerID
issuerCode = callerDetails.issuerCode
issuerBorderManagement = callerDetails.BorderManagement
//Verified, since the passport is created by the issuer
issuerVerified = true
}
if isProvider == false && (issuerCode == "" || issuerID == "" || issuerBorderManagement == "") {
return nil, errors.New("One of the required fields are not available in transaction certificate [issuerCode, issuerID, BorderManagement] -> [" + issuerID + ", " + issuerID + "," + issuerBorderManagement + "]")
}
//Validate passport Type code
passportTypeCode := passportParams[2]
isValid, err := validatepassportTypeCode(passportTypeCode)
if err != nil {
fmt.Println(err)
return nil, fmt.Errorf("Could not validate passportTypeCode -> [%v]", err)
}
if isValid == false {
return nil, fmt.Errorf("Invalid passportTypeCode. Must contain only AlphaNumeric characters, minimum length of 4 and maximum of 10")
}
providerEnrollmentID := passportParams[0]
passportCode := passportParams[1]
//Encrypted Payload
encryptedPayload, err := decodeBase64(passportParams[3])
if err != nil {
return nil, fmt.Errorf("Bad Encrypted Payload [%v] ", err)
}
//Encrypted Key
encryptedKey, err := decodeBase64(passportParams[4])
if err != nil {
return nil, fmt.Errorf("Bad Encrypted Key [%v] ", err)
}
//Encrypted Attachment
encryptedAttachmentURIString := passportParams[7]
var encryptedAttachmentURI []byte
if encryptedAttachmentURIString != "" {
encryptedAttachmentURI, err = decodeBase64(passportParams[7])
if err != nil {
return nil, fmt.Errorf("Bad Encrypted AttachmentURI [%v] ", err)
}
}
//Check if similar passport exists
var key2columns []shim.Column
key2Col1 := shim.Column{Value: &shim.Column_String_{String_: passportCode}}
//key2Col2 := shim.Column{Value: &shim.Column_String_{String_: passportTypeCode}}
//key2Col3 := shim.Column{Value: &shim.Column_String_{String_: issuerID}}
key2columns = append(key2columns, key2Col1)
tableName := providerEnrollmentID + passport_TBL_PREFIX
rows, err := getRows(&stub, tableName, key2columns)
if err != nil {
return nil, fmt.Errorf("Error checking for existing passport, [%v]", err)
}
if len(rows) > 0 {
rowPointer := rows[0]
row := *rowPointer
return nil, fmt.Errorf("passport already exists -> " + row.Columns[1].GetString_() + "|" + row.Columns[2].GetString_() + "|" + row.Columns[5].GetString_())
}
//Get Transaction TimeStamp
stampPointer, err := stub.GetTxTimestamp()
if err != nil {
return nil, fmt.Errorf("Could not get Transaction timestamp from peer, [%v]", err)
}
//Save passport
timestamp := *stampPointer
_, err = stub.InsertRow(
tableName,
shim.Row{
Columns: []*shim.Column{
&shim.Column{Value: &shim.Column_String_{String_: providerEnrollmentID}},
&shim.Column{Value: &shim.Column_String_{String_: passportCode}},
&shim.Column{Value: &shim.Column_String_{String_: passportTypeCode}},
&shim.Column{Value: &shim.Column_Bytes{Bytes: encryptedPayload}},
&shim.Column{Value: &shim.Column_String_{String_: issuerCode}},
&shim.Column{Value: &shim.Column_String_{String_: issuerID}},
&shim.Column{Value: &shim.Column_String_{String_: issuerBorderManagement}},
&shim.Column{Value: &shim.Column_Bytes{Bytes: encryptedKey}},
&shim.Column{Value: &shim.Column_String_{String_: passportParams[6]}},
&shim.Column{Value: &shim.Column_Bool{Bool: issuerVerified}},
&shim.Column{Value: &shim.Column_Bytes{Bytes: encryptedAttachmentURI}},
&shim.Column{Value: &shim.Column_String_{String_: callerDetails.user}},
&shim.Column{Value: &shim.Column_Int64{Int64: timestamp.Seconds}},
&shim.Column{Value: &shim.Column_String_{String_: ""}},
&shim.Column{Value: &shim.Column_Int64{Int64: 0}},
},
})
fmt.Println(err)
if err != nil {
return nil, fmt.Errorf("Could not get save passport, [%v]", err)
}
eventPayload := providerEnrollmentID + "|" + passportCode
//Broadcast 'New ID Issued'
err = stub.SetEvent(EVENT_NEW_passport_ISSUED, []byte(eventPayload))
fmt.Println(err)
if err != nil {
return nil, fmt.Errorf("Failed to setevent EVENT_NEW_passport_ISSUED, [%v] -> "+eventPayload, err)
}
return nil, nil
}
func (t *passportChainCode) Removepassport(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
//Get Caller Details
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
//Check if Tcert has a valid role
validRoles := hasValidRoles(callerDetails)
if validRoles == false {
return nil, fmt.Errorf("Access denied. Unknown role in Tcert -> " + callerDetails.role)
}
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 1 -> [enrollmentID, passportCode]")
}
enrollmentID := args[0]
passportCode := args[1]
isProv := isProvider(callerDetails)
isUser := isUser(callerDetails)
if isUser == true && callerDetails.userEnrollmentID != args[0] {
errmsg := "Access Denied. User Role found in TCert but Enrollment ID on certificate don't match"
fmt.Println(errmsg + "->" + callerDetails.userEnrollmentID)
return nil, fmt.Errorf(errmsg)
}
var columns []shim.Column = []shim.Column{}
keyCol1 := shim.Column{Value: &shim.Column_String_{String_: passportCode}}
columns = append(columns, keyCol1)
if isProv == false && isUser == false {
keyCol2 := shim.Column{Value: &shim.Column_String_{String_: callerDetails.issuerID}}
columns = append(columns, keyCol2)
}
tableName := enrollmentID + passport_TBL_PREFIX
rowPointers, err := getRows(&stub, tableName, columns)
if err != nil {
return nil, fmt.Errorf("Error Getting passport, [%v]", err)
}
if len(rowPointers) == 0 {
return nil, fmt.Errorf("passport does not exist")
}
row := *rowPointers[0]
err = stub.DeleteRow(tableName, []shim.Column{
shim.Column{Value: &shim.Column_String_{String_: row.Columns[1].GetString_()}},
shim.Column{Value: &shim.Column_String_{String_: row.Columns[2].GetString_()}},
shim.Column{Value: &shim.Column_String_{String_: row.Columns[4].GetString_()}},
shim.Column{Value: &shim.Column_String_{String_: row.Columns[5].GetString_()}},
})
if err != nil {
return nil, fmt.Errorf("Error deleting passport, [%v] -> "+enrollmentID+"|"+passportCode, err)
}
return []byte("passport successfully removed"), nil
}
func (t *passportChainCode) GetPassports(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
//Get Caller Details
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
//Check if Tcert has a valid role
validRoles := hasValidRoles(callerDetails)
if validRoles == false {
return nil, fmt.Errorf("Access denied. Unknown role in Tcert -> " + callerDetails.role)
}
if len(args) < 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1 -> [enrollmentID]")
}
enrollmentID := args[0]
isProv := isProvider(callerDetails)
isUser := isUser(callerDetails)
if isUser == true && callerDetails.userEnrollmentID != args[0] {
errmsg := "Access Denied. User Role found in TCert but Enrollment ID on certificate don't match"
fmt.Println(errmsg + "->" + callerDetails.userEnrollmentID)
return nil, fmt.Errorf(errmsg)
}
var columns []shim.Column = []shim.Column{}
if isProv == false && isUser == false { //Its Issuer
keyCol1 := shim.Column{Value: &shim.Column_String_{String_: callerDetails.issuerID}}
columns = append(columns, keyCol1)
}
tableName := enrollmentID + passport_TBL_PREFIX
rowPointers, err := getRows(&stub, tableName, columns)
if err != nil {
return nil, fmt.Errorf("Error Getting Passports, [%v]", err)
}
var passports []passportMin
for _, rowPointer := range rowPointers {
row := *rowPointer
var passport = passportMin{}
passport.ProviderEnrollmentID = enrollmentID
passport.passportCode = row.Columns[1].GetString_()
passport.passportTypeCode = row.Columns[2].GetString_()
passport.IssuerCode = row.Columns[4].GetString_()
passport.IssuerID = row.Columns[5].GetString_()
passport.IssuerBorderManagement = row.Columns[6].GetString_()
passport.CreatedBy = row.Columns[11].GetString_()
passport.CreatedOnTxTimestamp = row.Columns[12].GetInt64()
passport.LastUpdatedBy = row.Columns[13].GetString_()
passport.LastUpdatedOnTxTimestamp = row.Columns[14].GetInt64()
passport.IssuerVerified = row.Columns[9].GetBool()
passports = append(passports, passport)
}
jsonRp, err := json.Marshal(passports)
if err != nil {
return nil, fmt.Errorf("Error Getting Passports, [%v]", err)
}
fmt.Println(string(jsonRp))
return jsonRp, nil
}
func (t *passportChainCode) Getpassport(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
//Get Caller Details
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
//Check if Tcert has a valid role
validRoles := hasValidRoles(callerDetails)
if validRoles == false {
return nil, fmt.Errorf("Access denied. Unknown role in Tcert -> " + callerDetails.role)
}
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 1 -> [enrollmentID, passportCode]")
}
enrollmentID := args[0]
passportCode := args[1]
isProv := isProvider(callerDetails)
isUser := isUser(callerDetails)
if isUser == true && callerDetails.userEnrollmentID != args[0] {
errmsg := "Access Denied. User Role found in TCert but Enrollment ID on certificate don't match"
fmt.Println(errmsg + "->" + callerDetails.userEnrollmentID)
return nil, fmt.Errorf(errmsg)
}
var columns []shim.Column = []shim.Column{}
keyCol1 := shim.Column{Value: &shim.Column_String_{String_: passportCode}}
columns = append(columns, keyCol1)
if isProv == false && isUser == false {
keyCol2 := shim.Column{Value: &shim.Column_String_{String_: callerDetails.issuerID}}
columns = append(columns, keyCol2)
}
tableName := enrollmentID + passport_TBL_PREFIX
rowPointers, err := getRows(&stub, tableName, columns)
if err != nil {
return nil, fmt.Errorf("Error Getting passport, [%v]", err)
}
row := *rowPointers[0]
var passport = passport{}
passport.ProviderEnrollmentID = enrollmentID
passport.passportCode = row.Columns[1].GetString_()
passport.passportTypeCode = row.Columns[2].GetString_()
passport.EncryptedPayload = encodeBase64(row.Columns[3].GetBytes())
passport.IssuerCode = row.Columns[4].GetString_()
passport.IssuerID = row.Columns[5].GetString_()
passport.IssuerBorderManagement = row.Columns[6].GetString_()
passport.EncryptedKey = encodeBase64(row.Columns[7].GetBytes())
passport.MetaData = row.Columns[8].GetString_()
passport.IssuerVerified = row.Columns[9].GetBool()
passport.EncryptedAttachmentURI = encodeBase64(row.Columns[10].GetBytes())
passport.CreatedBy = row.Columns[11].GetString_()
passport.CreatedOnTxTimestamp = row.Columns[12].GetInt64()
passport.LastUpdatedBy = row.Columns[13].GetString_()
passport.LastUpdatedOnTxTimestamp = row.Columns[14].GetInt64()
jsonRp, err := json.Marshal(passport)
if err != nil {
return nil, fmt.Errorf("Error Getting passport, [%v]", err)
}
return jsonRp, nil
}
func (t *passportChainCode) GetPublicKey(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
//Get Caller Details
callerDetails, err := readCallerDetails(&stub)
if err != nil {
return nil, fmt.Errorf("Error getting caller details, [%v]", err)
}
//Check if Tcert has a valid role
validRoles := hasValidRoles(callerDetails)
if validRoles == false {
return nil, fmt.Errorf("Access denied. Unknown role in Tcert -> " + callerDetails.role)
}
if len(args) < 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1 -> [enrollmentID]")
}
enrollmentID := args[0]
//Verify that Enrollment ID and Pubic key is not null
if enrollmentID == "" {
return nil, errors.New("Provider Enrollment ID required")
}
//Add Public key state
existingPKBytes, err := stub.GetState(enrollmentID + PUBLIC_KEY_PREFIX)
if err != nil {
return nil, fmt.Errorf("Public Key for " + enrollmentID + " does not exist")
}
return existingPKBytes, nil
}
|
package game_map
import (
"github.com/steelx/go-rpg-cgm/gui"
"github.com/steelx/tilepix"
)
func mapTown(gStack *gui.StateStack) MapInfo {
gMap, err := tilepix.ReadFile("map_town.tmx")
logFatalErr(err)
return MapInfo{
Tilemap: gMap,
CollisionLayer: 2,
CollisionLayerName: "02 Collision",
HiddenLayer: "",
Actions: nil,
TriggerTypes: nil,
Triggers: nil,
OnWake: nil,
}
}
|
package rpc
const ntag = 255
func (c *Client) aqcuireTag() uint8 {
if c.tags == nil {
c.tags = make(chan uint8, ntag)
for i := uint8(0); i < ntag; i++ {
c.tags <- i
}
}
return <-c.tags
}
func (c *Client) releaseTag(tag uint8) {
c.tags <- tag
}
|
package logfmt
import (
"bytes"
"encoding/json"
"fmt"
"path/filepath"
"strings"
"unicode"
"github.com/bingoohuang/golog/pkg/caller"
"github.com/bingoohuang/golog/pkg/gid"
"github.com/bingoohuang/golog/pkg/spec"
"github.com/bingoohuang/golog/pkg/str"
"github.com/bingoohuang/golog/pkg/timex"
"github.com/sirupsen/logrus"
)
// Layout describes the parsed layout of expression.
type Layout struct {
Parts []Part
}
func (l Layout) Append(b *bytes.Buffer, e Entry) {
for _, p := range l.Parts {
p.Append(b, e)
}
}
type Part interface {
Append(*bytes.Buffer, Entry)
}
type LiteralPart string
func (l LiteralPart) Append(b *bytes.Buffer, _ Entry) {
b.WriteString(string(l))
}
func (l *Layout) addLiteralPart(part string) {
l.addPart(LiteralPart(part))
}
func (l *Layout) addPart(p Part) {
l.Parts = append(l.Parts, p)
}
// NewLayout creates a new layout from string expression.
func NewLayout(layout string) (*Layout, error) {
l := &Layout{}
percentPos := 0
for layout != "" && percentPos >= 0 {
percentPos = strings.Index(layout, "%")
if percentPos < 0 {
l.addLiteralPart(layout)
continue
}
if percentPos > 0 {
l.addLiteralPart(layout[:percentPos])
}
layout = layout[percentPos+1:]
if strings.HasPrefix(layout, "%") {
l.addLiteralPart("%")
layout = layout[1:]
continue
}
minus := false
digits := ""
indicator := ""
options := ""
var err error
layout, minus = parseMinus(layout)
layout, digits = parseDigits(layout)
layout, indicator = parseIndicator(layout)
layout, options, err = parseOptions(layout)
if err != nil {
return nil, err
}
var p Part
switch indicator {
case "t", "time":
p, err = parseTime(minus, digits, options)
case "l", "level":
p, err = parseLevel(minus, digits, options)
case "pid":
p, err = parsePid(minus, digits, options)
case "gid":
p, err = parseGid(minus, digits, options)
case "trace":
p, err = parseTrace(minus, digits, options)
case "caller":
p, err = parseCaller(minus, digits, options)
case "fields":
p, err = parseFields(minus, digits, options)
case "message", "msg", "m":
p, err = parseMessage(minus, digits, options)
case "n":
p, err = parseNewLine(minus, digits, options)
}
if err != nil {
return nil, err
}
l.addPart(p)
}
return l, nil
}
type NewLinePart struct {
}
func (n NewLinePart) Append(b *bytes.Buffer, e Entry) {
b.WriteString("\n")
}
func parseNewLine(minus bool, digits string, options string) (Part, error) {
return &NewLinePart{}, nil
}
type MessagePart struct {
SingleLine bool
}
func (p MessagePart) Append(b *bytes.Buffer, e Entry) {
// indent multiple lines log
msg := e.Message()
msg = strings.TrimRight(msg, "\r\n")
if p.SingleLine {
// indent multiple lines log
b.WriteString(strings.Replace(msg, "\n", `\n `, -1))
} else {
b.WriteString(msg)
}
}
func parseMessage(minus bool, digits string, options string) (Part, error) {
p := &MessagePart{SingleLine: true}
fields := strings.FieldsFunc(options, func(c rune) bool {
return unicode.IsSpace(c) || c == ','
})
for _, f := range fields {
parts := strings.SplitN(f, "=", 2)
k := ""
v := ""
if len(parts) > 0 {
k = strings.ToLower(parts[0])
}
if len(parts) > 1 {
v = parts[1]
}
switch k {
case "singleline":
p.SingleLine = str.ParseBool(v, true)
}
}
return p, nil
}
type FieldsPart struct {
}
func (p FieldsPart) Append(b *bytes.Buffer, e Entry) {
if fields := e.Fields(); len(fields) > 0 {
if v, err := json.Marshal(fields); err == nil {
b.Write(v)
}
}
}
func parseFields(minus bool, digits string, options string) (Part, error) {
return &FieldsPart{}, nil
}
type CallerPart struct {
Digits string
Level logrus.Level
Sep string
}
func (p CallerPart) Append(b *bytes.Buffer, e Entry) {
ll, _ := logrus.ParseLevel(e.Level())
if ll > p.Level {
return
}
fileLine := "-"
c := e.Caller()
if c == nil {
c = caller.GetCaller()
}
if c != nil {
fileLine = fmt.Sprintf("%s%s%d", filepath.Base(c.File), p.Sep, c.Line)
}
b.WriteString(fmt.Sprintf("%"+p.Digits+"s", fileLine))
}
func parseCaller(minus bool, digits string, options string) (Part, error) {
c := &CallerPart{Digits: compositeDigits(minus, digits, "")}
fields := strings.FieldsFunc(options, func(c rune) bool {
return unicode.IsSpace(c) || c == ','
})
level := ""
for _, f := range fields {
parts := strings.SplitN(f, "=", 2)
k := ""
v := ""
if len(parts) > 0 {
k = strings.ToLower(parts[0])
}
if len(parts) > 1 {
v = parts[1]
}
switch k {
case "level":
level = v
case "sep":
c.Sep = v
}
}
c.Level, _ = logrus.ParseLevel(str.Or(level, "warn"))
c.Sep = str.Or(c.Sep, ":")
return c, nil
}
type TracePart struct {
Digits string
}
func (t TracePart) Append(b *bytes.Buffer, e Entry) {
b.WriteString(fmt.Sprintf("%"+t.Digits+"s", e.TraceID()))
}
func parseTrace(minus bool, digits string, options string) (Part, error) {
p := &TracePart{Digits: compositeDigits(minus, digits, "")}
return p, nil
}
type GidPart struct {
Digits string
}
func (p GidPart) Append(b *bytes.Buffer, e Entry) {
b.WriteString(fmt.Sprintf("%"+p.Digits+"s", gid.CurGoroutineID()))
}
func parseGid(minus bool, digits string, options string) (Part, error) {
p := &GidPart{Digits: compositeDigits(minus, digits, "")}
return p, nil
}
type PidPart struct {
Digits string
}
func (p PidPart) Append(b *bytes.Buffer, e Entry) {
b.WriteString(fmt.Sprintf("%d ", Pid))
}
func parsePid(minus bool, digits string, options string) (Part, error) {
p := &PidPart{Digits: compositeDigits(minus, digits, "")}
return p, nil
}
type LevelPart struct {
Digits string
PrintColor bool
LowerCase bool
Length int
}
func (l LevelPart) Append(b *bytes.Buffer, e Entry) {
lvl := strings.ToUpper(str.Or(e.Level(), "info"))
if l.PrintColor {
_, _ = fmt.Fprintf(b, "\x1b[%dm", ColorByLevel(lvl))
}
if strings.ToLower(lvl) == "warning" {
lvl = lvl[:4]
}
if l.Length > 0 && len(lvl) > l.Length {
lvl = lvl[:l.Length]
}
if l.LowerCase {
lvl = strings.ToLower(lvl)
}
b.WriteString(fmt.Sprintf("%"+l.Digits+"s", lvl))
if l.PrintColor { // reset
b.WriteString("\x1b[0m")
}
}
func parseLevel(minus bool, digits string, options string) (Part, error) {
l := &LevelPart{Digits: compositeDigits(minus, digits, "5")}
fields := strings.FieldsFunc(options, func(c rune) bool {
return unicode.IsSpace(c) || c == ','
})
for _, f := range fields {
parts := strings.SplitN(f, "=", 2)
k := ""
v := ""
if len(parts) > 0 {
k = strings.ToLower(parts[0])
}
if len(parts) > 1 {
v = parts[1]
}
switch k {
case "printcolor":
l.PrintColor = str.ParseBool(v, false)
case "lowercase":
l.LowerCase = str.ParseBool(v, false)
case "length":
l.Length = str.ParseInt(v, 0)
}
}
return l, nil
}
func compositeDigits(minus bool, digits, defaultValue string) string {
if digits == "" && defaultValue != "" {
digits = defaultValue
}
if minus {
digits = "-" + digits
}
return digits
}
type Time struct {
Format string
}
func (t Time) Append(b *bytes.Buffer, e Entry) {
b.WriteString(timex.OrNow(e.Time()).Format(t.Format))
}
func parseTime(minus bool, digits string, options string) (Part, error) {
format := spec.ConvertTimeLayout(str.Or(options, "2006-01-02 15:04:05.000"))
return &Time{Format: format}, nil
}
func parseMinus(layout string) (string, bool) {
if strings.HasPrefix(layout, "-") {
return layout[1:], true
}
return layout, false
}
func parseDigits(layout string) (string, string) {
digits := ""
j := 0
for i, r := range layout {
j = i
if unicode.IsDigit(r) || r == '.' {
digits += string(r)
j++
} else {
break
}
}
return layout[j:], digits
}
func parseOptions(layout string) (string, string, error) {
if !strings.HasPrefix(layout, "{") {
return layout, "", nil
}
rightPos := strings.Index(layout, "}")
if rightPos < 0 {
return "", "", fmt.Errorf("bad layout, unclosed brace")
}
return layout[rightPos+1:], layout[1:rightPos], nil
}
func parseIndicator(layout string) (string, string) {
indicator := ""
j := 0
for i, r := range layout {
j = i
if unicode.IsLetter(r) {
indicator += string(r)
j++
} else {
break
}
}
return layout[j:], indicator
}
|
/*
Copyright 2020 Humio https://humio.com
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"
"errors"
"fmt"
"github.com/go-logr/logr"
"github.com/google/go-cmp/cmp"
humioapi "github.com/humio/cli/api"
humiov1alpha1 "github.com/humio/humio-operator/api/v1alpha1"
"github.com/humio/humio-operator/pkg/helpers"
"github.com/humio/humio-operator/pkg/humio"
"github.com/humio/humio-operator/pkg/kubernetes"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// HumioActionReconciler reconciles a HumioAction object
type HumioActionReconciler struct {
client.Client
BaseLogger logr.Logger
Log logr.Logger
HumioClient humio.Client
Namespace string
}
//+kubebuilder:rbac:groups=core.humio.com,resources=humioactions,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core.humio.com,resources=humioactions/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=core.humio.com,resources=humioactions/finalizers,verbs=update
func (r *HumioActionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
if r.Namespace != "" {
if r.Namespace != req.Namespace {
return reconcile.Result{}, nil
}
}
r.Log = r.BaseLogger.WithValues("Request.Namespace", req.Namespace, "Request.Name", req.Name, "Request.Type", helpers.GetTypeName(r), "Reconcile.ID", kubernetes.RandomString())
r.Log.Info("Reconciling HumioAction")
ha := &humiov1alpha1.HumioAction{}
err := r.Get(ctx, req.NamespacedName, ha)
if err != nil {
if k8serrors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
cluster, err := helpers.NewCluster(ctx, r, ha.Spec.ManagedClusterName, ha.Spec.ExternalClusterName, ha.Namespace, helpers.UseCertManager(), true)
if err != nil || cluster == nil || cluster.Config() == nil {
r.Log.Error(err, "unable to obtain humio client config")
err = r.setState(ctx, humiov1alpha1.HumioActionStateConfigError, ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "unable to set action state")
}
return reconcile.Result{}, err
}
err = r.resolveSecrets(ctx, ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "could not resolve secret references")
}
if _, err := humio.ActionFromActionCR(ha); err != nil {
r.Log.Error(err, "unable to validate action")
err = r.setState(ctx, humiov1alpha1.HumioActionStateConfigError, ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "unable to set action state")
}
return reconcile.Result{}, err
}
defer func(ctx context.Context, humioClient humio.Client, ha *humiov1alpha1.HumioAction) {
curAction, err := r.HumioClient.GetAction(cluster.Config(), req, ha)
if errors.As(err, &humioapi.EntityNotFound{}) {
_ = r.setState(ctx, humiov1alpha1.HumioActionStateNotFound, ha)
return
}
if err != nil || curAction == nil {
_ = r.setState(ctx, humiov1alpha1.HumioActionStateUnknown, ha)
return
}
_ = r.setState(ctx, humiov1alpha1.HumioActionStateExists, ha)
}(ctx, r.HumioClient, ha)
return r.reconcileHumioAction(ctx, cluster.Config(), ha, req)
}
func (r *HumioActionReconciler) reconcileHumioAction(ctx context.Context, config *humioapi.Config, ha *humiov1alpha1.HumioAction, req ctrl.Request) (reconcile.Result, error) {
// Delete
r.Log.Info("Checking if Action is marked to be deleted")
isMarkedForDeletion := ha.GetDeletionTimestamp() != nil
if isMarkedForDeletion {
r.Log.Info("Action marked to be deleted")
if helpers.ContainsElement(ha.GetFinalizers(), humioFinalizer) {
// Run finalization logic for humioFinalizer. If the
// finalization logic fails, don't remove the finalizer so
// that we can retry during the next reconciliation.
r.Log.Info("Deleting Action")
if err := r.HumioClient.DeleteAction(config, req, ha); err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "Delete Action returned error")
}
r.Log.Info("Action Deleted. Removing finalizer")
ha.SetFinalizers(helpers.RemoveElement(ha.GetFinalizers(), humioFinalizer))
err := r.Update(ctx, ha)
if err != nil {
return reconcile.Result{}, err
}
r.Log.Info("Finalizer removed successfully")
}
return reconcile.Result{}, nil
}
r.Log.Info("Checking if Action requires finalizer")
// Add finalizer for this CR
if !helpers.ContainsElement(ha.GetFinalizers(), humioFinalizer) {
r.Log.Info("Finalizer not present, adding finalizer to Action")
ha.SetFinalizers(append(ha.GetFinalizers(), humioFinalizer))
err := r.Update(ctx, ha)
if err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{Requeue: true}, nil
}
r.Log.Info("Checking if action needs to be created")
// Add Action
curAction, err := r.HumioClient.GetAction(config, req, ha)
if errors.As(err, &humioapi.EntityNotFound{}) {
r.Log.Info("Action doesn't exist. Now adding action")
addedAction, err := r.HumioClient.AddAction(config, req, ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "could not create action")
}
r.Log.Info("Created action", "Action", ha.Spec.Name)
result, err := r.reconcileHumioActionAnnotations(ctx, addedAction, ha, req)
if err != nil {
return result, err
}
return reconcile.Result{Requeue: true}, nil
}
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "could not check if action exists")
}
r.Log.Info("Checking if action needs to be updated")
// Update
expectedAction, err := humio.ActionFromActionCR(ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "could not parse expected action")
}
sanitizeAction(curAction)
sanitizeAction(expectedAction)
if !cmp.Equal(*curAction, *expectedAction) {
r.Log.Info("Action differs, triggering update")
action, err := r.HumioClient.UpdateAction(config, req, ha)
if err != nil {
return reconcile.Result{}, r.logErrorAndReturn(err, "could not update action")
}
if action != nil {
r.Log.Info(fmt.Sprintf("Updated action %q", ha.Spec.Name))
}
}
r.Log.Info("done reconciling, will requeue after 15 seconds")
return reconcile.Result{}, nil
}
func (r *HumioActionReconciler) resolveSecrets(ctx context.Context, ha *humiov1alpha1.HumioAction) error {
var err error
if ha.Spec.SlackPostMessageProperties != nil {
ha.Spec.SlackPostMessageProperties.ApiToken, err = r.resolveField(ctx, ha.Namespace, ha.Spec.SlackPostMessageProperties.ApiToken, ha.Spec.SlackPostMessageProperties.ApiTokenSource)
if err != nil {
return fmt.Errorf("slackPostMessageProperties.ingestTokenSource.%v", err)
}
}
if ha.Spec.OpsGenieProperties != nil {
ha.Spec.OpsGenieProperties.GenieKey, err = r.resolveField(ctx, ha.Namespace, ha.Spec.OpsGenieProperties.GenieKey, ha.Spec.OpsGenieProperties.GenieKeySource)
if err != nil {
return fmt.Errorf("opsGenieProperties.ingestTokenSource.%v", err)
}
}
if ha.Spec.HumioRepositoryProperties != nil {
ha.Spec.HumioRepositoryProperties.IngestToken, err = r.resolveField(ctx, ha.Namespace, ha.Spec.HumioRepositoryProperties.IngestToken, ha.Spec.HumioRepositoryProperties.IngestTokenSource)
if err != nil {
return fmt.Errorf("humioRepositoryProperties.ingestTokenSource.%v", err)
}
}
return nil
}
func (r *HumioActionReconciler) resolveField(ctx context.Context, namespace, value string, ref humiov1alpha1.VarSource) (string, error) {
if value != "" {
return value, nil
}
if ref.SecretKeyRef != nil {
secret, err := kubernetes.GetSecret(ctx, r, ref.SecretKeyRef.Name, namespace)
if err != nil {
if k8serrors.IsNotFound(err) {
return "", fmt.Errorf("secretKeyRef was set but no secret exists by name %s in namespace %s", ref.SecretKeyRef.Name, namespace)
}
return "", fmt.Errorf("unable to get secret with name %s in namespace %s", ref.SecretKeyRef.Name, namespace)
}
value, ok := secret.Data[ref.SecretKeyRef.Key]
if !ok {
return "", fmt.Errorf("secretKeyRef was found but it does not contain the key %s", ref.SecretKeyRef.Key)
}
return string(value), nil
}
return "", nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *HumioActionReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&humiov1alpha1.HumioAction{}).
Complete(r)
}
func (r *HumioActionReconciler) setState(ctx context.Context, state string, hr *humiov1alpha1.HumioAction) error {
if hr.Status.State == state {
return nil
}
r.Log.Info(fmt.Sprintf("setting action state to %s", state))
hr.Status.State = state
return r.Status().Update(ctx, hr)
}
func (r *HumioActionReconciler) logErrorAndReturn(err error, msg string) error {
r.Log.Error(err, msg)
return fmt.Errorf("%s: %w", msg, err)
}
func sanitizeAction(action *humioapi.Action) {
action.ID = ""
}
|
package bd
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var MongoC = ConectarBD()
var clientOptions = options.Client().ApplyURI("mongodb+srv://yoandredb:hV9HhwKHDjQcR3uD@cluster0.enacc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
/*ConectarBD es necesario*/
func ConectarBD() *mongo.Client {
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err.Error())
return client
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err.Error())
return client
}
log.Printfln("Conexion exitosa con la BD")
return client
}
/*CheckConect es la funcion*/
func CheckConect() int {
err = MongoC.Ping(context.TODO(), nil)
if err != nil {
return 0
}
return 1
}
|
package main
import (
"fmt"
"strconv"
"texas_real_foods/pkg/connectors/web"
"texas_real_foods/pkg/utils"
updater "texas_real_foods/pkg/auto-updater"
)
var (
// create map to house environment variables
cfg = utils.NewConfigMapWithValues(
map[string]string{
"postgres_url": "postgres://postgres:postgres-dev@192.168.99.100:5432",
"phone_validation_api_host": "http://localhost:10847",
"collection_interval_minutes": "1",
"trf_api_host": "0.0.0.0",
"trf_api_port": "10999",
"utils_api_host": "0.0.0.0",
"utils_api_port": "10847",
"log_level": "INFO",
},
)
)
// function used to retrieve API config for utils API
func getUtilsAPIConfig() utils.APIDependencyConfig {
// get configuration for downstream API dependencies and convert to integer
apiPortString := cfg.Get("utils_api_port")
apiPort, err := strconv.Atoi(apiPortString)
if err != nil {
panic(fmt.Sprintf("received invalid api port for utils API '%s'", apiPortString))
}
return utils.APIDependencyConfig{
Host: cfg.Get("utils_api_host"),
Port: &apiPort,
Protocol: "http",
}
}
// function used to retrieve API config for texas real foods API
func getTexasRealFoodsAPIConfig() utils.APIDependencyConfig {
// get configuration for downstream API dependencies and convert to integer
apiPortString := cfg.Get("trf_api_port")
apiPort, err := strconv.Atoi(apiPortString)
if err != nil {
panic(fmt.Sprintf("received invalid api port for trf API '%s'", apiPortString))
}
return utils.APIDependencyConfig{
Host: cfg.Get("trf_api_host"),
Port: &apiPort,
Protocol: "http",
}
}
func main() {
cfg.ConfigureLogging()
// generate new web connector and instance of notification engine
connector := connectors.NewWebConnector(getUtilsAPIConfig())
intervalString := cfg.Get("collection_interval_minutes")
// convert given interval from string to integer
interval, err := strconv.Atoi(intervalString)
if err != nil {
panic(fmt.Sprintf("received invalid collection interval '%s'", intervalString))
}
// create new updater with data connector and run
collector := updater.NewStreamedAutoUpdater(connector, interval, cfg.Get("postgres_url"),
getTexasRealFoodsAPIConfig())
collector.RunWithStreaming()
}
|
package view
import "github.com/maxence-charriere/go-app/v7/pkg/app"
// NavbarItem : navigation bar item
type NavbarItem struct {
Text string
Herf string
}
// Navbar : navigation bar
func Navbar(title string, items []NavbarItem) app.UI {
return app.Nav().Body(
app.Div().Class("nav-wrapper grey darken-4").Body(
app.A().Class("logo").Text(title),
app.Ul().Class("right").Body(
app.Range(items).Slice(func(i int) app.UI {
return app.Li().Body(
app.A().Href(items[i].Herf).Text(items[i].Text),
)
}),
),
),
)
}
|
/*
Mubashir needs your help to find the Simple Numbers in a given range.
A number X, that has an N amount of digits (which we'll enumerate as d1, d2, ..., dN), is Simple if the following equation holds true:
X = d1^1 + d2^2 + ... + dN^N
Examples of Simple Numbers:
89 = 8^1 + 9^2
135 = 1^1 + 3^2 + 5^3
Create a function that returns an array of all the Simple Numbers that exist within a given range between a and b (both numbers are inclusive).
Generate an array with the numbers from a to b.
Filter the array so that only "simple numbers" are kept.
To find out if a number is "simple":
Generate an array of the individual digits of the number.
For each digit, calculate digit ^ (indexOfTheDigit + 1).
Sum the results of the calculations above and compare with the original number, if they're equal, the number is "simple".
Examples
simpleNumbers(1, 10) ➞ [1, 2, 3, 4, 5, 6, 7, 8, 9]
simpleNumbers(1, 100) ➞ [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
simpleNumbers(90, 100) ➞ []
Notes
N/A
*/
package main
import (
"fmt"
"reflect"
)
func main() {
test(1, 10, []int{1, 2, 3, 4, 5, 6, 7, 8, 9})
test(1, 100, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 89})
test(10, 89, []int{89})
test(10, 100, []int{89})
test(90, 100, []int{})
test(90, 150, []int{135})
test(50, 150, []int{89, 135})
test(10, 150, []int{89, 135})
test(89, 135, []int{89, 135})
test(100, 32253, []int{135, 175, 518, 598, 1306, 1676, 2427})
}
func test(a, b int, r []int) {
p := simple(a, b)
fmt.Println(p)
if len(p) == 0 {
assert(len(p) == len(r))
} else {
assert(reflect.DeepEqual(p, r))
}
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func simple(a, b int) []int {
var p []int
for i := a; i <= b; i++ {
if valid(i) {
p = append(p, i)
}
}
return p
}
func valid(n int) bool {
var d []int
n = abs(n)
for v := n; v != 0; v /= 10 {
d = append(d, v%10)
}
r := 0
for i := range d {
r += ipow(d[i], len(d)-i)
}
return r == n
}
func abs(x int) int {
if x < 0 {
x = -x
}
return x
}
func ipow(x, y int) int {
if y < 0 {
return 0
}
p := 1
for i := 0; i < y; i++ {
p *= x
}
return p
}
|
package common
import (
"context"
"math/rand"
)
// Context : 应用程序上下文
type Context struct {
Ctx context.Context // 常驻功能
Rand *rand.Rand // 常驻功能
Config *Config // 常驻功能
Log ILogger // 常驻功能
Node INode // 常驻功能
ServerForClient ITCPServer // 注册该字段相应接口,才会开启
ServerForIntranet ITCPServer // 注册该字段相应接口,才会开启
Login ILogin // 节点类型为 Login,才会开启
Gateway IGateway // 节点类型为 Gateway ,才会开启
}
|
package mall
import (
"context"
"github.com/gin-gonic/gin"
"github.com/lenuse/mall/handles/admin"
"github.com/lenuse/mall/middlewares"
"net/http"
"time"
)
func New() *gin.Engine {
app := gin.Default()
app.Use(func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 8*time.Second)
defer func() {
if c.Err() == context.DeadlineExceeded {
c.Writer.WriteHeader(http.StatusRequestTimeout)
c.Abort()
}
cancel()
}()
c.Request = c.Request.WithContext(ctx)
c.Next()
})
app.Use(middlewares.SetTraceId())
app.POST("/v1/admin/login", admin.SignIn)
app.POST("/v1/admin/create", admin.CreateAdminUser)
v1 := app.Group("/v1/admin").Use(middlewares.JwtVerify())
{
v1.GET("/static")
}
return app
}
|
package base58Encrypt
import "github.com/btcsuite/btcutil/base58"
func Base58Encryption(ver, pubKeyHash, checkSum []byte) string {
verAddPubKeyHash := append(ver, pubKeyHash...)
data := append(verAddPubKeyHash, checkSum...)
encoded := base58.Encode(data)
return encoded
}
|
package game
import "korok.io/korok/engi"
/**
标记并分类游戏对象, 在 Tag (Name) 的基础上再加一个 Label,作为二级分类,
在游戏中,很多时候是需要这样的二级分类的。比如: enemy {bullet, ship}
*/
type TagComp struct {
Name, Label string
}
// TODO 如何高效的存储和查找tag数据?
type TagTable struct {
comps []TagComp
_map map[uint32]int
index, cap int
d map[string][]engi.Entity
}
func (tt *TagTable) NewComp(entity engi.Entity) (tc *TagComp) {
tc = &tt.comps[tt.index]
tt._map[entity.Index()] = tt.index
tt.index ++
return
}
func (tt *TagTable) Comp(entity engi.Entity) (tc *TagComp) {
if v, ok := tt._map[entity.Index()]; ok {
tc = &tt.comps[v]
}
return
}
// todo
func (tt *TagTable) Delete(entity engi.Entity) (tc *TagComp) {
return nil
}
func (tt *TagTable) Group(tag string) []engi.Entity {
return nil
}
func (tt *TagTable) Size() (size, cap int) {
return 0, 0
}
|
package apigen
var qIDStr string
var paramStr string
// WriteToConstantFile - This writes the constants
func WriteToConstantFile(apimodel API) {
prepareQueryID(apimodel)
prepareConstantStr(apimodel)
fileContent := qIDStr + paramStr
ReplaceFileContent(apimodel.Methods.Detail.FileName.ConstName, "#Replace#", fileContent)
}
func prepareQueryID(apimodel API) {
qIDStr = ""
dataAPIName := apimodel.Methods.Detail.DataAPIConfig.DataAPIName
qIDStr = `QueryID.` + dataAPIName + `= '` + dataAPIName + `';`
}
func prepareConstantStr(apimodel API) {
paramStr = ""
Accepts := apimodel.Methods.Detail.LbConfig.Accepts
for _, Accept := range Accepts {
paramStr +=
`
APIVariable.` + Accept.Arg + " = '" + Accept.Arg + `';
`
}
}
|
// Created by Yaz Saito on 06/15/12.
// Modified by Geert-Johan Riemer, Foize B.V.
// TODO:
// - travis CI
package fifo
const chunkSize = 64
// chunks are used to make a queue auto resizeable.
type chunk struct {
items [chunkSize]interface{} // list of queue'ed items
first, last int // positions for the first and list item in this chunk
next *chunk // pointer to the next chunk (if any)
}
// fifo queue
type UnsafeQueue struct {
head, tail *chunk // chunk head and tail
count int // total amount of items in the queue
}
// NewUnsafeQueue creates a new and empty *fifo.UnsafeQueue
func NewUnsafeQueue() (q *UnsafeQueue) {
initChunk := new(chunk)
q = &UnsafeQueue{
head: initChunk,
tail: initChunk,
}
return q
}
// Return the number of items in the queue
func (q *UnsafeQueue) Len() (length int) {
// copy q.count and return length
length = q.count
return length
}
// Add an item to the end of the queue
func (q *UnsafeQueue) Add(item interface{}) {
// check if item is valid
if item == nil {
panic("can not add nil item to fifo queue")
}
// if the tail chunk is full, create a new one and add it to the queue.
if q.tail.last >= chunkSize {
q.tail.next = new(chunk)
q.tail = q.tail.next
}
// add item to the tail chunk at the last position
q.tail.items[q.tail.last] = item
q.tail.last++
q.count++
}
// Adds an list of items to the queue
func (q *UnsafeQueue) AddList(items []interface{}) {
// check if item is valid
if len(items) == 0 {
// len(nil) == 0 as well
return
}
//
if len(items) > chunkSize { // Add each piece separated
chunks := len(items) / chunkSize
if chunks*chunkSize != len(items) { // Rouding up
chunks++
}
for i := 0; i < chunks; i++ {
s := i * chunkSize
e := (i + 1) * chunkSize
if e > len(items) {
e = len(items)
}
q.AddList(items[s:e])
}
return
}
// if the tail chunk is full, create a new one and add it to the queue.
if q.tail.last >= chunkSize {
q.tail.next = new(chunk)
q.tail = q.tail.next
}
s := q.tail.last
e := len(items) - s
n := copy(q.tail.items[s:e], items)
q.tail.last += n
q.count += n
items = items[e:]
if len(items) > 0 {
q.AddList(items) // Add Remaining Items
}
}
// Returns the next N elements from the queue
// In case of not enough elements, returns the elements that are available
func (q *UnsafeQueue) NextN(n int) []interface{} {
if n > chunkSize {
// Recursive call to append
chunks := n / chunkSize
if chunks*chunkSize < n {
chunks++
}
out := make([]interface{}, 0)
read := 0
for i := 0; i < chunks; i++ {
e := chunkSize
if read+e > n {
e = n - read
}
out = append(out, q.NextN(e)...)
}
return out
}
if q.count < n {
n = q.count // Not enough elements
}
if q.count == 0 || q.head.first >= q.head.last {
return make([]interface{}, 0)
}
// TODO: Slice it
out := make([]interface{}, n)
read := 0
for i := 0; i < n; i++ {
if q.count == 0 {
break
}
read++
out[i] = q.Next()
}
return out[:read]
}
// Remove the item at the head of the queue and return it.
// Returns nil when there are no items left in queue.
func (q *UnsafeQueue) Next() (item interface{}) {
// Return nil if there are no items to return
if q.count == 0 {
return nil
}
// FIXME: why would this check be required?
if q.head.first >= q.head.last {
return nil
}
// Get item from queue
item = q.head.items[q.head.first]
// increment first position and decrement queue item count
q.head.first++
q.count--
if q.head.first >= q.head.last {
// we're at the end of this chunk and we should do some maintainance
// if there are no follow up chunks then reset the current one so it can be used again.
if q.count == 0 {
q.head.first = 0
q.head.last = 0
q.head.next = nil
} else {
// set queue's head chunk to the next chunk
// old head will fall out of scope and be GC-ed
q.head = q.head.next
}
}
// return the retrieved item
return item
}
// Reads the item at the head of the queue without removing it
// Returns nil when there are no items left in queue
func (q *UnsafeQueue) Peek() (item interface{}) {
// Return nil if there are no items to return
if q.count == 0 {
return nil
}
// FIXME: why would this check be required?
if q.head.first >= q.head.last {
return nil
}
// Get item from queue
return q.head.items[q.head.first]
}
|
package main
import "fmt"
func main() {
var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
for i := range s {
s[i] = byte(i + 3)
}
printSlice("S", s)
t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0
for i, v := range s {
t[i] = s[i]
fmt.Printf("s[%d] = %d\n", i, v)
}
s = t
x := AppendByte(s, 5, 4, 3)
printSlice("X", x)
p := []byte{2, 3, 5}
p = AppendByte(p, 7, 11, 13)
printSlice("P", p)
p = append(p, s...)
printSlice("P'", p)
}
func AppendByte(slice []byte, data ...byte) []byte {
m := len(slice)
n := m + len(data)
if n > cap(slice) { // if necessary, reallocate
// allocate double what's needed, for future growth.
newSlice := make([]byte, (n+1)*2)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:n]
copy(slice[m:n], data)
return slice
}
func printSlice(name string, s []byte) {
fmt.Printf("Slice %s len=%d cap=%d %v\n", name, len(s), cap(s), s)
}
|
package rabbitenv
import (
"testing"
"github.com/streadway/amqp"
)
// TestGetConfig tests rabbitenv.GetConfig
func TestGetConfig(t *testing.T) {
if Config("queue") != "test" {
t.Error("Config is incorrect")
}
}
func TestPublish(t *testing.T) {
body := "test"
msg := amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
}
err := Publish(msg)
if err != nil {
t.Error("Message is not sent")
}
}
|
package main
import (
"server/controller"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
// @title Swagger Example Book API
// @version 1.0
// @host localhost:8080
// @BasePath /
func main() {
engine := gin.Default()
// CORS対応
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://localhost:4000"}
engine.Use(cors.New(config))
apiEngine := engine.Group("/api")
{
v1 := apiEngine.Group("/v1")
{
v1.POST("/book", controller.BookAdd)
v1.GET("/books", controller.BookList)
v1.PUT("/book/:id", controller.BookUpdate)
v1.DELETE("/book/:id", controller.BookDelete)
}
}
// なぜかswagger uiが見れない
engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
engine.Run(":8080")
}
|
package task
import (
"net/http"
"github.com/gin-gonic/gin"
)
func TaskRegister(r *gin.RouterGroup) {
r.POST("/:uuid/done", TaskDone)
r.POST("/", TaskCreation)
r.GET("/:slug", Retrieve)
}
func TaskCreation(c *gin.Context) {
taskValidator := NewTaskValidator()
if err := taskValidator.Bind(c); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := taskValidator.TaskModel.Save(); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"task": taskValidator.TaskModel.Response()})
}
func Retrieve(c *gin.Context) {
slug := c.Param("slug")
task, err := FindOne(&Task{Slug: slug})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"task": task})
}
func TaskDone(c *gin.Context) {
uuid := c.Param("uuid")
task, err := FindOne(&Task{UUID: uuid})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if task.Done {
c.JSON(http.StatusOK, gin.H{"status": "OK"})
return
}
if err = task.Update(Task{Done: true}); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"task": task})
}
|
package pacs
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00900102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pacs.009.001.02 Document"`
Message *FinancialInstitutionCreditTransferV02 `xml:"FinInstnCdtTrf"`
}
func (d *Document00900102) AddMessage() *FinancialInstitutionCreditTransferV02 {
d.Message = new(FinancialInstitutionCreditTransferV02)
return d.Message
}
// Scope
// The FinancialInstitutionCreditTransfer message is sent by a debtor financial institution to a creditor financial institution, directly or through other agents and/or a payment clearing and settlement system.
// It is used to move funds from a debtor account to a creditor, where both debtor and creditor are financial institutions.
// Usage
// The FinancialInstitutionCreditTransfer message is exchanged between agents and can contain one or more credit transfer instructions where debtor and creditor are both financial institutions.
// The FinancialInstitutionCreditTransfer message does not allow for grouping: a CreditTransferTransactionInformation block must be present for each credit transfer transaction.
// The FinancialInstitutionCreditTransfer message can be used in domestic and cross-border scenarios.
type FinancialInstitutionCreditTransferV02 struct {
// Set of characteristics shared by all individual transactions included in the message.
GroupHeader *iso20022.GroupHeader35 `xml:"GrpHdr"`
// Set of elements providing information specific to the individual credit transfer(s).
CreditTransferTransactionInformation []*iso20022.CreditTransferTransactionInformation13 `xml:"CdtTrfTxInf"`
}
func (f *FinancialInstitutionCreditTransferV02) AddGroupHeader() *iso20022.GroupHeader35 {
f.GroupHeader = new(iso20022.GroupHeader35)
return f.GroupHeader
}
func (f *FinancialInstitutionCreditTransferV02) AddCreditTransferTransactionInformation() *iso20022.CreditTransferTransactionInformation13 {
newValue := new(iso20022.CreditTransferTransactionInformation13)
f.CreditTransferTransactionInformation = append(f.CreditTransferTransactionInformation, newValue)
return newValue
}
|
// Package dnscache provides a simple caching DNS resolver,
// mainly designed to work with docker internal resolver.
package dnscache
import (
"fmt"
"io/ioutil"
"net"
"time"
"strings"
"github.com/korovkin/limiter"
"github.com/miekg/dns"
"github.com/sirupsen/logrus"
)
var (
DefaultUpstream = "127.0.0.11:53"
DefaultTimeout = time.Second * 5
DefaultUpdateInterval = time.Second * 15
DefaultEntryTTL = time.Second * 1800
// if entry is newer than 5s, we don't re-resolve it. This isn't configurable atm
noUpdatePeriod = time.Second * 5
)
type Resolver struct {
listenAddr string
listenPort int
upstream string
dialTimeout time.Duration
udpServer *dns.Server
tcpServer *dns.Server
stopChan chan struct{}
exchangeFunc func(*dns.Msg, string) (*dns.Msg, error)
limiter *limiter.ConcurrencyLimiter
cache *cache
cacheUpdateInterval time.Duration
cacheEntryTTL time.Duration
}
// NewResolver creates a new resolver with given options
// or with default values for missing ones.
func NewResolver(host string, port int, opts ...ResolverOption) *Resolver {
r := Resolver{
listenAddr: host,
listenPort: port,
upstream: DefaultUpstream,
dialTimeout: DefaultTimeout,
stopChan: make(chan struct{}, 1),
cache: &cache{
cacheTypes: []uint16{dns.TypeA, dns.TypeAAAA},
data: map[string]cacheEntry{},
},
exchangeFunc: dns.Exchange,
cacheUpdateInterval: DefaultUpdateInterval,
cacheEntryTTL: DefaultEntryTTL,
}
for _, option := range opts {
option(&r)
}
return &r
}
// Start runs tcp/udp listeners and cache updating goroutine.
//
// Keep in mind that this call doesn't block.
func (r *Resolver) Start() error {
err := r.startUDP()
if err != nil {
return err
}
err = r.startTCP()
if err != nil {
return err
}
t := time.NewTicker(r.cacheUpdateInterval)
go func() {
for {
select {
case <-t.C:
r.updateCache()
case <-r.stopChan:
t.Stop()
}
}
}()
return nil
}
// Stop shuts down both TCP and UDP listeners and stops the ticker goroutine.
func (r *Resolver) Stop() {
r.stopChan <- struct{}{}
// shutdown also closes connections
if r.udpServer != nil {
r.udpServer.Shutdown()
}
if r.tcpServer != nil {
r.tcpServer.Shutdown()
}
}
// ListenAddress returns address that the resolver is listening on (without port).
func (r *Resolver) ListenAddress() string {
return r.listenAddr
}
// ServeDNS implements Handler interface of miekg/dns package.
func (r *Resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
if query == nil || len(query.Question) == 0 {
return
}
fail := func() {
resp := new(dns.Msg)
resp.SetRcode(query, dns.RcodeServerFailure)
w.WriteMsg(resp)
}
name := query.Question[0].Name
qtype := query.Question[0].Qtype
qtypeStr := dns.TypeToString[qtype]
logrus.Debugf("[resolver] resolving '%s', qtype '%s'", name, qtypeStr)
proto := w.LocalAddr().Network()
if r.cache.IsCachedType(qtype) {
if resp, ok := r.responseFromCache(query); ok {
w.WriteMsg(resp)
return
}
logrus.Debugf("[resolver] cache miss: %s", name)
resp, err := r.forward(proto, query)
if err != nil {
logrus.Warn(err)
fail()
return
}
w.WriteMsg(resp)
if resp.Rcode == dns.RcodeSuccess {
r.cache.Set(name, qtype, resp)
}
}
logrus.Debugf("[resolver] forwarding query to '%s'", r.upstream)
resp, err := r.forward(proto, query)
if err != nil {
logrus.Debugf("[resolver] got an error from upstream:", err)
fail()
return
}
w.WriteMsg(resp)
}
func (r *Resolver) startUDP() error {
started := make(chan struct{})
errc := make(chan error)
udpAddr := &net.UDPAddr{
IP: net.ParseIP(r.listenAddr),
Port: r.listenPort,
}
udpListener, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return err
}
udpServer := &dns.Server{Handler: r, PacketConn: udpListener}
udpServer.NotifyStartedFunc = func() {
started <- struct{}{}
}
r.udpServer = udpServer
go func() {
errc <- udpServer.ActivateAndServe()
}()
select {
case <-started:
return nil
case err := <-errc:
return err
}
}
func (r *Resolver) startTCP() error {
started := make(chan struct{})
errc := make(chan error)
tcpAddr := &net.TCPAddr{
IP: net.ParseIP(r.listenAddr),
Port: r.listenPort,
}
tcpListener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return err
}
tcpServer := &dns.Server{Handler: r, Listener: tcpListener}
tcpServer.NotifyStartedFunc = func() {
started <- struct{}{}
}
r.udpServer = tcpServer
go func() {
errc <- tcpServer.ActivateAndServe()
}()
select {
case <-started:
return nil
case err := <-errc:
return err
}
}
func (r *Resolver) responseFromCache(query *dns.Msg) (*dns.Msg, bool) {
name := query.Question[0].Name
qtype := query.Question[0].Qtype
logrus.Debugf("[resolver] looking up cache for '%s'", name)
resp, ok := r.cache.Get(name, qtype)
if ok {
resp.SetReply(query)
}
return resp, ok
}
func (r *Resolver) updateCache() {
logrus.Debug("[cache] updating cache")
entries := r.cache.Entries()
for _, fqdn := range entries {
r.updateCacheEntry(fqdn)
}
}
func (r *Resolver) updateCacheEntry(fqdn string) {
lastAccess := r.cache.LastAccess(fqdn)
if time.Since(lastAccess) >= r.cacheEntryTTL {
logrus.Debugf("[cache] ttl expired, deleting '%s'", fqdn)
r.cache.DelKey(fqdn)
return
}
lastUpdate := r.cache.LastUpdate(fqdn)
if time.Since(lastUpdate) <= noUpdatePeriod {
logrus.Debugf("[cache] entry for '%s' is too fresh, skipping update", fqdn)
return
}
for _, qtype := range r.cache.GetCachedTypes() {
q := new(dns.Msg)
q.Id = dns.Id()
q.RecursionDesired = true
q.Question = []dns.Question{
{
Name: fqdn,
Qtype: qtype,
Qclass: dns.ClassINET,
},
}
resp, err := r.exchangeFunc(q, r.upstream)
if err != nil || resp == nil {
logrus.Debugf("[cache] got an error, deleting entry: err: %s, resp: %v", err, resp)
r.cache.DelRecord(fqdn, qtype) // just delete the entry as we cannot ensure its validity
return
}
if resp.Rcode != dns.RcodeSuccess {
if rcodestr, ok := dns.RcodeToString[resp.Rcode]; ok {
logrus.Debugf("[cache] response rcode != NOERROR, deleting entry: rcode: %s", rcodestr)
} else {
logrus.Debugf("[cache] response rcode unknown, deleting entry: rcode: %d", resp.Rcode)
}
return
}
r.cache.Set(fqdn, qtype, resp)
}
logrus.Debugf("[cache] updated %s", fqdn)
}
func (r *Resolver) forward(proto string, msg *dns.Msg) (*dns.Msg, error) {
switch proto {
case "udp":
return r.exchangeFunc(msg, r.upstream)
case "tcp":
conn, err := net.DialTimeout(proto, r.upstream, r.dialTimeout)
if err != nil {
return nil, err
}
defer conn.Close()
dnsConn := &dns.Conn{
Conn: conn,
UDPSize: dns.DefaultMsgSize,
}
defer dnsConn.Close()
err = dnsConn.WriteMsg(msg)
if err != nil {
return nil, err
}
return dnsConn.ReadMsg()
default:
return nil, fmt.Errorf("[resolver] wrong proto: %s", proto)
}
}
// ReplaceDockerDNS edits /etc/resolv.conf, replacing lines containing
// nameserver 127.0.0.11 (which is docker internal resolver address) with given address.
//
// https://github.com/docker/compose/issues/2847
//
// It has very limited use cases, so I don't recommend to use it.
func ReplaceDockerDNS(addr string) error {
input, err := ioutil.ReadFile("/etc/resolv.conf")
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
for i, line := range lines {
if strings.Contains(line, "nameserver 127.0.0.11") {
lines[i] = "nameserver " + addr
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile("/etc/resolv.conf", []byte(output), 0644)
if err != nil {
return err
}
return nil
}
|
/*
* @lc app=leetcode.cn id=26 lang=golang
*
* [26] 删除排序数组中的重复项
*/
package solution
// @lc code=start
func removeDuplicates(nums []int) int {
n := len(nums)
if n < 2 {
return n
}
p := 0
for q := 1; q < n; q++ {
for q < n && nums[q] == nums[q-1] {
q++
}
if q < n {
p++
nums[p] = nums[q]
}
}
return p + 1
}
// @lc code=end
|
// Test for pointless make() calls.
// Package pkg ...
package pkg
func f() {
x := make([]T, 0) // MATCH /var x \[\]T/
y := make([]somepkg.Foo_Bar, 0) // MATCH /var y \[\]somepkg.Foo_Bar/
z = make([]T, 0) // ok, because we don't know where z is declared
}
|
package main
func main() {
var i1, i2 int
var f1, f2 float64
var r1, r2 rune
var s1, s2 string
var b1, b2 bool
var ii1, ii2 = 3, 4
var ff1, ff2 = 3.0, 4.0
var rr1, rr2 = 'r', 's'
var bb1, bb2 = true, false
var ss1, ss2 = "Hello", "World"
var (
iii1, iii2 int
fff1, fff2 float64
rrr1, rrr2 rune
sss1, sss2 string
bbb1, bbb2 bool
)
}
|
package user
import (
"database/sql"
_ "github.com/lib/pq"
)
type UserRepo interface {
getAllUsers() ([]*User, error)
get(int) (*User, error)
create(*User) (*User, error)
update(*User) (*User, error)
getMatches(int) ([]*User, error)
deleteMatch(int, int) (bool, error)
}
type userRepo struct {
connector *sql.DB
}
func NewDatabase() UserRepo {
return &userRepo{
connector: LoadPGDB(),
}
}
func (db *userRepo) getAllUsers() ([]*User, error) {
var userList []*User
sqlStatement := `SELECT * FROM users;`
rows, err := db.connector.Query(sqlStatement)
if err != nil {
panic(err)
}
defer rows.Close()
// cols, _ := rows.Columns()
// fmt.Printf("COLS: %s", strings.Join(cols, " "))
for rows.Next() {
u := &User{}
if err := rows.Scan(&u.UserID, &u.FirstName, &u.LastName, &u.Birthdate, &u.Location, &u.Interest); err != nil {
return nil, err
}
userList = append(userList, u)
}
return userList, nil
}
func (db *userRepo) get(userID int) (*User, error) {
//s.db.get
sqlStatement := `SELECT * FROM users WHERE userid=$1;`
row := db.connector.QueryRow(sqlStatement, userID)
u := &User{}
if err := row.Scan(&u.UserID, &u.FirstName, &u.LastName, &u.Birthdate, &u.Location, &u.Interest); err != nil {
return nil, err
}
return u, nil
}
// Why are we returning the same user we just created?
func (db *userRepo) create(user *User) (*User, error) {
// IWAACCT
sqlStatement := `INSERT INTO users VALUES ($1, $2, $3, $4, $5, $6);`
_, err := db.connector.Exec(sqlStatement, user.UserID, user.FirstName, user.LastName, user.Birthdate, user.Location, user.Interest)
// Put ID into the user
if err != nil {
return nil, err
}
return user, nil
}
func (db *userRepo) update(user *User) (*User, error) {
// IWAACCT
oldUser, err := db.get(user.UserID)
if err != nil {
return nil, err
}
newUser := &User{}
// NAME
if user.FirstName == "" {
newUser.FirstName = oldUser.FirstName
} else {
newUser.FirstName = user.FirstName
}
if user.LastName == "" {
newUser.LastName = oldUser.LastName
} else {
newUser.LastName = user.LastName
}
// BIRTHDAY
if user.Birthdate == "" {
newUser.Birthdate = oldUser.Birthdate
} else {
newUser.Birthdate = user.Birthdate
}
// LOCATION
if user.Location == "" {
newUser.Location = oldUser.Location
} else {
newUser.Location = user.Location
}
// INTEREST
if user.Interest == "" {
newUser.Interest = oldUser.Interest
} else {
newUser.Interest = user.Interest
}
// Insert new user into database
sqlStatement := `
UPDATE users
SET firstName = $1, lastName = $2, birthdate=$3, location=$4, interest=$5
WHERE userID = $6;`
_, err = db.connector.Exec(sqlStatement, newUser.FirstName, newUser.LastName, newUser.Birthdate, newUser.Location, newUser.Interest, user.UserID)
if err != nil {
return nil, err
}
return user, nil
}
func (db *userRepo) getMatches(userID int) ([]*User, error) {
var userList []*User
sqlStatement := `SELECT
userid, firstName, lastName, birthdate, location, interest
FROM
matchrequest m
RIGHT JOIN
users u
ON m.userb = u.userid
WHERE
m.usera = $1
and status = $2;`
rows, err := db.connector.Query(sqlStatement, userID, StatusAccept)
if err != nil {
return nil, err
}
defer rows.Close()
// cols, _ := rows.Columns()
// fmt.Printf("COLS: %s\n", strings.Join(cols, " "))
for rows.Next() {
u := &User{}
if err := rows.Scan(&u.UserID, &u.FirstName, &u.LastName, &u.Birthdate, &u.Location, &u.Interest); err != nil {
return nil, err
}
userList = append(userList, u)
}
return userList, nil
}
func (db *userRepo) deleteMatch(userID, targetID int) (bool, error) {
sqlStatement := `DELETE FROM matchrequest WHERE (usera=$1 AND userb=$2) OR (usera=$2 and userb=$1);`
_, err := db.connector.Exec(sqlStatement, userID, targetID)
if err != nil {
return false, err
}
return true, nil
}
|
package validator
import (
"fmt"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/authelia/authelia/v4/internal/configuration/schema"
)
func newDefaultConfig() schema.Configuration {
config := schema.Configuration{}
config.Server.Address = &schema.AddressTCP{Address: schema.NewAddressFromNetworkValues("tcp", loopback, 9090)}
config.Log.Level = "info"
config.Log.Format = "text"
config.JWTSecret = testJWTSecret
config.AuthenticationBackend.File = &schema.AuthenticationBackendFile{
Path: "/a/path",
}
config.AccessControl = schema.AccessControl{
DefaultPolicy: "two_factor",
}
config.Session = schema.Session{
Secret: "secret",
Cookies: []schema.SessionCookie{
{
SessionCookieCommon: schema.SessionCookieCommon{
Name: "authelia_session",
},
Domain: exampleDotCom,
},
},
}
config.Storage.EncryptionKey = testEncryptionKey
config.Storage.Local = &schema.StorageLocal{
Path: "abc",
}
config.Notifier = schema.Notifier{
FileSystem: &schema.NotifierFileSystem{
Filename: "/tmp/file",
},
}
return config
}
func TestShouldEnsureNotifierConfigIsProvided(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 0)
config = newDefaultConfig()
config.Notifier.SMTP = nil
config.Notifier.FileSystem = nil
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
assert.EqualError(t, validator.Errors()[0], "notifier: you must ensure either the 'smtp' or 'filesystem' notifier is configured")
}
func TestShouldAddDefaultAccessControl(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.AccessControl.DefaultPolicy = ""
config.AccessControl.Rules = []schema.AccessControlRule{
{
Policy: "bypass",
Domains: []string{
"public.example.com",
},
},
}
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 0)
assert.NotNil(t, config.AccessControl)
assert.Equal(t, "deny", config.AccessControl.DefaultPolicy)
}
func TestShouldRaiseErrorWithUndefinedJWTSecretKey(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.JWTSecret = ""
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
require.Len(t, validator.Warnings(), 1)
assert.EqualError(t, validator.Errors()[0], "option 'jwt_secret' is required")
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
}
func TestShouldRaiseErrorWithBadDefaultRedirectionURL(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.DefaultRedirectionURL = "bad_default_redirection_url"
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
require.Len(t, validator.Warnings(), 1)
assert.EqualError(t, validator.Errors()[0], "option 'default_redirection_url' is invalid: could not parse 'bad_default_redirection_url' as a URL")
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
}
func TestShouldNotOverrideCertificatesDirectoryAndShouldPassWhenBlank(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
ValidateConfiguration(&config, validator)
assert.Len(t, validator.Errors(), 0)
require.Len(t, validator.Warnings(), 1)
require.Equal(t, "", config.CertificatesDirectory)
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
}
func TestShouldRaiseErrorOnInvalidCertificatesDirectory(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.CertificatesDirectory = "not-a-real-file.go"
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
require.Len(t, validator.Warnings(), 1)
if runtime.GOOS == "windows" {
assert.EqualError(t, validator.Errors()[0], "the location 'certificates_directory' could not be inspected: CreateFile not-a-real-file.go: The system cannot find the file specified.")
} else {
assert.EqualError(t, validator.Errors()[0], "the location 'certificates_directory' could not be inspected: stat not-a-real-file.go: no such file or directory")
}
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
config = newDefaultConfig()
validator = schema.NewStructValidator()
config.CertificatesDirectory = "const.go"
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
require.Len(t, validator.Warnings(), 1)
assert.EqualError(t, validator.Errors()[0], "the location 'certificates_directory' refers to 'const.go' is not a directory")
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
}
func TestShouldNotRaiseErrorOnValidCertificatesDirectory(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.CertificatesDirectory = "../../suites/common/pki"
ValidateConfiguration(&config, validator)
assert.Len(t, validator.Errors(), 0)
require.Len(t, validator.Warnings(), 1)
assert.EqualError(t, validator.Warnings()[0], "access control: no rules have been specified so the 'default_policy' of 'two_factor' is going to be applied to all requests")
}
func TestValidateDefault2FAMethod(t *testing.T) {
testCases := []struct {
desc string
have *schema.Configuration
expectedErrs []string
}{
{
desc: "ShouldAllowConfiguredMethodTOTP",
have: &schema.Configuration{
Default2FAMethod: "totp",
DuoAPI: schema.DuoAPI{
SecretKey: "a key",
IntegrationKey: "another key",
Hostname: "none",
},
},
},
{
desc: "ShouldAllowConfiguredMethodWebAuthn",
have: &schema.Configuration{
Default2FAMethod: "webauthn",
DuoAPI: schema.DuoAPI{
SecretKey: "a key",
IntegrationKey: "another key",
Hostname: "none",
},
},
},
{
desc: "ShouldAllowConfiguredMethodMobilePush",
have: &schema.Configuration{
Default2FAMethod: "mobile_push",
DuoAPI: schema.DuoAPI{
SecretKey: "a key",
IntegrationKey: "another key",
Hostname: "none",
},
},
},
{
desc: "ShouldNotAllowDisabledMethodTOTP",
have: &schema.Configuration{
Default2FAMethod: "totp",
DuoAPI: schema.DuoAPI{
SecretKey: "a key",
IntegrationKey: "another key",
Hostname: "none",
},
TOTP: schema.TOTP{Disable: true},
},
expectedErrs: []string{
"option 'default_2fa_method' must be one of the enabled options 'webauthn' or 'mobile_push' but it's configured as 'totp'",
},
},
{
desc: "ShouldNotAllowDisabledMethodWebAuthn",
have: &schema.Configuration{
Default2FAMethod: "webauthn",
DuoAPI: schema.DuoAPI{
SecretKey: "a key",
IntegrationKey: "another key",
Hostname: "none",
},
WebAuthn: schema.WebAuthn{Disable: true},
},
expectedErrs: []string{
"option 'default_2fa_method' must be one of the enabled options 'totp' or 'mobile_push' but it's configured as 'webauthn'",
},
},
{
desc: "ShouldNotAllowDisabledMethodMobilePush",
have: &schema.Configuration{
Default2FAMethod: "mobile_push",
DuoAPI: schema.DuoAPI{Disable: true},
},
expectedErrs: []string{
"option 'default_2fa_method' must be one of the enabled options 'totp' or 'webauthn' but it's configured as 'mobile_push'",
},
},
{
desc: "ShouldNotAllowInvalidMethodDuo",
have: &schema.Configuration{
Default2FAMethod: "duo",
},
expectedErrs: []string{
"option 'default_2fa_method' must be one of 'totp', 'webauthn', or 'mobile_push' but it's configured as 'duo'",
},
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
validator := schema.NewStructValidator()
validateDefault2FAMethod(tc.have, validator)
assert.Len(t, validator.Warnings(), 0)
errs := validator.Errors()
require.Len(t, errs, len(tc.expectedErrs))
for i, expected := range tc.expectedErrs {
t.Run(fmt.Sprintf("Err%d", i+1), func(t *testing.T) {
assert.EqualError(t, errs[i], expected)
})
}
})
}
}
|
package goxtremio
import (
"regexp"
xms "github.com/emccode/goxtremio/api/v3"
)
type Event *xms.Event
//GetEvents returns a list or a specific events filtered by severity,
//eventCode, or description
func (c *Client) GetEvents(
severity, eventCode, descRxPatt string) ([]Event, error) {
events, err := c.api.GetEvents(severity)
if err != nil {
return nil, err
}
var filtered []Event
rx, _ := regexp.Compile(descRxPatt)
for _, e := range events.Events {
if (eventCode == "" || e.EventCode == eventCode) &&
(e.Description == "" || rx.MatchString(e.Description)) {
filtered = append(filtered, e)
}
}
return filtered, nil
}
|
package repository
import (
"database/sql"
"fmt"
"github.com/DATA-DOG/go-sqlmock"
"github.com/beevik/guid"
"github.com/jinzhu/gorm"
"github.com/radyatamaa/loyalti-go-echo/src/domain/model"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"testing"
"time"
)
type CardSuite struct {
suite.Suite
DB *gorm.DB
mock sqlmock.Sqlmock
card_repository CardRepository
card *model.Card
}
func (s *CardSuite) SetupSuite(){
fmt.Println("test suite")
var (
db *sql.DB
err error
)
fmt.Println("test 2")
db, s.mock, err = sqlmock.New()
require.NoError(s.T(), err)
fmt.Println("test 3")
s.DB, err = gorm.Open("sqlserver", db)
require.NoError(s.T(), err)
fmt.Println("test 4")
s.DB.LogMode(true)
fmt.Println("test 5")
s.card_repository = CreateCardRepository(s.DB)
fmt.Println("test terlewati")
}
func (s *CardSuite) AfterTest(_, _ string){
require.NoError(s.T(), s.mock.ExpectationsWereMet())
}
func TestInitCard(t *testing.T){
suite.Run(t, new(CardSuite))
}
type card_connection_mock struct {
mock.Mock
}
func (c card_connection_mock) ConnectionDB() (gorm *gorm.DB) {
fmt.Println("connection mock")
return
}
func (s *CardSuite) Test_Create_Card(){
fmt.Println("test 1")
var (
card = model.Card{
Id: guid.NewString(),
Created: time.Now(),
CreatedBy: "",
Modified: time.Now(),
ModifiedBy: "",
Active: true,
IsDeleted: false,
Deleted: nil,
DeletedBy: "",
Title: "Kartue",
Description: "Deskripsi",
FontColor: "Black",
TemplateColor: "White",
IconImage: "",
TermsAndCondition: "TnC",
Benefit: "1 gelas TeaJus",
ValidUntil: time.Time{},
CurrentPoint: 0,
IsValid: true,
ProgramId: 2,
CardType: "Chop",
IconImageStamp: "",
MerchantId: 2,
Tier: "",
}
)
fmt.Println("test 2")
err := s.card_repository.CreateCard(&card)
fmt.Println("test 3")
require.NoError(s.T(), err)
fmt.Println("test 4")
}
func (s *CardSuite) Test_Delete_Card(){
fmt.Println("test 1")
var(
kartu = model.Card{
Id: "088c4c24-7ff6-4f4b-a059-50187e5941e1",
}
)
fmt.Println("test 2")
err := s.card_repository.DeleteCard(&kartu)
fmt.Println("test 3")
require.NoError(s.T(), err)
fmt.Println("test 4")
}
func (s *CardSuite) Test_Update_Card(){
fmt.Println("Test update card")
var (
kartu = model.Card{
Id: "f584d39f-ac6b-445b-a592-a98071d5d4e1",
Active: true,
DeletedBy: "",
Title: "KARTU POINT",
Description: "Deskripsi",
FontColor: "White",
TemplateColor: "Black",
IconImage: "Icon",
TermsAndCondition: "TnC",
Benefit: "1 Kopi",
ValidUntil: time.Time{},
CurrentPoint: 200,
IsValid: true,
ProgramId: 1,
CardType: "Point",
IconImageStamp: "",
MerchantId: 2,
Tier: "",
}
)
fmt.Println("test update 1")
err := s.card_repository.UpdateCard(&kartu)
fmt.Println("test update 2")
require.NoError(s.T(), err)
fmt.Println("test update 3")
}
|
// Copyright (c) 2018 Andreas Auernhammer. All rights reserved.
// Use of this source code is governed by a license that can be
// found in the LICENSE file.
// +build amd64,!gccgo,!appengine
package siv
import (
"crypto/aes"
"crypto/cipher"
"crypto/subtle"
"golang.org/x/sys/cpu"
)
func polyval(tag *[16]byte, additionalData, plaintext, key []byte)
func aesGcmXORKeyStream(dst, src, iv, keys []byte, keyLen uint64)
func newGCM(key []byte) aead {
if cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ {
block, _ := aes.NewCipher(key)
return &aesGcmSivAsm{block: block, keyLen: len(key)}
}
return newGCMGeneric(key)
}
var _ aead = (*aesGcmSivAsm)(nil)
type aesGcmSivAsm struct {
block cipher.Block
keyLen int
}
func (c *aesGcmSivAsm) seal(ciphertext, nonce, plaintext, additionalData []byte) {
encKey, authKey := deriveKeys(nonce, c.block, c.keyLen)
var tag [16]byte
polyval(&tag, additionalData, plaintext, authKey)
for i := range nonce {
tag[i] ^= nonce[i]
}
tag[15] &= 0x7f
var encKeys [240]byte
keySchedule(encKeys[:], encKey)
encryptBlock(tag[:], tag[:], encKeys[:], uint64(len(encKey)))
ctrBlock := tag
ctrBlock[15] |= 0x80
aesGcmXORKeyStream(ciphertext, plaintext, ctrBlock[:], encKeys[:], uint64(len(encKey)))
copy(ciphertext[len(plaintext):], tag[:])
}
func (c *aesGcmSivAsm) open(plaintext, nonce, ciphertext, additionalData []byte) error {
tag := ciphertext[len(ciphertext)-16:]
ciphertext = ciphertext[:len(ciphertext)-16]
encKey, authKey := deriveKeys(nonce, c.block, c.keyLen)
var ctrBlock [16]byte
copy(ctrBlock[:], tag)
ctrBlock[15] |= 0x80
var encKeys [240]byte
keySchedule(encKeys[:], encKey)
aesGcmXORKeyStream(plaintext, ciphertext, ctrBlock[:], encKeys[:], uint64(len(encKey)))
var sum [16]byte
polyval(&sum, additionalData, plaintext, authKey)
for i := range nonce {
sum[i] ^= nonce[i]
}
sum[15] &= 0x7f
encryptBlock(sum[:], sum[:], encKeys[:], uint64(len(encKey)))
if subtle.ConstantTimeCompare(sum[:], tag[:]) != 1 {
for i := range plaintext {
plaintext[i] = 0
}
return errOpen
}
return nil
}
|
package configuration
import (
"io/ioutil"
"log"
"net/http"
)
func GetRobotsHandler(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte(GetRobots()))
}
func GetRobots() string {
content, err := ioutil.ReadFile(Conf.GetFilePath("static/robots.txt"))
if err != nil {
log.Panicf("Erreur lors la lecture du fichier robots.txt : %s", err.Error())
}
return string(content)
}
func GetSitemapHandler(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte(GetSitemap()))
writer.Header().Set("Content-Type", "application/xml")
}
func GetSitemap() string {
content, err := ioutil.ReadFile(Conf.GetFilePath("static/sitemap.xml"))
if err != nil {
log.Panicf("Erreur lors la lecture du fichier robots.txt : %s", err.Error())
}
return string(content)
}
|
package main
import (
"github.com/gorilla/mux"
"encoding/json"
"fmt"
"net/http"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var db *gorm.db
var err error
type Person struct {
gorm.Model
Id string
Firstname string
Lastname string
Age string
Address string
}
func InitiaMigration() {
db, err = gorm.Open("sqlite3", "test.db")
if err != nill {
fmt.Println(err.Erroe())
panic("Failed to connect to database")
}
defer db.Close()
db.AutoMigrate(&Person{})
}
func FindAllPersons(w http.ResponseWriter, r *http.Request) {
db, err = gorm.Open("sqlite3", "person.db")
if err != nil {
panic("Unable to connect to the database")
}
defer db.close()
var persons []Person
db.Find(&persons)
json.NewEncoder(w).Encode(persons)
}
func NewPersonCreate(w http.ResponseWriter, r *http.Request){
db, err = gorm.Open("sqlite3", "person.db")
if err != nil {
panic("Unable to connect to the database")
}
defer db.close()
vars := mux.Vars(r)
firstname := vars("firstname")
lastname := vars("lastname")
age := vars("age")
address := vars("address")
db.Create(&Person{Firstname: firstname, Lastname: lastname, Age: age, Address: address})
fmt.Fprintf(w, "New Person Created")
}
func FindPersonByFirstName(w http.ResponseWriter, r *http.Request){
db, err = gorm.Open("sqlite3", "person.db")
if err != nil {
panic("Unable to connect to the database")
}
defer db.close()
vars := mux.Vars(r)
firstname := vars["firstname"]
var person Person
db.Where("firstname = ?", firstname).Find($person)
}
func FindPersonByAge(w http.ResponseWriter, r *http.Request){
db, err = gorm.Open("sqlite3", "person.db")
if err != nil {
panic("Unable to connect to the database")
}
defer db.close()
vars := mux.Vars(r)
firstname := vars["age"]
var person Person
db.Where("age = ?", age).Find($person)
}
func DeletePersonByFirstName(w http.ResponseWriter, r *http.Request){
db, err = gorm.Open("sqlite3", "person.db")
if err != nil {
panic("Unable to connect to the database")
}
defer db.close()
vars := mux.Vars(r)
firstname := vars["firstname"]
var person Person
db.Where("firstname = ?", firstname).Find($person)
db.Delete(&person)
fmt.Fprintf(w, "Person Deleted")
}
|
package main
import (
"encoding/json"
"fmt"
"regexp"
"strings"
)
// PrettyPrint prints objects in a readable format for debugging
func PrettyPrint(v interface{}) (err error) {
b, err := json.MarshalIndent(v, "", " ")
if err == nil {
fmt.Sprint(string(b))
}
return
}
// Detent removes leading tab from string
func detent(s string) string {
return regexp.MustCompile("(?m)^[\t]*").ReplaceAllString(s, "")
}
// standardizeSpaces removes extra spaces and trims string
func standardizeSpaces(s string) string {
return strings.Join(strings.Fields(s), " ")
}
|
package runner
// This file contains the data structures used by the CUDA package that are used
// for when the platform is and is not supported
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/go-stack/stack"
"github.com/karlmutch/errors"
"github.com/lthibault/jitterbug"
)
type device struct {
UUID string `json:"uuid"`
Name string `json:"name"`
Temp uint `json:"temp"`
Powr uint `json:"powr"`
MemTot uint64 `json:"memtot"`
MemUsed uint64 `json:"memused"`
MemFree uint64 `json:"memfree"`
EccFailure *errors.Error `json:"eccfailure"`
}
type cudaDevices struct {
Devices []device `json:"devices"`
}
type GPUTrack struct {
UUID string // The UUID designation for the GPU being managed
Group string // The user grouping to which this GPU has been bound
Slots uint // The number of logical slots the GPU based on its size has
Mem uint64 // The amount of memory the GPU posses
FreeSlots uint // The number of free logical slots the GPU has available
FreeMem uint64 // The amount of free memory the GPU has
EccFailure *errors.Error // Any Ecc failure related error messages, nil if no errors encounted
}
type gpuTracker struct {
Allocs map[string]*GPUTrack
sync.Mutex
}
var (
// A map keyed on the nvidia device UUID containing information about cards and
// their occupancy by the go runner.
//
gpuAllocs gpuTracker
// UseGPU is used for specific types of testing to disable GPU tests when there
// are GPU cards potentially present but they need to be disabled, this flag
// is not used during production to change behavior in any way
UseGPU *bool
CudaInitErr *errors.Error = nil
)
func init() {
temp := true
UseGPU = &temp
gpuDevices, err := getCUDAInfo()
if err != nil {
CudaInitErr = &err
fmt.Fprintf(os.Stderr, "Warning: %s\n", *CudaInitErr)
return
}
visDevices := strings.Split(os.Getenv("CUDA_VISIBLE_DEVICES"), ",")
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
gpuAllocs.Allocs = make(map[string]*GPUTrack, len(visDevices))
// If the visDevices were specified use then to generate existing entries inside the device map.
// These entries will then get filled in later.
//
// Look to see if we have any index values in here, it really should be all UUID strings.
// Warn if we find some, but still continue.
warned := false
for _, id := range visDevices {
if len(id) == 0 {
continue
}
if i, err := strconv.Atoi(id); err == nil {
if !warned {
warned = true
fmt.Fprintf(os.Stderr, "CUDA_VISIBLE_DEVICES should be using UUIDs not indexes\n")
}
if i > len(gpuDevices.Devices) {
fmt.Fprintf(os.Stderr, "CUDA_VISIBLE_DEVICES contained an index %d past the known population %d of GPU cards\n", i, len(gpuDevices.Devices))
}
gpuAllocs.Allocs[gpuDevices.Devices[i].UUID] = &GPUTrack{}
} else {
gpuAllocs.Allocs[id] = &GPUTrack{}
}
}
if len(gpuAllocs.Allocs) == 0 {
for _, dev := range gpuDevices.Devices {
gpuAllocs.Allocs[dev.UUID] = &GPUTrack{}
}
}
// Scan the inventory, checking matches if they were specified in the visibility env var and then fill
// in real world data
//
for _, dev := range gpuDevices.Devices {
// Dont include devices that were not specified by CUDA_VISIBLE_DEVICES
if _, isPresent := gpuAllocs.Allocs[dev.UUID]; !isPresent {
continue
}
track := &GPUTrack{
UUID: dev.UUID,
Mem: dev.MemFree,
Slots: 1,
FreeSlots: 1,
EccFailure: dev.EccFailure,
}
switch {
case strings.Contains(dev.Name, "GTX 1050"),
strings.Contains(dev.Name, "GTX 1060"):
track.Slots = 1
case strings.Contains(dev.Name, "GTX 1070"),
strings.Contains(dev.Name, "GTX 1080"):
track.Slots = 2
case strings.Contains(dev.Name, "TITAN X"):
track.Slots = 4
}
track.FreeSlots = track.Slots
track.FreeMem = track.Mem
gpuAllocs.Allocs[dev.UUID] = track
}
}
// Having initialized all of the devices in the tracking map a go func
// is started that will check the devices for ECC and other errors marking
// failed GPUs
//
func MonitorGPUs(ctx context.Context, errC chan<- errors.Error) {
t := jitterbug.New(time.Second*30, &jitterbug.Norm{Stdev: time.Second * 3})
defer t.Stop()
for {
select {
case <-t.C:
gpuDevices, err := getCUDAInfo()
if err != nil {
select {
case errC <- err:
default:
fmt.Println(err)
}
}
// Look at allhe GPUs we have in our hardware config
for _, dev := range gpuDevices.Devices {
if dev.EccFailure != nil {
gpuAllocs.Lock()
// Check to see if the hardware GPU had a failure
// and if it is in the tracking table and does
// not yet have an error logged log the error
// in the tracking table
if gpu, isPresent := gpuAllocs.Allocs[dev.UUID]; isPresent {
if gpu.EccFailure == nil {
gpu.EccFailure = dev.EccFailure
gpuAllocs.Allocs[gpu.UUID] = gpu
}
}
gpuAllocs.Unlock()
select {
case errC <- *dev.EccFailure:
default:
fmt.Println(dev.EccFailure)
}
}
}
case <-ctx.Done():
return
}
}
}
// GPUSlots gets the free and total number of GPU capacity slots within
// the machine
//
func GPUSlots() (cnt uint, freeCnt uint) {
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
for _, alloc := range gpuAllocs.Allocs {
cnt += alloc.Slots
freeCnt += alloc.FreeSlots
}
return cnt, freeCnt
}
// LargestFreeGPUSlots gets the largest number of single device free GPU slots
//
func LargestFreeGPUSlots() (cnt uint) {
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
for _, alloc := range gpuAllocs.Allocs {
if alloc.FreeSlots > cnt {
cnt = alloc.FreeSlots
}
}
return cnt
}
func LargestFreeGPUMem() (freeMem uint64) {
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
for _, alloc := range gpuAllocs.Allocs {
if alloc.Slots != 0 && alloc.FreeMem > freeMem {
freeMem = alloc.FreeMem
}
}
return freeMem
}
// FindGPUs is used to locate all GPUs matching the criteria within the
// parameters supplied. The free values specify minimums for resources.
// If the pgroup is not set then the GPUs not assigned to any group will
// be selected using the free values, and if it is specified then
// the group must match along with the minimums for the resources. Any GPUs
// that have recorded Ecc errors will not be included
//
func FindGPUs(group string, freeSlots uint, freeMem uint64) (gpus map[string]GPUTrack) {
gpus = map[string]GPUTrack{}
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
for _, gpu := range gpuAllocs.Allocs {
if group == gpu.Group && gpu.EccFailure == nil &&
freeSlots <= gpu.FreeSlots && freeMem <= gpu.FreeMem {
gpus[gpu.UUID] = *gpu
}
}
return gpus
}
type GPUAllocated struct {
cudaDev string // The device identifier this allocation was successful against
group string // The users group that the allocation was made for
slots uint // The number of GPU slots given from the allocation
mem uint64 // The amount of memory given to the allocation
Env map[string]string // Any environment variables the device allocator wants the runner to use
}
// DumpGPU is used to return to a monitoring system a JSOBN based representation of the current
// state of GPU allocations
//
func DumpGPU() (dump string) {
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
b, err := json.Marshal(&gpuAllocs)
if err != nil {
return ""
}
return string(b)
}
// AllocGPU will attempt to find a free CUDA capable GPU and assign it to the client. It will
// on finding a device set the appropriate values in the allocated return structure that the client
// can use to manage their resource consumption to match the permitted limits.
//
// At this time allocations cannot occur across multiple devices, only within a single device.
//
func AllocGPU(group string, maxGPU uint, maxGPUMem uint64) (alloc *GPUAllocated, err errors.Error) {
alloc = &GPUAllocated{
Env: map[string]string{},
}
if maxGPU == 0 {
return alloc, nil
}
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
// Look for any free slots inside the inventory that are either completely free or occupy a card already
// that has some free slots left
//
matchedDevice := ""
for _, dev := range gpuAllocs.Allocs {
if dev.Group == "" {
if dev.FreeSlots >= maxGPU && dev.FreeMem >= maxGPUMem && dev.EccFailure == nil {
matchedDevice = dev.UUID
}
continue
}
// Pack the work in naively, enhancements could include looking for the best
// fitting gaps etc
if dev.Group == group && dev.FreeSlots >= maxGPU && dev.FreeMem >= maxGPUMem && dev.EccFailure == nil {
matchedDevice = dev.UUID
break
}
}
if matchedDevice == "" {
return nil, errors.New(fmt.Sprintf("no available slots where found for group %s", group)).With("stack", stack.Trace().TrimRuntime())
}
// Determine number of slots that could be allocated and the max requested
//
slots := maxGPU
if slots > gpuAllocs.Allocs[matchedDevice].FreeSlots {
slots = gpuAllocs.Allocs[matchedDevice].FreeSlots
}
if maxGPUMem == 0 {
// If the user does not know take it all, burn it to the ground
slots = gpuAllocs.Allocs[matchedDevice].FreeSlots
maxGPUMem = gpuAllocs.Allocs[matchedDevice].FreeMem
}
gpuAllocs.Allocs[matchedDevice].Group = group
gpuAllocs.Allocs[matchedDevice].FreeSlots -= slots
gpuAllocs.Allocs[matchedDevice].FreeMem -= maxGPUMem
alloc = &GPUAllocated{
cudaDev: matchedDevice,
group: group,
slots: slots,
mem: maxGPUMem,
Env: map[string]string{"CUDA_VISIBLE_DEVICES": matchedDevice},
}
return alloc, nil
}
// ReturnGPU releases the GPU allocation passed in. It will validate some of the allocation
// details but is an honors system.
//
func ReturnGPU(alloc *GPUAllocated) (err errors.Error) {
if alloc.slots == 0 || alloc.mem == 0 {
return nil
}
gpuAllocs.Lock()
defer gpuAllocs.Unlock()
// Make sure that the allocation is still valid
dev, isPresent := gpuAllocs.Allocs[alloc.cudaDev]
if !isPresent {
return errors.New(fmt.Sprintf("cuda device %s is no longer in service", alloc.cudaDev)).With("stack", stack.Trace().TrimRuntime())
}
// Make sure the device was not reset and is now doing something else entirely
if dev.Group != alloc.group {
return errors.New(fmt.Sprintf("cuda device %s is no longer assigned to group %s, instead it is running %s", alloc.cudaDev, alloc.group, dev.Group)).With("stack", stack.Trace().TrimRuntime())
}
gpuAllocs.Allocs[alloc.cudaDev].FreeSlots += alloc.slots
gpuAllocs.Allocs[alloc.cudaDev].FreeMem += alloc.mem
// If there is no work running or left on the GPU drop it from the group constraint
//
if gpuAllocs.Allocs[alloc.cudaDev].FreeSlots == gpuAllocs.Allocs[alloc.cudaDev].Slots &&
gpuAllocs.Allocs[alloc.cudaDev].FreeMem == gpuAllocs.Allocs[alloc.cudaDev].Mem {
gpuAllocs.Allocs[alloc.cudaDev].Group = ""
}
return nil
}
|
package main
import (
"log"
"os"
"os/signal"
"github.com/sacOO7/gowebsocket"
)
func main() {
log.Println("Starting up...")
interrupt := make(chan os.Signal, 1) // I dont really understand this full yet?
signal.Notify(interrupt, os.Interrupt)
socket := gowebsocket.New("ws://echo.websocket.org/")
socket.OnConnectError = func(err error, socket gowebsocket.Socket) {
log.Fatal("Received connect error - ", err)
}
socket.OnConnected = func(socket gowebsocket.Socket) {
log.Println("Connected to server")
}
socket.OnTextMessage = func(message string, socket gowebsocket.Socket) {
log.Println("Recevied message - " + message)
}
socket.OnPingReceived = func(data string, socket gowebsocket.Socket) {
log.Println("Receive ping - " + data)
}
socket.OnPongReceived = func(data string, socket gowebsocket.Socket) {
log.Println("Receive pong - " + data)
}
socket.OnDisconnected = func(err error, socket gowebsocket.Socket) {
log.Println("Disconnect from server")
return
}
socket.Connect()
socket.SendText("Throughtworks guys are awsome !!!!")
for {
select {
case <-interrupt:
log.Println("interrupt")
socket.Close()
return
}
}
}
|
package components
import (
"github.com/GoAdminGroup/go-admin/template/types"
"html/template"
)
type RowAttribute struct {
Name string
Content template.HTML
types.Attribute
}
// 盢把计砞竚RowAttribute(struct)
func (compo *RowAttribute) SetContent(value template.HTML) types.RowAttribute {
compo.Content = value
return compo
}
// 盢把计砞竚RowAttribute(struct)
func (compo *RowAttribute) AddContent(value template.HTML) types.RowAttribute {
compo.Content += value
return compo
}
// 盢才TreeAttribute.TemplateList["components/tree-header"](map[string]string)text(string)
// 钡帝盢把计compo糶buffer(bytes.Buffer)い程块HTML
func (compo *RowAttribute) GetContent() template.HTML {
// template\components\composer.go
// 盢才TreeAttribute.TemplateList["components/row"](map[string]string)text(string)钡帝盢把计の睰倒穝家狾秆猂家狾砰
// 盢把计compo糶buffer(bytes.Buffer)い程块HTML
return ComposeHtml(compo.TemplateList, *compo, "row")
}
|
// Copyright 2018 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 testutil
import (
"context"
"fmt"
"testing"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/logutil"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// SessionExecInGoroutine export for testing.
func SessionExecInGoroutine(s kv.Storage, dbName, sql string, done chan error) {
ExecMultiSQLInGoroutine(s, dbName, []string{sql}, done)
}
// ExecMultiSQLInGoroutine exports for testing.
func ExecMultiSQLInGoroutine(s kv.Storage, dbName string, multiSQL []string, done chan error) {
go func() {
se, err := session.CreateSession4Test(s)
if err != nil {
done <- errors.Trace(err)
return
}
defer se.Close()
_, err = se.Execute(context.Background(), "use "+dbName)
if err != nil {
done <- errors.Trace(err)
return
}
for _, sql := range multiSQL {
rs, err := se.Execute(context.Background(), sql)
if err != nil {
done <- errors.Trace(err)
return
}
if rs != nil {
done <- errors.Errorf("RecordSet should be empty")
return
}
done <- nil
}
}()
}
// ExtractAllTableHandles extracts all handles of a given table.
func ExtractAllTableHandles(se session.Session, dbName, tbName string) ([]int64, error) {
dom := domain.GetDomain(se)
tbl, err := dom.InfoSchema().TableByName(model.NewCIStr(dbName), model.NewCIStr(tbName))
if err != nil {
return nil, err
}
err = sessiontxn.NewTxn(context.Background(), se)
if err != nil {
return nil, err
}
var allHandles []int64
err = tables.IterRecords(tbl, se, nil,
func(h kv.Handle, _ []types.Datum, _ []*table.Column) (more bool, err error) {
allHandles = append(allHandles, h.IntValue())
return true, nil
})
return allHandles, err
}
// FindIdxInfo is to get IndexInfo by index name.
func FindIdxInfo(dom *domain.Domain, dbName, tbName, idxName string) *model.IndexInfo {
tbl, err := dom.InfoSchema().TableByName(model.NewCIStr(dbName), model.NewCIStr(tbName))
if err != nil {
logutil.BgLogger().Warn("cannot find table", zap.String("dbName", dbName), zap.String("tbName", tbName))
return nil
}
return tbl.Meta().FindIndexByName(idxName)
}
// SubStates is a slice of SchemaState.
type SubStates = []model.SchemaState
// TestMatchCancelState is used to test whether the cancel state matches.
func TestMatchCancelState(t *testing.T, job *model.Job, cancelState interface{}, sql string) bool {
switch v := cancelState.(type) {
case model.SchemaState:
if job.Type == model.ActionMultiSchemaChange {
msg := fmt.Sprintf("unexpected multi-schema change(sql: %s, cancel state: %s)", sql, v)
require.Failf(t, msg, "use []model.SchemaState as cancel states instead")
return false
}
return job.SchemaState == v
case SubStates: // For multi-schema change sub-jobs.
if job.MultiSchemaInfo == nil {
msg := fmt.Sprintf("not multi-schema change(sql: %s, cancel state: %v)", sql, v)
require.Failf(t, msg, "use model.SchemaState as the cancel state instead")
return false
}
require.Equal(t, len(job.MultiSchemaInfo.SubJobs), len(v), sql)
for i, subJobSchemaState := range v {
if job.MultiSchemaInfo.SubJobs[i].SchemaState != subJobSchemaState {
return false
}
}
return true
default:
return false
}
}
|
package service
import (
"context"
"testing"
"time"
"github.com/micro/go-micro/client"
sample "github.com/ob-vss-ss19/sample-micro-tests/srv/sample/proto"
"github.com/stretchr/testify/assert"
)
func TestServiceStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
go RunService(ctx, true)
time.Sleep(50 * time.Millisecond)
var client client.Client
srvClient := sample.NewSampleService("go.micro.srv.sample", client)
var req sample.ListRequest
rsp, err := srvClient.List(context.TODO(), &req)
assert.Nil(t, err)
assert.Len(t, rsp.Items, 2)
cancel()
time.Sleep(1 * time.Second)
}
|
package main
import (
"encoding/json"
"fmt"
)
/*
首字母大写:公有
首字母小写:私有
*/
type Role struct {
Uid []int
}
type User struct {
ID int `json:"id"` // 设置转后的key
Name string
Role
}
func main() {
var u = User{
ID: 33,
Name: "yyx",
Role: Role{
Uid: []int{1, 2, 3},
},
}
fmt.Printf("%#v -- %T\n", u, u)
jsonByte, _ := json.Marshal(u)
fmt.Println(jsonByte)
jsonStr := string(jsonByte)
fmt.Println(jsonStr)
var dict = `{"ID":33,"Name":"yyx"}`
fmt.Println(dict)
var u1 User
err := json.Unmarshal([]byte(dict), &u1)
if err != nil {
fmt.Println(err)
}
fmt.Println(u1)
fmt.Printf("%v %T\n", u1, u1)
fmt.Printf("%#v %T\n", u1, u1)
}
|
package main
/*
* @lc app=leetcode id=84 lang=golang
*
* [84] Largest Rectangle in Histogram
*/
// Solution 2: 单调栈(十分类似单调队列)
// 只需确保栈中元素是单调递增就好
func largestRectangleArea(heights []int) int {
maxArea := 0
stack := make(stack_84, 0, len(heights))
heights = append(heights, -1) // 在尾部加一个元素,确保最后栈中元素被全部弹出
for i := 0; i < len(heights); i++ {
for !stack.isEmpty() && heights[stack.peek()] > heights[i] {
h := heights[stack.pop()]
var w int
if stack.isEmpty() {
w = i
} else {
w = i - stack.peek() - 1
}
if h*w > maxArea {
maxArea = h * w
}
}
stack.push(i)
}
return maxArea
}
// Solution 1: 预处理,遍历每个结点,
// 重点在 p=fromLeft[p] 代替 p--, 将时间复杂度降低一个级别
// 巧妙至极
func largestRectangleArea_1(heights []int) int {
if len(heights) == 0 {
return 0
}
fromLeft := make([]int, len(heights))
fromRight := make([]int, len(heights))
fromLeft[0] = -1
fromRight[len(heights)-1] = len(heights)
for i := 1; i < len(heights); i++ {
p := i - 1
for p >= 0 && heights[p] >= heights[i] {
p = fromLeft[p]
}
fromLeft[i] = p
}
for i := len(heights) - 2; i >= 0; i-- {
p := i + 1
for p < len(heights) && heights[p] >= heights[i] {
p = fromRight[p]
}
fromRight[i] = p
}
maxArea := 0
for i := 0; i < len(heights); i++ {
area := heights[i] * (fromRight[i] - fromLeft[i] - 1)
if area > maxArea {
maxArea = area
}
}
return maxArea
}
// 使用切片实现的简单栈
type stack_84 []int
func (s *stack_84) isEmpty() bool {
return len(*s) == 0
}
func (s *stack_84) peek() int {
return (*s)[len(*s)-1]
}
func (s *stack_84) push(v int) {
*s = append(*s, v)
}
func (s *stack_84) pop() int {
res := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return res
}
|
// Copyright 2023 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 asyncloaddata
import (
"encoding/json"
"sync"
"go.uber.org/atomic"
"golang.org/x/exp/maps"
)
// LogicalImportProgress is the progress info of the logical import mode.
type LogicalImportProgress struct {
// LoadedFileSize is the size of the data that's loaded in bytes. It's
// larger than the actual loaded data size, but due to the fact that reading
// is once-a-block and a block may generate multiple tasks that are
// concurrently executed, we can't know the actual loaded data size easily.
LoadedFileSize atomic.Int64
}
// PhysicalImportProgress is the progress info of the physical import mode.
type PhysicalImportProgress struct {
// ReadRowCnt is the number of rows read from data files.
// Lines ignored by IGNORE N LINES clause is not included.
ReadRowCnt atomic.Uint64
// EncodeFileSize is the size of the file that has finished KV encoding in bytes.
// it should equal to SourceFileSize eventually.
EncodeFileSize atomic.Int64
colSizeMu sync.Mutex
colSizeMap map[int64]int64
}
// Progress is the progress of the LOAD DATA task.
type Progress struct {
// SourceFileSize is the size of the source file in bytes. When we can't get
// the size of the source file, it will be set to -1.
// Currently, the value is read by seek(0, end), when LOAD DATA LOCAL we wrap
// SimpleSeekerOnReadCloser on MySQL client connection which doesn't support
// it.
SourceFileSize int64
*LogicalImportProgress `json:",inline"`
*PhysicalImportProgress `json:",inline"`
// LoadedRowCnt is the number of rows that has been loaded.
// for physical mode, it's the number of rows that has been imported into TiKV.
// in SHOW LOAD JOB we call it Imported_Rows, to make it compatible with 7.0,
// the variable name is not changed.
LoadedRowCnt atomic.Uint64
}
// NewProgress creates a new Progress.
// todo: better pass import mode, but it causes import cycle.
func NewProgress(logicalImport bool) *Progress {
var li *LogicalImportProgress
var pi *PhysicalImportProgress
if logicalImport {
li = &LogicalImportProgress{}
} else {
pi = &PhysicalImportProgress{
colSizeMap: make(map[int64]int64),
}
}
return &Progress{
SourceFileSize: -1,
LogicalImportProgress: li,
PhysicalImportProgress: pi,
}
}
// AddColSize adds the size of the column to the progress.
func (p *Progress) AddColSize(colSizeMap map[int64]int64) {
p.colSizeMu.Lock()
defer p.colSizeMu.Unlock()
for key, value := range colSizeMap {
p.colSizeMap[key] += value
}
}
// GetColSize returns the size of the column.
func (p *Progress) GetColSize() map[int64]int64 {
p.colSizeMu.Lock()
defer p.colSizeMu.Unlock()
return maps.Clone(p.colSizeMap)
}
// String implements the fmt.Stringer interface.
func (p *Progress) String() string {
bs, _ := json.Marshal(p)
return string(bs)
}
// ProgressFromJSON creates Progress from a JSON string.
func ProgressFromJSON(bs []byte) (*Progress, error) {
var p Progress
err := json.Unmarshal(bs, &p)
return &p, err
}
|
package service
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-ocf/cloud/cloud2cloud-connector/events"
"github.com/go-ocf/cloud/cloud2cloud-gateway/store"
pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb"
"github.com/go-ocf/kit/log"
kitNetGrpc "github.com/go-ocf/kit/net/grpc"
)
type devicesSubscription struct {
rh *RequestHandler
goroutinePoolGo GoroutinePoolGoFunc
}
func newDevicesSubscription(rh *RequestHandler, goroutinePoolGo GoroutinePoolGoFunc) *devicesSubscription {
return &devicesSubscription{
rh: rh,
goroutinePoolGo: goroutinePoolGo,
}
}
func handleSubscription(ctx context.Context, rh *RequestHandler, sub store.DevicesSubscription) error {
devicesRegistered := make(map[string]events.Device)
devicesOnline := make(map[string]events.Device)
devicesOffline := make(map[string]events.Device)
authorizationContext := pbCQRS.AuthorizationContext{
UserId: sub.UserID,
}
devices, err := rh.GetDevices(kitNetGrpc.CtxWithToken(ctx, sub.AccessToken), nil, authorizationContext)
if err != nil {
sub, errPop := rh.store.PopSubscription(ctx, sub.ID)
if errPop != nil {
return err
}
_, _ = emitEvent(ctx, events.EventType_SubscriptionCanceled, sub, func(ctx context.Context, subscriptionID string) (uint64, error) {
return sub.SequenceNumber, nil
}, nil)
return err
}
lastDevicesRegistered := make(events.DevicesRegistered, 0, len(devices))
lastDevicesOnline := make(events.DevicesOnline, 0, len(devices))
lastDevicesOffline := make(events.DevicesOffline, 0, len(devices))
for _, dev := range devices {
devicesRegistered[dev.Device.ID] = events.Device{
ID: dev.Device.ID,
}
lastDevicesRegistered = append(lastDevicesRegistered, events.Device{
ID: dev.Device.ID,
})
if dev.Status == Status_ONLINE {
devicesOnline[dev.Device.ID] = events.Device{
ID: dev.Device.ID,
}
lastDevicesOnline = append(lastDevicesOnline, events.Device{
ID: dev.Device.ID,
})
} else {
devicesOffline[dev.Device.ID] = events.Device{
ID: dev.Device.ID,
}
lastDevicesOffline = append(lastDevicesOffline, events.Device{
ID: dev.Device.ID,
})
}
}
devicesUnregistered := make(map[string]events.Device)
for _, dev := range sub.LastDevicesRegistered {
dev, ok := devicesRegistered[dev.ID]
if ok {
delete(devicesRegistered, dev.ID)
} else {
devicesUnregistered[dev.ID] = dev
}
}
for _, dev := range sub.LastDevicesOnline {
delete(devicesOnline, dev.ID)
}
for _, dev := range sub.LastDevicesOffline {
delete(devicesOffline, dev.ID)
}
if sub.SequenceNumber != 0 && len(devicesRegistered) == 0 && len(devicesUnregistered) == 0 && len(devicesOnline) == 0 && len(devicesOffline) == 0 {
return nil
}
log.Debugf("emit events for subscription %+v", sub)
for _, eventType := range sub.EventTypes {
switch eventType {
case events.EventType_DevicesRegistered:
if len(devicesRegistered) > 0 || sub.SequenceNumber == 0 {
devs := make(events.DevicesRegistered, 0, len(devicesRegistered))
for _, dev := range devicesRegistered {
devs = append(devs, dev)
}
remove, err := emitEvent(ctx, eventType, sub.Subscription, rh.store.IncrementSubscriptionSequenceNumber, devs)
if remove {
rh.store.PopSubscription(ctx, sub.ID)
}
if err != nil {
return fmt.Errorf("cannot emit event: %w", err)
}
}
case events.EventType_DevicesUnregistered:
if len(devicesUnregistered) > 0 || sub.SequenceNumber == 0 {
devs := make(events.DevicesUnregistered, 0, len(devicesUnregistered))
for _, dev := range devicesUnregistered {
devs = append(devs, dev)
}
remove, err := emitEvent(ctx, eventType, sub.Subscription, rh.store.IncrementSubscriptionSequenceNumber, devs)
if remove {
rh.store.PopSubscription(ctx, sub.ID)
}
if err != nil {
return fmt.Errorf("cannot emit event: %w", err)
}
}
case events.EventType_DevicesOnline:
if len(devicesOnline) > 0 || sub.SequenceNumber == 0 {
devs := make(events.DevicesOnline, 0, len(devicesOnline))
for _, dev := range devicesOnline {
devs = append(devs, dev)
}
remove, err := emitEvent(ctx, eventType, sub.Subscription, rh.store.IncrementSubscriptionSequenceNumber, devs)
if remove {
rh.store.PopSubscription(ctx, sub.ID)
}
if err != nil {
return fmt.Errorf("cannot emit event: %w", err)
}
}
case events.EventType_DevicesOffline:
if len(devicesOffline) > 0 || sub.SequenceNumber == 0 {
devs := make(events.DevicesOffline, 0, len(devicesOffline))
for _, dev := range devicesOffline {
devs = append(devs, dev)
}
remove, err := emitEvent(ctx, eventType, sub.Subscription, rh.store.IncrementSubscriptionSequenceNumber, devs)
if remove {
rh.store.PopSubscription(ctx, sub.ID)
}
if err != nil {
return fmt.Errorf("cannot emit event: %w", err)
}
}
}
}
err = rh.store.UpdateDevicesSubscription(ctx, sub.ID, lastDevicesRegistered, lastDevicesOnline, lastDevicesOffline)
if err != nil {
return err
}
return nil
}
func (s *devicesSubscription) Handle(ctx context.Context, iter store.DevicesSubscriptionIter) error {
var wg sync.WaitGroup
for {
var sub store.DevicesSubscription
if !iter.Next(ctx, &sub) {
break
}
wg.Add(1)
err := s.goroutinePoolGo(func() {
defer wg.Done()
err := handleSubscription(ctx, s.rh, sub)
if err != nil {
log.Error(fmt.Errorf("cannot handle subscription %v: %w", sub.ID, err))
}
})
if err != nil {
wg.Done()
}
}
wg.Wait()
return iter.Err()
}
func (s *devicesSubscription) Serve(ctx context.Context, checkInterval time.Duration) {
for {
err := s.rh.store.LoadDevicesSubscriptions(ctx, store.DevicesSubscriptionQuery{
LastCheck: time.Now().Add(-checkInterval),
}, s)
if err != nil {
log.Errorf("cannot server devicesscriptionSubscription: %v", err)
}
select {
case <-time.After(checkInterval):
case <-ctx.Done():
return
}
}
}
|
package master
import (
"fmt"
"net"
"server/libs/log"
"server/share"
"server/util"
"time"
)
type App struct {
Apps map[string]string `json:apps`
MustApps []string `json:mustapps`
}
var (
context *Master
)
type Master struct {
Agent bool
AgentId string
Host string
Port int
LocalIP string
OuterIP string
AppDef App
ConsolePort int
Template string
AppArgs map[string][]byte
tcpListener net.Listener
waitGroup *util.WaitGroupWrapper
app map[int32]*app
quit chan int
agent *Agent
agentlist *AgentList
WaitAgents int
waitfor bool
NoBalance bool
}
func (m *Master) Start() {
context = m
if !m.Agent {
log.TraceInfo("master", "start")
tcpListener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", m.Host, m.Port))
if err != nil {
log.LogError(err)
log.LogFatalf(err)
}
m.tcpListener = tcpListener
tcpserver := &tcp_server{}
m.waitGroup.Wrap(func() { util.TCPServer(m.tcpListener, tcpserver) })
}
if !m.Agent && m.ConsolePort != 0 {
StartConsoleServer(m)
log.LogMessage("console start at:", m.ConsolePort)
}
if m.Agent {
log.TraceInfo("master agent", "start")
m.agent = &Agent{}
m.agent.Connect(m.Host, m.Port, true, m.ConnectToMaster)
} else {
m.agentlist = NewAgentList()
m.waitfor = true
if m.WaitAgents == 0 {
m.waitfor = false
StartApp(m)
}
}
}
func (m *Master) AgentsDown() {
if m.waitfor && m.agentlist.Count() >= m.WaitAgents {
m.waitfor = false
StartAppBlance(m)
}
}
func (m *Master) ConnectToMaster() {
m.agent.Register(m.AgentId, m.NoBalance)
StartApp(m)
}
func (m *Master) Wait(ch chan int) {
m.quit = ch
<-m.quit
}
func (m *Master) Stop() {
m.quit <- 1
}
func (m *Master) Exit() {
log.TraceInfo("master", "stop")
if m.Agent {
m.agent.Close()
} else {
m.agentlist.CloseAll()
}
for _, a := range m.app {
a.Close()
}
if m.tcpListener != nil {
m.tcpListener.Close()
}
log.LogInfo("wait all app quit")
for len(m.app) != 0 {
time.Sleep(time.Second)
}
m.waitGroup.Wait()
}
func (m *Master) CreateApp(reqid string, appid string, appuid int32, typ string, startargs string, callbackapp int32) {
if appuid == 0 {
appuid = GetAppUid()
}
if m.agentlist != nil {
agent := m.agentlist.GetMinLoadAgent()
if agent != nil {
if agent.load < Load {
//远程创建
err := agent.CreateApp(reqid, appid, appuid, typ, startargs, callbackapp)
if err != nil && callbackapp != 0 {
data, err := share.CreateAppBakMsg(reqid, appuid, err.Error())
if err != nil {
log.LogFatalf(err)
}
m.SendToApp(callbackapp, data)
}
return
}
}
}
//本地创建
err := CreateApp(appid, appuid, typ, startargs)
res := "ok"
if err != nil {
res = err.Error()
}
if callbackapp != 0 {
data, err := share.CreateAppBakMsg(reqid, appuid, res)
if err != nil {
log.LogFatalf(err)
}
m.SendToApp(callbackapp, data)
}
}
func (m *Master) SendToApp(app int32, data []byte) error {
if app, exist := m.app[app]; exist {
return app.Send(data)
}
return fmt.Errorf("app not found")
}
func NewMaster() *Master {
m := &Master{}
m.AppArgs = make(map[string][]byte)
m.waitGroup = &util.WaitGroupWrapper{}
m.app = make(map[int32]*app)
return m
}
|
package delivery
import (
"testing"
"github.com/stretchr/testify/suite"
)
type klineServiceTestSuite struct {
baseTestSuite
}
func TestKlineService(t *testing.T) {
suite.Run(t, new(klineServiceTestSuite))
}
// https://binance-docs.github.io/apidocs/delivery/en/#kline-candlestick-data
func (s *klineServiceTestSuite) TestKlines() {
data := []byte(`[
[
1591258320000,
"9640.7",
"9642.4",
"9640.6",
"9642.0",
"206",
1591258379999,
"2.13660389",
48,
"119",
"1.23424865",
"0"
]
]`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
interval := "15m"
limit := 10
startTime := int64(1499040000000)
endTime := int64(1499040000001)
s.assertReq(func(r *request) {
e := newRequest().setParams(params{
"symbol": symbol,
"interval": interval,
"limit": limit,
"startTime": startTime,
"endTime": endTime,
})
s.assertRequestEqual(e, r)
})
klines, err := s.client.NewKlinesService().Symbol(symbol).
Interval(interval).Limit(limit).StartTime(startTime).
EndTime(endTime).Do(newContext())
s.r().NoError(err)
s.Len(klines, 1)
kline1 := &Kline{
OpenTime: 1591258320000,
Open: "9640.7",
High: "9642.4",
Low: "9640.6",
Close: "9642.0",
Volume: "206",
CloseTime: 1591258379999,
QuoteAssetVolume: "2.13660389",
TradeNum: 48,
TakerBuyBaseAssetVolume: "119",
TakerBuyQuoteAssetVolume: "1.23424865",
}
s.assertKlineEqual(kline1, klines[0])
}
func (s *klineServiceTestSuite) assertKlineEqual(e, a *Kline) {
r := s.r()
r.Equal(e.OpenTime, a.OpenTime, "OpenTime")
r.Equal(e.Open, a.Open, "Open")
r.Equal(e.High, a.High, "High")
r.Equal(e.Low, a.Low, "Low")
r.Equal(e.Close, a.Close, "Close")
r.Equal(e.Volume, a.Volume, "Volume")
r.Equal(e.CloseTime, a.CloseTime, "CloseTime")
r.Equal(e.QuoteAssetVolume, a.QuoteAssetVolume, "QuoteAssetVolume")
r.Equal(e.TradeNum, a.TradeNum, "TradeNum")
r.Equal(e.TakerBuyBaseAssetVolume, a.TakerBuyBaseAssetVolume, "TakerBuyBaseAssetVolume")
r.Equal(e.TakerBuyQuoteAssetVolume, a.TakerBuyQuoteAssetVolume, "TakerBuyQuoteAssetVolume")
}
|
package main
import (
"testing"
)
func CopyLocalToRemoteServiceTest(t *testing.T) {
t.Error("Hi")
}
|
package ini
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/saucelabs/saucectl/internal/flags"
"github.com/spf13/pflag"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/Netflix/go-expect"
"github.com/hinshun/vt10x"
"github.com/stretchr/testify/require"
"gotest.tools/v3/fs"
"github.com/saucelabs/saucectl/internal/config"
"github.com/saucelabs/saucectl/internal/credentials"
"github.com/saucelabs/saucectl/internal/cypress"
"github.com/saucelabs/saucectl/internal/devices"
"github.com/saucelabs/saucectl/internal/espresso"
"github.com/saucelabs/saucectl/internal/framework"
"github.com/saucelabs/saucectl/internal/mocks"
"github.com/saucelabs/saucectl/internal/playwright"
"github.com/saucelabs/saucectl/internal/puppeteer"
"github.com/saucelabs/saucectl/internal/region"
"github.com/saucelabs/saucectl/internal/testcafe"
"github.com/saucelabs/saucectl/internal/vmd"
"github.com/saucelabs/saucectl/internal/xcuitest"
)
// Test Case setup is partially reused from:
// - https://github.com/AlecAivazis/survey/blob/master/survey_test.go
// - https://github.com/AlecAivazis/survey/blob/master/survey_posix_test.go
// As everything related to console may result in hanging, it's preferable
// to add a timeout to avoid any test to stay for ages.
func executeQuestionTestWithTimeout(t *testing.T, test questionTest) {
timeout := time.After(2 * time.Second)
done := make(chan bool)
go func() {
executeQuestionTest(t, test)
done <- true
}()
select {
case <-timeout:
t.Fatal("Test timed-out")
case <-done:
}
}
func executeQuestionTest(t *testing.T, test questionTest) {
buf := new(bytes.Buffer)
c, state, err := vt10x.NewVT10XConsole(expect.WithStdout(buf))
require.Nil(t, err)
defer c.Close()
donec := make(chan struct{})
go func() {
defer close(donec)
if lerr := test.procedure(c); lerr != nil {
if lerr.Error() != "read /dev/ptmx: input/output error" {
t.Errorf("error: %v", lerr)
}
}
}()
test.ini.stdio = terminal.Stdio{In: c.Tty(), Out: c.Tty(), Err: c.Tty()}
err = test.execution(test.ini, test.startState)
require.Nil(t, err)
if !reflect.DeepEqual(test.startState, test.expectedState) {
t.Errorf("got: %v, want: %v", test.startState, test.expectedState)
}
// Close the slave end of the pty, and read the remaining bytes from the master end.
c.Tty().Close()
<-donec
t.Logf("Raw output: %q", buf.String())
// Dump the terminal's screen.
t.Logf("\n%s", expect.StripTrailingEmptyLines(state.String()))
}
func stringToProcedure(actions string) func(*expect.Console) error {
return func(c *expect.Console) error {
for _, chr := range actions {
switch chr {
case '↓':
c.Send(string(terminal.KeyArrowDown))
case '↑':
c.Send(string(terminal.KeyArrowUp))
case '✓':
c.Send(string(terminal.KeyEnter))
case '🔚':
c.ExpectEOF()
default:
c.Send(fmt.Sprintf("%c", chr))
}
}
return nil
}
}
type questionTest struct {
name string
ini *initializer
execution func(*initializer, *initConfig) error
procedure func(*expect.Console) error
startState *initConfig
expectedState *initConfig
}
func TestAskFramework(t *testing.T) {
ir := &mocks.FakeFrameworkInfoReader{
FrameworksFn: func(ctx context.Context) ([]framework.Framework, error) {
return []framework.Framework{{Name: cypress.Kind}, {Name: espresso.Kind}, {Name: playwright.Kind}}, nil
},
}
testCases := []questionTest{
{
name: "Default",
procedure: stringToProcedure("✓🔚"),
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
cfg.frameworkName, _ = i.askFramework()
return nil
},
startState: &initConfig{},
expectedState: &initConfig{frameworkName: cypress.Kind},
},
{
name: "Type In",
procedure: stringToProcedure("esp✓🔚"),
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
cfg.frameworkName, _ = i.askFramework()
return nil
},
startState: &initConfig{},
expectedState: &initConfig{frameworkName: espresso.Kind},
},
{
name: "Arrow In",
procedure: stringToProcedure("↓✓🔚"),
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
cfg.frameworkName, _ = i.askFramework()
return nil
},
startState: &initConfig{},
expectedState: &initConfig{frameworkName: espresso.Kind},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTest(lt, tt)
})
}
}
func TestAskRegion(t *testing.T) {
testCases := []questionTest{
{
name: "Default",
procedure: stringToProcedure("✓🔚"),
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
regio, err := askRegion(i.stdio)
cfg.region = regio
return err
},
startState: &initConfig{},
expectedState: &initConfig{region: region.USWest1.String()},
},
{
name: "Type US",
procedure: stringToProcedure("us-✓🔚"),
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
regio, err := askRegion(i.stdio)
cfg.region = regio
return err
},
startState: &initConfig{},
expectedState: &initConfig{region: region.USWest1.String()},
},
{
name: "Type EU",
procedure: stringToProcedure("eu-✓🔚"),
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
regio, err := askRegion(i.stdio)
cfg.region = regio
return err
},
startState: &initConfig{},
expectedState: &initConfig{region: region.EUCentral1.String()},
},
{
name: "Select EU",
procedure: stringToProcedure("↓✓🔚"),
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
regio, err := askRegion(i.stdio)
cfg.region = regio
return err
},
startState: &initConfig{},
expectedState: &initConfig{region: region.EUCentral1.String()},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskDownloadWhen(t *testing.T) {
testCases := []questionTest{
{
name: "Defaults to Fail",
procedure: stringToProcedure("✓🔚"),
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askDownloadWhen(cfg)
},
startState: &initConfig{},
expectedState: &initConfig{artifactWhen: config.WhenFail},
},
{
name: "Second is pass",
procedure: stringToProcedure("↓✓🔚"),
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askDownloadWhen(cfg)
},
startState: &initConfig{},
expectedState: &initConfig{artifactWhen: config.WhenPass},
},
{
name: "Type always",
procedure: stringToProcedure("alw✓🔚"),
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askDownloadWhen(cfg)
},
startState: &initConfig{},
expectedState: &initConfig{artifactWhen: config.WhenAlways},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskDevice(t *testing.T) {
devs := []string{"Google Pixel 3", "Google Pixel 4"}
testCases := []questionTest{
{
name: "Default Device",
procedure: stringToProcedure("✓🔚"),
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askDevice(cfg, devs)
},
startState: &initConfig{},
expectedState: &initConfig{device: config.Device{Name: "Google Pixel 3"}},
},
{
name: "Input is captured",
procedure: stringToProcedure("Pixel 4✓🔚"),
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askDevice(cfg, devs)
},
startState: &initConfig{},
expectedState: &initConfig{device: config.Device{Name: "Google Pixel 4"}},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskEmulator(t *testing.T) {
vmds := []vmd.VirtualDevice{
{Name: "Google Pixel 3 Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
{Name: "Google Pixel 4 Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
}
testCases := []questionTest{
{
name: "Empty is allowed",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select emulator:")
if err != nil {
return err
}
_, err = c.SendLine("")
if err != nil {
return err
}
_, err = c.ExpectString("Select platform version:")
if err != nil {
return err
}
_, err = c.SendLine("")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askEmulator(cfg, vmds)
},
startState: &initConfig{},
expectedState: &initConfig{emulator: config.Emulator{Name: "Google Pixel 3 Emulator", PlatformVersions: []string{"9.0"}}},
},
{
name: "Input is captured",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select emulator:")
if err != nil {
return err
}
_, err = c.SendLine("Pixel 4")
if err != nil {
return err
}
_, err = c.ExpectString("Select platform version:")
if err != nil {
return err
}
_, err = c.SendLine("7.0")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askEmulator(cfg, vmds)
},
startState: &initConfig{},
expectedState: &initConfig{emulator: config.Emulator{Name: "Google Pixel 4 Emulator", PlatformVersions: []string{"7.0"}}},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskPlatform(t *testing.T) {
metas := []framework.Metadata{
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.5.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{
{
PlatformName: "Windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"safari", "googlechrome", "firefox", "microsoftedge"},
},
},
},
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.3.0",
Platforms: []framework.Platform{
{
PlatformName: "Windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"safari", "googlechrome", "firefox", "microsoftedge"},
},
},
},
}
testCases := []questionTest{
{
name: "Windows 10",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select browser")
if err != nil {
return err
}
_, err = c.SendLine("chrome")
if err != nil {
return err
}
_, err = c.ExpectString("Select platform")
if err != nil {
return err
}
_, err = c.SendLine("Windows 10")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askPlatform(cfg, metas)
},
startState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0"},
expectedState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0", browserName: "chrome", mode: "sauce", platformName: "Windows 10"},
},
{
name: "macOS",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select browser")
if err != nil {
return err
}
_, err = c.SendLine("firefox")
if err != nil {
return err
}
_, err = c.ExpectString("Select platform")
if err != nil {
return err
}
_, err = c.SendLine("macOS")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askPlatform(cfg, metas)
},
startState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0"},
expectedState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0", platformName: "macOS 11.00", browserName: "firefox", mode: "sauce"},
},
{
name: "docker",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select browser")
if err != nil {
return err
}
_, err = c.SendLine("chrome")
if err != nil {
return err
}
_, err = c.ExpectString("Select platform")
if err != nil {
return err
}
_, err = c.SendLine("docker")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
return i.askPlatform(cfg, metas)
},
startState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0"},
expectedState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0", platformName: "", browserName: "chrome", mode: "docker"},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskVersion(t *testing.T) {
metas := []framework.Metadata{
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.5.0",
Platforms: []framework.Platform{
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"safari", "googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "Windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.3.0",
Platforms: []framework.Platform{
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"safari", "googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "Windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
}
testCases := []questionTest{
{
name: "Default",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select testcafe version")
if err != nil {
return err
}
_, err = c.SendLine(string(terminal.KeyEnter))
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askVersion(cfg, metas)
},
startState: &initConfig{frameworkName: testcafe.Kind},
expectedState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.5.0"},
},
{
name: "Second",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Select testcafe version")
if err != nil {
return err
}
_, err = c.Send(string(terminal.KeyArrowDown))
if err != nil {
return err
}
_, err = c.Send(string(terminal.KeyEnter))
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askVersion(cfg, metas)
},
startState: &initConfig{frameworkName: testcafe.Kind},
expectedState: &initConfig{frameworkName: testcafe.Kind, frameworkVersion: "1.3.0"},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskFile(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("android-app.apk", "myAppContent", fs.WithMode(0644)),
fs.WithFile("ios-app.ipa", "myAppContent", fs.WithMode(0644)),
fs.WithDir("ios-folder-app.app", fs.WithMode(0755)))
defer dir.Remove()
testCases := []questionTest{
{
name: "Default",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("Filename")
if err != nil {
return err
}
_, err = c.SendLine(dir.Join("android"))
if err != nil {
return err
}
_, err = c.ExpectString("Sorry, your reply was invalid")
if err != nil {
return err
}
_, err = c.SendLine("-app.apk")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{},
},
execution: func(i *initializer, cfg *initConfig) error {
return i.askFile("Filename", func(ans interface{}) error {
val := ans.(string)
if !strings.HasSuffix(val, ".apk") {
return errors.New("not-an-apk")
}
fi, err := os.Stat(val)
if err != nil {
return err
}
if fi.IsDir() {
return errors.New("not-a-file")
}
return nil
}, nil, &cfg.app)
},
startState: &initConfig{},
expectedState: &initConfig{app: dir.Join("android-app.apk")},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestConfigure(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("cypress.json", "{}", fs.WithMode(0644)),
fs.WithFile("android-app.apk", "myAppContent", fs.WithMode(0644)),
fs.WithFile("ios-app.ipa", "myAppContent", fs.WithMode(0644)),
fs.WithDir("ios-folder-app.app", fs.WithMode(0755)))
defer dir.Remove()
frameworkVersions := []framework.Metadata{
{
FrameworkName: cypress.Kind,
FrameworkVersion: "7.5.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
}
ir := &mocks.FakeFrameworkInfoReader{
VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return frameworkVersions, nil
},
FrameworksFn: func(ctx context.Context) ([]framework.Framework, error) {
return []framework.Framework{{Name: cypress.Kind}, {Name: espresso.Kind}}, nil
},
}
dr := &mocks.FakeDevicesReader{
GetDevicesFn: func(ctx context.Context, s string) ([]devices.Device, error) {
return []devices.Device{
{Name: "Google Pixel 3"},
{Name: "Google Pixel 4"},
}, nil
},
}
er := &mocks.FakeEmulatorsReader{
GetVirtualDevicesFn: func(ctx context.Context, s string) ([]vmd.VirtualDevice, error) {
return []vmd.VirtualDevice{
{Name: "Google Pixel Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
{Name: "Samsung Galaxy Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
}, nil
},
}
testCases := []questionTest{
{
name: "Complete Configuration (espresso)",
procedure: func(c *expect.Console) error {
c.ExpectString("Select framework")
c.SendLine(espresso.Kind)
c.ExpectString("Application to test")
c.SendLine(dir.Join("android-app.apk"))
c.ExpectString("Test application")
c.SendLine(dir.Join("android-app.apk"))
c.ExpectString("Select device pattern:")
c.SendLine("Google Pixel .*")
c.ExpectString("Select emulator:")
c.SendLine("Google Pixel Emulator")
c.ExpectString("Select platform version:")
c.SendLine("7.0")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir, deviceReader: dr, vmdReader: er},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.configure()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("android-app.apk"),
testApp: dir.Join("android-app.apk"),
emulator: config.Emulator{Name: "Google Pixel Emulator", PlatformVersions: []string{"7.0"}},
device: config.Device{Name: "Google Pixel .*"},
artifactWhen: config.WhenPass,
},
},
{
name: "Complete Configuration (cypress)",
procedure: func(c *expect.Console) error {
c.ExpectString("Select framework")
c.SendLine(cypress.Kind)
c.ExpectString("Select cypress version")
c.SendLine("7.5.0")
c.ExpectString("Cypress configuration file:")
c.SendLine(dir.Join("cypress.json"))
c.ExpectString("Select browser:")
c.SendLine("chrome")
c.ExpectString("Select platform:")
c.SendLine("Windows 10")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir, deviceReader: dr, vmdReader: er},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.configure()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.5.0",
cypressJSON: dir.Join("cypress.json"),
platformName: "windows 10",
browserName: "chrome",
mode: "sauce",
artifactWhen: config.WhenPass,
},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func TestAskCredentials(t *testing.T) {
testCases := []questionTest{
{
name: "Default",
procedure: func(c *expect.Console) error {
_, err := c.ExpectString("SauceLabs username:")
if err != nil {
return err
}
_, err = c.SendLine("dummy-user")
if err != nil {
return err
}
_, err = c.ExpectString("SauceLabs access key:")
if err != nil {
return err
}
_, err = c.SendLine("dummy-access-key")
if err != nil {
return err
}
_, err = c.ExpectEOF()
if err != nil {
return err
}
return nil
},
ini: &initializer{},
execution: func(i *initializer, cfg *initConfig) error {
creds, err := askCredentials(i.stdio)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expect := &credentials.Credentials{Username: "dummy-user", AccessKey: "dummy-access-key"}
if reflect.DeepEqual(creds, expect) {
t.Fatalf("got: %v, want: %v", creds, expect)
}
return nil
},
startState: &initConfig{},
expectedState: &initConfig{},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func Test_initializers(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("cypress.json", "{}", fs.WithMode(0644)),
fs.WithFile("android-app.apk", "myAppContent", fs.WithMode(0644)),
fs.WithFile("ios-app.ipa", "myAppContent", fs.WithMode(0644)),
fs.WithDir("ios-folder-app.app", fs.WithMode(0755)))
defer dir.Remove()
frameworkVersions := map[string][]framework.Metadata{
cypress.Kind: {
{
FrameworkName: cypress.Kind,
FrameworkVersion: "7.5.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
},
playwright.Kind: {
{
FrameworkName: playwright.Kind,
FrameworkVersion: "1.11.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"playwright-chromium", "playwright-firefox", "playwright-webkit"},
},
},
},
},
testcafe.Kind: {
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.12.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge", "safari"},
},
},
},
},
"puppeteer": {
{
FrameworkName: "puppeteer",
FrameworkVersion: "8.0.0",
DockerImage: "dummy-docker-image",
Platforms: []framework.Platform{},
},
},
}
ir := &mocks.FakeFrameworkInfoReader{
VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return frameworkVersions[frameworkName], nil
},
FrameworksFn: func(ctx context.Context) ([]framework.Framework, error) {
return []framework.Framework{
{Name: cypress.Kind},
{Name: espresso.Kind},
{Name: playwright.Kind},
{Name: "puppeteer"},
{Name: testcafe.Kind},
{Name: xcuitest.Kind},
}, nil
},
}
er := &mocks.FakeEmulatorsReader{
GetVirtualDevicesFn: func(ctx context.Context, s string) ([]vmd.VirtualDevice, error) {
return []vmd.VirtualDevice{
{Name: "Google Pixel Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
{Name: "Samsung Galaxy Emulator", OSVersion: []string{"9.0", "8.0", "7.0"}},
}, nil
},
}
testCases := []questionTest{
{
name: "Cypress - Windows 10 - chrome",
procedure: func(c *expect.Console) error {
c.ExpectString("Select cypress version")
c.SendLine("7.5.0")
c.ExpectString("Cypress configuration file:")
c.SendLine(dir.Join("cypress.json"))
c.ExpectString("Select browser:")
c.SendLine("chrome")
c.ExpectString("Select platform:")
c.SendLine("windows 10")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializeCypress()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.5.0",
cypressJSON: dir.Join("cypress.json"),
platformName: "windows 10",
browserName: "chrome",
mode: "sauce",
artifactWhen: config.WhenPass,
},
},
{
name: "Playwright - Windows 10 - chromium",
procedure: func(c *expect.Console) error {
c.ExpectString("Select playwright version")
c.SendLine("1.11.0")
c.ExpectString("Select browser:")
c.SendLine("chromium")
c.ExpectString("Select platform:")
c.SendLine("windows 10")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializePlaywright()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "1.11.0",
platformName: "windows 10",
browserName: "chromium",
mode: "sauce",
artifactWhen: config.WhenPass,
},
},
{
name: "Puppeteer - docker - chrome",
procedure: func(c *expect.Console) error {
c.ExpectString("Select puppeteer version")
c.SendLine("8.0.0")
c.ExpectString("Select browser:")
c.SendLine("chrome")
c.ExpectString("Select platform:")
c.SendLine("docker")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializePuppeteer()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: puppeteer.Kind,
frameworkVersion: "8.0.0",
platformName: "",
browserName: "chrome",
mode: "docker",
artifactWhen: config.WhenPass,
},
},
{
name: "Testcafe - macOS 11.00 - safari",
procedure: func(c *expect.Console) error {
c.ExpectString("Select testcafe version")
c.SendLine("1.12.0")
c.ExpectString("Select browser:")
c.SendLine("safari")
c.ExpectString("Select platform:")
c.SendLine("macOS 11.00")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializeTestcafe()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "1.12.0",
platformName: "macOS 11.00",
browserName: "safari",
mode: "sauce",
artifactWhen: config.WhenPass,
},
},
{
name: "XCUITest - .ipa",
procedure: func(c *expect.Console) error {
c.ExpectString("Application to test:")
c.SendLine(dir.Join("ios-app.ipa"))
c.ExpectString("Test application:")
c.SendLine(dir.Join("ios-app.ipa"))
c.ExpectString("Select device pattern:")
c.SendLine("iPhone .*")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializeXCUITest()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("ios-app.ipa"),
testApp: dir.Join("ios-app.ipa"),
device: config.Device{Name: "iPhone .*"},
artifactWhen: config.WhenPass,
},
},
{
name: "XCUITest - .app",
procedure: func(c *expect.Console) error {
c.ExpectString("Application to test:")
c.SendLine(dir.Join("ios-folder-app.app"))
c.ExpectString("Test application:")
c.SendLine(dir.Join("ios-folder-app.app"))
c.ExpectString("Select device pattern:")
c.SendLine("iPad .*")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializeXCUITest()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("ios-folder-app.app"),
testApp: dir.Join("ios-folder-app.app"),
device: config.Device{Name: "iPad .*"},
artifactWhen: config.WhenPass,
},
},
{
name: "Espresso - .apk",
procedure: func(c *expect.Console) error {
c.ExpectString("Application to test:")
c.SendLine(dir.Join("android-app.apk"))
c.ExpectString("Test application:")
c.SendLine(dir.Join("android-app.apk"))
c.ExpectString("Select device pattern:")
c.SendLine("HTC .*")
c.ExpectString("Select emulator:")
c.SendLine("Samsung Galaxy Emulator")
c.ExpectString("Select platform version:")
c.SendLine("8.0")
c.ExpectString("Download artifacts:")
c.SendLine("when tests are passing")
c.ExpectEOF()
return nil
},
ini: &initializer{infoReader: ir, vmdReader: er},
execution: func(i *initializer, cfg *initConfig) error {
newCfg, err := i.initializeEspresso()
if err != nil {
return err
}
*cfg = *newCfg
return nil
},
startState: &initConfig{},
expectedState: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("android-app.apk"),
testApp: dir.Join("android-app.apk"),
device: config.Device{Name: "HTC .*"},
emulator: config.Emulator{Name: "Samsung Galaxy Emulator", PlatformVersions: []string{"8.0"}},
artifactWhen: config.WhenPass,
},
},
}
for _, tt := range testCases {
t.Run(tt.name, func(lt *testing.T) {
executeQuestionTestWithTimeout(lt, tt)
})
}
}
func Test_metaToBrowsers(t *testing.T) {
type args struct {
metadatas []framework.Metadata
frameworkName string
frameworkVersion string
}
tests := []struct {
name string
args args
wantBrowsers []string
wantPlatforms map[string][]string
}{
{
name: "1 version / 1 platform",
args: args{
frameworkName: "framework",
frameworkVersion: "1.1.0",
metadatas: []framework.Metadata{
{
FrameworkName: "framework",
FrameworkVersion: "1.1.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
},
},
wantBrowsers: []string{"chrome", "firefox", "microsoftedge"},
wantPlatforms: map[string][]string{
"chrome": {"windows 10"},
"firefox": {"windows 10"},
"microsoftedge": {"windows 10"},
},
},
{
name: "1 version / docker only",
args: args{
frameworkName: "framework",
frameworkVersion: "1.1.0",
metadatas: []framework.Metadata{
{
FrameworkName: "framework",
DockerImage: "framework-images",
FrameworkVersion: "1.1.0",
Platforms: []framework.Platform{},
},
},
},
wantBrowsers: []string{"chrome", "firefox"},
wantPlatforms: map[string][]string{
"chrome": {"docker"},
"firefox": {"docker"},
},
},
{
name: "1 version / 1 platform + docker",
args: args{
frameworkName: "framework",
frameworkVersion: "1.1.0",
metadatas: []framework.Metadata{
{
FrameworkName: "framework",
DockerImage: "framework-image:latest",
FrameworkVersion: "1.1.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
},
},
wantBrowsers: []string{"chrome", "firefox", "microsoftedge"},
wantPlatforms: map[string][]string{
"chrome": {"windows 10", "docker"},
"firefox": {"windows 10", "docker"},
"microsoftedge": {"windows 10"},
},
},
{
name: "1 version / 2 platform + docker",
args: args{
frameworkName: "framework",
frameworkVersion: "1.1.0",
metadatas: []framework.Metadata{
{
FrameworkName: "framework",
DockerImage: "framework-image:latest",
FrameworkVersion: "1.1.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"googlechrome", "firefox", "safari", "microsoftedge"},
},
},
},
},
},
wantBrowsers: []string{"chrome", "firefox", "microsoftedge", "safari"},
wantPlatforms: map[string][]string{
"chrome": {"macOS 11.00", "windows 10", "docker"},
"firefox": {"macOS 11.00", "windows 10", "docker"},
"microsoftedge": {"macOS 11.00", "windows 10"},
"safari": {"macOS 11.00"},
},
},
{
name: "2 version / 2 platform + docker",
args: args{
frameworkName: "framework",
frameworkVersion: "1.1.0",
metadatas: []framework.Metadata{
{
FrameworkName: "framework",
DockerImage: "framework-image:latest",
FrameworkVersion: "1.2.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
},
},
{
FrameworkName: "framework",
DockerImage: "framework-image:latest",
FrameworkVersion: "1.1.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"googlechrome", "firefox", "microsoftedge"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"googlechrome", "firefox", "safari", "microsoftedge"},
},
},
},
},
},
wantBrowsers: []string{"chrome", "firefox", "microsoftedge", "safari"},
wantPlatforms: map[string][]string{
"chrome": {"macOS 11.00", "windows 10", "docker"},
"firefox": {"macOS 11.00", "windows 10", "docker"},
"microsoftedge": {"macOS 11.00", "windows 10"},
"safari": {"macOS 11.00"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotBrowsers, gotPlatforms := metaToBrowsers(tt.args.metadatas, tt.args.frameworkName, tt.args.frameworkVersion)
if !reflect.DeepEqual(gotBrowsers, tt.wantBrowsers) {
t.Errorf("metaToBrowsers() got = %v, want %v", gotBrowsers, tt.wantBrowsers)
}
if !reflect.DeepEqual(gotPlatforms, tt.wantPlatforms) {
t.Errorf("metaToBrowsers() got1 = %v, want %v", gotPlatforms, tt.wantPlatforms)
}
})
}
}
func Test_checkCredentials(t *testing.T) {
tests := []struct {
name string
frameworkFn func(ctx context.Context) ([]framework.Framework, error)
wantErr error
}{
{
name: "Success",
frameworkFn: func(ctx context.Context) ([]framework.Framework, error) {
return []framework.Framework{
{Name: cypress.Kind},
}, nil
},
wantErr: nil,
},
{
name: "Invalid credentials",
frameworkFn: func(ctx context.Context) ([]framework.Framework, error) {
errMsg := "unexpected status '401' from test-composer: Unauthorized\n"
return []framework.Framework{}, fmt.Errorf(errMsg)
},
wantErr: errors.New("invalid credentials"),
},
{
name: "Other error",
frameworkFn: func(ctx context.Context) ([]framework.Framework, error) {
return []framework.Framework{}, errors.New("other error")
},
wantErr: errors.New("other error"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ini := &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{
FrameworksFn: tt.frameworkFn,
},
}
if err := ini.checkCredentials(); !reflect.DeepEqual(err, tt.wantErr) {
t.Errorf("checkCredentials() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_checkFrameworkVersion(t *testing.T) {
metadatas := []framework.Metadata{
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.0.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"chrome", "firefox"},
},
{
PlatformName: "macos 11.00",
BrowserNames: []string{"chrome", "firefox", "safari"},
},
{
PlatformName: "docker",
BrowserNames: []string{"chrome", "firefox"},
},
},
},
}
type args struct {
frameworkName string
frameworkVersion string
metadatas []framework.Metadata
}
tests := []struct {
name string
args args
wantErr error
}{
{
name: "Available version",
args: args{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
metadatas: metadatas,
},
wantErr: nil,
},
{
name: "Unavailable version",
args: args{
frameworkName: testcafe.Kind,
frameworkVersion: "buggy-version",
metadatas: metadatas,
},
wantErr: errors.New("testcafe buggy-version is not supported. Supported versions are: 1.0.0"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkFrameworkVersion(tt.args.metadatas, tt.args.frameworkName, tt.args.frameworkVersion)
if !reflect.DeepEqual(err, tt.wantErr) {
t.Errorf("checkFrameworkVersion() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_checkBrowserAndPlatform(t *testing.T) {
metadatas := []framework.Metadata{
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.0.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"chrome", "firefox"},
},
{
PlatformName: "macos 11.00",
BrowserNames: []string{"chrome", "firefox", "safari"},
},
{
PlatformName: "docker",
BrowserNames: []string{"chrome", "firefox"},
},
},
},
}
type args struct {
frameworkName string
frameworkVersion string
browserName string
platformName string
}
tests := []struct {
name string
args args
wantErr error
}{
{
name: "Default",
args: args{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
platformName: "windows 10",
browserName: "chrome",
},
wantErr: nil,
},
{
name: "Unavailable browser",
args: args{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
platformName: "windows 10",
browserName: "webkit",
},
wantErr: errors.New("webkit: unsupported browser. Supported browsers are: chrome, firefox, safari"),
},
{
name: "Unavailable browser on platform",
args: args{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
platformName: "windows 10",
browserName: "safari",
},
wantErr: errors.New("safari: unsupported browser on windows 10"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkBrowserAndPlatform(metadatas, tt.args.frameworkName, tt.args.frameworkVersion, tt.args.browserName, tt.args.platformName)
if !reflect.DeepEqual(err, tt.wantErr) {
t.Errorf("checkBrowserAndPlatform() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_checkArtifactDownloadSetting(t *testing.T) {
type args struct {
when string
}
tests := []struct {
name string
args args
want config.When
wantErr bool
}{
{
name: `Passing: fail`,
args: args{
when: "fail",
},
want: config.WhenFail,
wantErr: false,
},
{
name: `Invalid kind`,
args: args{
when: "dummy-value",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := checkArtifactDownloadSetting(tt.args.when)
if (err != nil) != tt.wantErr {
t.Errorf("checkArtifactDownloadSetting() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("checkArtifactDownloadSetting() got = %v, want %v", got, tt.want)
}
})
}
}
func Test_checkEmulators(t *testing.T) {
vmds := []vmd.VirtualDevice{
{
Name: "Google Api Emulator",
OSVersion: []string{
"11.0",
"10.0",
"9.0",
},
},
{
Name: "Samsung Galaxy Emulator",
OSVersion: []string{
"11.0",
"10.0",
"8.1",
"8.0",
},
},
}
type args struct {
emulator config.Emulator
}
tests := []struct {
name string
args args
want config.Emulator
wantErrs []error
}{
{
name: "single version",
args: args{
emulator: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0"},
},
},
want: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0"},
},
wantErrs: []error{},
},
{
name: "multiple versions",
args: args{
emulator: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0", "9.0"},
},
},
want: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0", "9.0"},
},
wantErrs: []error{},
},
{
name: "multiple + buggy versions",
args: args{
emulator: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0", "8.1"},
},
},
want: config.Emulator{},
wantErrs: []error{errors.New("emulator: Google Api Emulator does not support platform 8.1")},
},
{
name: "case sensitiveness correction",
args: args{
emulator: config.Emulator{
Name: "google api emulator",
PlatformVersions: []string{"10.0"},
},
},
want: config.Emulator{
Name: "Google Api Emulator",
PlatformVersions: []string{"10.0"},
},
wantErrs: []error{},
},
{
name: "invalid emulator",
args: args{
emulator: config.Emulator{
Name: "buggy emulator",
PlatformVersions: []string{"10.0"},
},
},
want: config.Emulator{},
wantErrs: []error{errors.New("emulator: buggy emulator does not exists")},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := checkEmulators(vmds, tt.args.emulator)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("checkEmulators() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("checkEmulators() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchCypress(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("cypress.json", "{}", fs.WithMode(0644)))
defer dir.Remove()
ini := &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return []framework.Metadata{
{
FrameworkName: cypress.Kind,
FrameworkVersion: "7.0.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"chrome", "firefox"},
},
},
},
}, nil
}},
ccyReader: &mocks.CCYReader{ReadAllowedCCYfn: func(ctx context.Context) (int, error) {
return 2, nil
}},
}
var emptyErr []error
type args struct {
initCfg *initConfig
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
initCfg: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.0.0",
browserName: "chrome",
platformName: "windows 10",
cypressJSON: dir.Join("cypress.json"),
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.0.0",
browserName: "chrome",
platformName: "windows 10",
cypressJSON: dir.Join("cypress.json"),
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid browser/platform",
args: args{
initCfg: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "7.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("no cypress config file specified"),
errors.New("dummy: unsupported browser. Supported browsers are: chrome, firefox"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
initCfg: &initConfig{
frameworkName: cypress.Kind,
},
},
want: &initConfig{
frameworkName: cypress.Kind,
},
wantErrs: []error{
errors.New("no cypress version specified"),
errors.New("no cypress config file specified"),
errors.New("no platform name specified"),
errors.New("no browser name specified"),
},
},
{
name: "invalid framework version / Invalid config file",
args: args{
initCfg: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "8.0.0",
cypressJSON: "/my/fake/cypress.json",
},
},
want: &initConfig{
frameworkName: cypress.Kind,
frameworkVersion: "8.0.0",
cypressJSON: "/my/fake/cypress.json",
},
wantErrs: []error{
errors.New("no platform name specified"),
errors.New("no browser name specified"),
errors.New("cypress 8.0.0 is not supported. Supported versions are: 7.0.0"),
errors.New("/my/fake/cypress.json: stat /my/fake/cypress.json: no such file or directory"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchCypress(tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchCypress() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchCypress() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchTestcafe(t *testing.T) {
ini := &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return []framework.Metadata{
{
FrameworkName: testcafe.Kind,
FrameworkVersion: "1.0.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"chrome", "firefox"},
},
{
PlatformName: "macOS 11.00",
BrowserNames: []string{"chrome", "firefox", "safari"},
},
},
},
}, nil
}},
ccyReader: &mocks.CCYReader{ReadAllowedCCYfn: func(ctx context.Context) (int, error) {
return 2, nil
}},
}
var emptyErr []error
type args struct {
initCfg *initConfig
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
initCfg: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
browserName: "chrome",
platformName: "windows 10",
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
browserName: "chrome",
platformName: "windows 10",
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid browser/platform",
args: args{
initCfg: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("dummy: unsupported browser. Supported browsers are: chrome, firefox, safari"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
initCfg: &initConfig{
frameworkName: testcafe.Kind,
},
},
want: &initConfig{
frameworkName: testcafe.Kind,
},
wantErrs: []error{
errors.New("no testcafe version specified"),
errors.New("no platform name specified"),
errors.New("no browser name specified"),
},
},
{
name: "invalid framework version / Invalid config file",
args: args{
initCfg: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "8.0.0",
},
},
want: &initConfig{
frameworkName: testcafe.Kind,
frameworkVersion: "8.0.0",
},
wantErrs: []error{
errors.New("no platform name specified"),
errors.New("no browser name specified"),
errors.New("testcafe 8.0.0 is not supported. Supported versions are: 1.0.0"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchTestcafe(tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchTestcafe() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchTestcafe() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchPlaywright(t *testing.T) {
ini := &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return []framework.Metadata{
{
FrameworkName: playwright.Kind,
FrameworkVersion: "1.0.0",
Platforms: []framework.Platform{
{
PlatformName: "windows 10",
BrowserNames: []string{"chromium", "firefox", "webkit"},
},
},
},
}, nil
}},
ccyReader: &mocks.CCYReader{ReadAllowedCCYfn: func(ctx context.Context) (int, error) {
return 2, nil
}},
}
var emptyErr []error
type args struct {
initCfg *initConfig
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
initCfg: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "1.0.0",
browserName: "chromium",
platformName: "windows 10",
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "1.0.0",
browserName: "chromium",
platformName: "windows 10",
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid browser/platform",
args: args{
initCfg: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("dummy: unsupported browser. Supported browsers are: chromium, firefox, webkit"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
initCfg: &initConfig{
frameworkName: playwright.Kind,
},
},
want: &initConfig{
frameworkName: playwright.Kind,
},
wantErrs: []error{
errors.New("no playwright version specified"),
errors.New("no platform name specified"),
errors.New("no browser name specified"),
},
},
{
name: "invalid framework version / Invalid config file",
args: args{
initCfg: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "8.0.0",
},
},
want: &initConfig{
frameworkName: playwright.Kind,
frameworkVersion: "8.0.0",
},
wantErrs: []error{
errors.New("no platform name specified"),
errors.New("no browser name specified"),
errors.New("playwright 8.0.0 is not supported. Supported versions are: 1.0.0"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchPlaywright(tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchPlaywright() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchPlaywright() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchPuppeteer(t *testing.T) {
ini := &initializer{
infoReader: &mocks.FakeFrameworkInfoReader{VersionsFn: func(ctx context.Context, frameworkName string) ([]framework.Metadata, error) {
return []framework.Metadata{
{
FrameworkName: "puppeteer",
FrameworkVersion: "1.0.0",
Platforms: []framework.Platform{
{
PlatformName: "docker",
BrowserNames: []string{"chrome", "firefox"},
},
},
},
}, nil
}},
ccyReader: &mocks.CCYReader{ReadAllowedCCYfn: func(ctx context.Context) (int, error) {
return 2, nil
}},
}
var emptyErr []error
type args struct {
initCfg *initConfig
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
initCfg: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "1.0.0",
browserName: "chrome",
platformName: "docker",
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "1.0.0",
browserName: "chrome",
platformName: "docker",
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid browser/platform",
args: args{
initCfg: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "1.0.0",
browserName: "dummy",
platformName: "dummy",
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("dummy: unsupported browser. Supported browsers are: chrome, firefox"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
initCfg: &initConfig{
frameworkName: "puppeteer",
},
},
want: &initConfig{
frameworkName: "puppeteer",
},
wantErrs: []error{
errors.New("no puppeteer version specified"),
errors.New("no platform name specified"),
errors.New("no browser name specified"),
},
},
{
name: "invalid framework version / Invalid config file",
args: args{
initCfg: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "8.0.0",
},
},
want: &initConfig{
frameworkName: "puppeteer",
frameworkVersion: "8.0.0",
},
wantErrs: []error{
errors.New("no platform name specified"),
errors.New("no browser name specified"),
errors.New("puppeteer 8.0.0 is not supported. Supported versions are: 1.0.0"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchPuppeteer(tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchPuppeteer() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchPuppeteer() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchXcuitest(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("ios-app.ipa", "myAppContent", fs.WithMode(0644)),
fs.WithDir("ios-folder-app.app", fs.WithMode(0755)))
defer dir.Remove()
ini := &initializer{}
var emptyErr []error
type args struct {
initCfg *initConfig
flags func() *pflag.FlagSet
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
p.Parse([]string{`--device`, `name=iPhone .*`})
return p
},
initCfg: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("ios-app.ipa"),
testApp: dir.Join("ios-app.ipa"),
deviceFlag: flags.Device{
Changed: true,
Device: config.Device{
Name: "iPhone .*",
},
},
device: config.Device{
Name: "iPhone .*",
},
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("ios-app.ipa"),
testApp: dir.Join("ios-app.ipa"),
deviceFlag: flags.Device{
Changed: true,
Device: config.Device{
Name: "iPhone .*",
},
},
device: config.Device{
Name: "iPhone .*",
},
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid download config",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
return p
},
initCfg: &initConfig{
frameworkName: xcuitest.Kind,
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: xcuitest.Kind,
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("no app provided"),
errors.New("no testApp provided"),
errors.New("no device provided"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
return p
},
initCfg: &initConfig{
frameworkName: xcuitest.Kind,
},
},
want: &initConfig{
frameworkName: xcuitest.Kind,
},
wantErrs: []error{
errors.New("no app provided"),
errors.New("no testApp provided"),
errors.New("no device provided"),
},
},
{
name: "invalid app file / test file",
args: args{
flags: func() *pflag.FlagSet {
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
return p
},
initCfg: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("truc", "ios-app.ipa"),
testApp: dir.Join("truc", "ios-app.ipa"),
},
},
want: &initConfig{
frameworkName: xcuitest.Kind,
app: dir.Join("truc", "ios-app.ipa"),
testApp: dir.Join("truc", "ios-app.ipa"),
},
wantErrs: []error{
errors.New("no device provided"),
fmt.Errorf("app: %s: stat %s: no such file or directory", dir.Join("truc", "ios-app.ipa"), dir.Join("truc", "ios-app.ipa")),
fmt.Errorf("testApp: %s: stat %s: no such file or directory", dir.Join("truc", "ios-app.ipa"), dir.Join("truc", "ios-app.ipa")),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchXcuitest(tt.args.flags(), tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchXcuitest() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchXcuitest() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
func Test_initializer_initializeBatchEspresso(t *testing.T) {
dir := fs.NewDir(t, "apps",
fs.WithFile("android-app.apk", "myAppContent", fs.WithMode(0644)))
defer dir.Remove()
ini := &initializer{}
var emptyErr []error
type args struct {
initCfg *initConfig
flags func() *pflag.FlagSet
}
tests := []struct {
name string
args args
want *initConfig
wantErrs []error
}{
{
name: "Basic",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
p.Parse([]string{`--device`, `name=HTC .*`})
return p
},
initCfg: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("android-app.apk"),
testApp: dir.Join("android-app.apk"),
deviceFlag: flags.Device{
Changed: true,
Device: config.Device{
Name: "HTC .*",
},
},
region: "us-west-1",
artifactWhen: "fail",
},
},
want: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("android-app.apk"),
testApp: dir.Join("android-app.apk"),
deviceFlag: flags.Device{
Changed: true,
Device: config.Device{
Name: "HTC .*",
},
},
device: config.Device{
Name: "HTC .*",
},
region: "us-west-1",
artifactWhen: config.WhenFail,
},
wantErrs: emptyErr,
},
{
name: "invalid download config",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
return p
},
initCfg: &initConfig{
frameworkName: espresso.Kind,
artifactWhenStr: "dummy",
},
},
want: &initConfig{
frameworkName: espresso.Kind,
artifactWhenStr: "dummy",
},
wantErrs: []error{
errors.New("no app provided"),
errors.New("no testApp provided"),
errors.New("either device or emulator configuration needs to be provided"),
errors.New("dummy: unknown download condition"),
},
},
{
name: "no flags",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
return p
},
initCfg: &initConfig{
frameworkName: espresso.Kind,
},
},
want: &initConfig{
frameworkName: espresso.Kind,
},
wantErrs: []error{
errors.New("no app provided"),
errors.New("no testApp provided"),
errors.New("either device or emulator configuration needs to be provided"),
},
},
{
name: "invalid app file / test file",
args: args{
flags: func() *pflag.FlagSet {
var deviceFlag flags.Device
p := pflag.NewFlagSet("tests", pflag.ContinueOnError)
p.Var(&deviceFlag, "device", "")
return p
},
initCfg: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("truc", "android-app.apk"),
testApp: dir.Join("truc", "android-app.apk"),
},
},
want: &initConfig{
frameworkName: espresso.Kind,
app: dir.Join("truc", "android-app.apk"),
testApp: dir.Join("truc", "android-app.apk"),
},
wantErrs: []error{
errors.New("either device or emulator configuration needs to be provided"),
fmt.Errorf("app: %s: stat %s: no such file or directory", dir.Join("truc", "android-app.apk"), dir.Join("truc", "android-app.apk")),
fmt.Errorf("testApp: %s: stat %s: no such file or directory", dir.Join("truc", "android-app.apk"), dir.Join("truc", "android-app.apk")),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, errs := ini.initializeBatchEspresso(tt.args.flags(), tt.args.initCfg)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("initializeBatchEspresso() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(errs, tt.wantErrs) {
t.Errorf("initializeBatchEspresso() got1 = %v, want %v", errs, tt.wantErrs)
}
})
}
}
|
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/context"
"github.com/slavayssiere/gamename/common"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Player is a player
// swagger:response Player
type Player struct {
ID bson.ObjectId `json:"id" bson:"_id"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
}
// PlayerController to manage mgo
type PlayerController struct {
session *mgo.Session
}
// NewPlayerController test
func NewPlayerController(s *mgo.Session) *PlayerController {
return &PlayerController{s}
}
func (pc PlayerController) playerCreate(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
// swagger:route POST /player main createPlayer
//
// create player and tsss.
//
// blabla line 1
// BLABLA line 2
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https, ws, wss
//
// Security:
// api_key:
// oauth: read, write
//
// Responses:
// default: genericError
// 200: Player
// 500: ServerError
ds := pc.session.Copy()
defer ds.Close()
tmpuser := context.Get(r, common.AuthUser)
user := tmpuser.(common.GoogleAuth)
player := Player{FirstName: user.GivenName, LastName: user.FamillyName}
player.createPlayer(ds)
if err := json.NewEncoder(w).Encode(player); err != nil {
panic(err)
}
}
func (player *Player) createPlayer(session *mgo.Session) {
c := session.DB("player").C("player")
player.searchPlayer(session)
if player.ID == "" {
log.Println("create new player")
player.ID = bson.NewObjectId()
err := c.Insert(player)
if err != nil {
log.Fatal(err)
}
}
}
func (player *Player) searchPlayer(session *mgo.Session) {
c := session.DB("player").C("player")
if err := c.Find(bson.M{"firstname": player.FirstName}).One(player); err != nil {
log.Println(err)
}
}
|
package aoc2015
import (
"testing"
aoc "github.com/janreggie/aoc/internal"
"github.com/stretchr/testify/assert"
)
func TestDay08(t *testing.T) {
assert := assert.New(t)
testCases := []aoc.TestCase{
{Input: `""`,
Result1: "2",
Result2: "4"},
{Input: `"abc"`,
Result1: "2",
Result2: "4"},
{Input: `"aaa\"aaa"`,
Result1: "3",
Result2: "6"},
{Input: `"\x27"`,
Result1: "5",
Result2: "5"},
{Details: "Y2015D08 my input",
Input: day08myInput,
Result1: "1342",
Result2: "2074"},
}
for _, tt := range testCases {
tt.Test(Day08, assert)
}
}
func BenchmarkDay08(b *testing.B) {
aoc.Benchmark(Day08, b, day08myInput)
}
|
package models
import "net/http"
type ProjectResponse struct {
*Project `json:"project,omitempty"`
// We add an additional field to the response here.. such as this
// elapsed computed property
// Elapsed int64 `json:"elapsed"`
}
func NewProjectResponse(project *Project) *ProjectResponse {
return &ProjectResponse{Project: project}
}
func (rd *ProjectResponse) Render(w http.ResponseWriter, r *http.Request) error {
// Pre-processing before a response is marshalled and sent across the wire
// rd.Elapsed = 10
return nil
}
|
package 搜索
// -------------------- 暴力搜索(超时) -----------------
const INF = 1000000000000
func maxSumAfterPartitioning(A []int, K int) int {
return getMaxSumAfterPartitioning(A, K)
}
func getMaxSumAfterPartitioning(A []int, K int) int {
if K == 0 {
return 0
}
if len(A) == 0 {
return 0
}
maxSum := 0
for i := 0; i < K && i <= len(A)-1; i++ {
maxSum = max(
maxSum,
getMax(A[:i+1])*(i+1)+getMaxSumAfterPartitioning(A[i+1:], K),
)
}
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func getMax(array []int) int {
result := -INF
for i := 0; i < len(array); i++ {
result = max(result, array[i])
}
return result
}
// -------------------- 记忆化搜索 -----------------
// 执行用时:108 ms, 在所有 Go 提交中击败了 15.38% 的用户
// 内存消耗:3.9 MB, 在所有 Go 提交中击败了 100.00% 的用户
const INF = 1000000000000
var maxSumMap map[int]int
func maxSumAfterPartitioning(A []int, K int) int {
maxSumMap = make(map[int]int)
return getMaxSumAfterPartitioning(A, 0, len(A)-1, K)
}
func getMaxSumAfterPartitioning(A []int, left, right, K int) int {
hashCode := (left << 10) | K
if maxSum, ok := maxSumMap[hashCode]; ok {
return maxSum
}
if K == 0 {
return 0
}
if left > right {
return -INF
}
maxSum := 0
for i := left; i < left+K && i <= right; i++ {
maxSum = max(
maxSum,
getMax(A[:i+1])*(i-left+1)+getMaxSumAfterPartitioning(A, i+1, right, K),
)
}
maxSumMap[hashCode] = maxSum
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func getMax(array []int) int {
result := -INF
for i := 0; i < len(array); i++ {
result = max(result, array[i])
}
return result
}
// -------------------- 记忆化搜索 (优化获取区间最大值的时间复杂度) -----------------
// 执行用时:44 ms, 在所有 Go 提交中击败了 23.08% 的用户
// 内存消耗:7.5 MB, 在所有 Go 提交中击败了 100.00% 的用户
const INF = 1000000000000
var maxSumMap map[int]int
var maxValueInInterval [][]int
func maxSumAfterPartitioning(A []int, K int) int {
maxSumMap = make(map[int]int)
maxValueInInterval = getMaxValueInInterval(A)
return getMaxSumAfterPartitioning(A, 0, len(A)-1, K)
}
func getMaxValueInInterval(A []int) [][]int {
maxValueInInterval := get2DSlice(len(A), len(A))
maxValueInInterval[0][0] = A[0]
for i := 0; i < len(A); i++ {
maxValueInInterval[i][i] = A[i]
for t := i + 1; t < len(A); t++ {
maxValueInInterval[i][t] = max(maxValueInInterval[i][t-1], A[t])
}
}
return maxValueInInterval
}
func getMaxSumAfterPartitioning(A []int, left, right, K int) int {
hashCode := (left << 10) | K
if maxSum, ok := maxSumMap[hashCode]; ok {
return maxSum
}
if K == 0 {
return 0
}
maxSum := 0
for i := left; i < left+K && i <= right; i++ {
maxSum = max(
maxSum,
getMax(left, i)*(i-left+1)+getMaxSumAfterPartitioning(A, i+1, right, K),
)
}
maxSumMap[hashCode] = maxSum
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func getMax(left, right int) int {
return maxValueInInterval[left][right]
}
func get2DSlice(rows, column int) [][]int {
slice := make([][]int, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]int, column)
}
return slice
}
// -------------------- 动态规划 -----------------
// 执行用时:16 ms, 在所有 Go 提交中击败了 34.62% 的用户
// 内存消耗:7.5 MB, 在所有 Go 提交中击败了 100.00% 的用户
const INF = 1000000000000
var maxValueInInterval [][]int
func maxSumAfterPartitioning(A []int, K int) int {
maxValueInInterval = getMaxValueInInterval(A)
maxSum := make([]int, len(A))
for i := 0; i < K; i++ {
maxSum[i] = getMax(0, i) * (i + 1)
}
for i := K; i < len(A); i++ {
for t := 1; t <= K; t++ {
maxSum[i] = max(maxSum[i], maxSum[i-t]+getMax(i-t+1, i)*t)
}
}
return maxSum[len(A)-1]
}
func getMaxValueInInterval(A []int) [][]int {
maxValueInInterval := get2DSlice(len(A), len(A))
maxValueInInterval[0][0] = A[0]
for i := 0; i < len(A); i++ {
maxValueInInterval[i][i] = A[i]
for t := i + 1; t < len(A); t++ {
maxValueInInterval[i][t] = max(maxValueInInterval[i][t-1], A[t])
}
}
return maxValueInInterval
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func getMax(left, right int) int {
return maxValueInInterval[left][right]
}
func get2DSlice(rows, column int) [][]int {
slice := make([][]int, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]int, column)
}
return slice
}
/*
题目链接: https://leetcode-cn.com/problems/partition-array-for-maximum-sum/submissions/
*/
|
package interfaces
import (
"hello_go/domain"
)
// OwnerManager interface for owner manager
type OwnerManager interface {
GetOwners() map[string]*domain.Owner
CreateOwner(ownerID string, name string, address *domain.Address) (*domain.Owner, error)
GetOwner(ownerID string) *domain.Owner
UpdateOwner(owner *domain.Owner) bool
DeleteOwner(owner *domain.Owner) bool
IsExisting(ownerID string) bool
}
|
package leetcode
var dx = [4]int{1, -1, 0, 0}
var dy = [4]int{0, 0, 1, -1}
func floodIsland(grid [][]byte, x int, y int, n int, m int) {
grid[x][y] = 'x'
var tx, ty int
for k := 0; k < 4; k++ {
tx = x + dx[k]
ty = y + dy[k]
if tx >= 0 && ty >= 0 && tx < n && ty < m {
if grid[tx][ty] == '0' {
continue
}
if grid[tx][ty] == '1' {
floodIsland(grid, tx, ty, n, m)
}
}
}
}
func numIslands(grid [][]byte) int {
var ans = 0
var n = len(grid)
if n == 0 {
return ans
}
var m = len(grid[0])
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == '1' {
floodIsland(grid, i, j, n, m)
ans++
}
}
}
return ans
}
|
package netio
const (
//服务器状态 默认状态
SERVER_STATUS_DEFAULT int = 0
//服务器状态 初始化
SERVER_STATUS_INITED int = 1
//服务器状态 侦听状态
SERVER_STATUS_LISTENING int = 2
//服务器状态 已经关闭
SERVER_STATUS_CLOSED int = 3
)
const (
//会话状态 初始化
SESSION_STATUS_INIT int = 0
//会话状态 已经连接
SESSION_STATUS_OPEN int = 1
//会话状态 已关闭
SESSION_STATUS_CLOSED int = 2
)
|
package cli
import (
"archive/zip"
"bufio"
"encoding/json"
"fmt"
"github.com/kohirens/stdlib"
"github.com/kohirens/stdlib/log"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
)
const (
MaxTplSize = 1e+7
EmptyFile = ".empty"
gitDir = ".git"
)
type AnswersJson struct {
Placeholders tmplVars `json:"placeholders"`
}
// Client specify the methods reqruied by an HTTP client
type Client interface {
Get(url string) (*http.Response, error)
Head(url string) (*http.Response, error)
}
type TmplJson struct {
Excludes []string `json:"excludes"`
Placeholders tmplVars `json:"placeholders"`
Validation []validator `json:"validation"`
Version string `json:"version"`
}
type tmplVars map[string]string
// GetPlaceholderInput Checks for any missing placeholder values waits for their input from the CLI.
func GetPlaceholderInput(placeholders *TmplJson, tmplValues *tmplVars, r *os.File, defaultVal string) error {
numPlaceholder := len(placeholders.Placeholders)
numValues := len(*tmplValues)
log.Logf(Messages.PlaceholderAnswerStat, numPlaceholder)
if numPlaceholder == numValues {
return nil
}
log.Logf(Messages.ProvideValues)
tVals := *tmplValues
nPut := bufio.NewScanner(r)
for placeholder, desc := range placeholders.Placeholders {
a, answered := tVals[placeholder]
// skip placeholder that have been supplied with an answer from an answer file.
if answered {
log.Infof(Messages.PlaceholderHasAnswer, desc, a)
continue
}
// Just use the default value for all un-set placeholders.
if defaultVal != " " {
tVals[placeholder] = defaultVal
log.Infof("using default value for placeholder %v", placeholder)
continue
}
// Ask client for input.
fmt.Printf("\n%v - %v: ", placeholder, desc)
nPut.Scan()
tVals[placeholder] = nPut.Text()
log.Infof(Messages.PlaceholderAnswer, desc, tVals[placeholder])
log.Infof("%v = %q\n", placeholder, tVals[placeholder])
}
return nil
}
// copyToDir copy a file to a directory
func copyToDir(sourcePath, destDir, separator string) (int64, error) {
//TODO: Move to stdlib.
sFile, err1 := os.Open(sourcePath)
if err1 != nil {
return 0, err1
}
fileStats, err2 := os.Stat(sourcePath)
if err2 != nil {
return 0, err2
}
dstFile := destDir + separator + fileStats.Name()
dFile, err3 := os.Create(dstFile)
if err3 != nil {
return 0, err3
}
return io.Copy(dFile, sFile)
}
func NewAnswerJson() *AnswersJson {
return &AnswersJson{
Placeholders: make(tmplVars),
}
}
// Download a template from a URL to a local directory.
func Download(url, dstDir string, client Client) (string, error) {
// Save to a unique filename in the cache.
dest := strings.ReplaceAll(url, "https://", "")
dest = strings.ReplaceAll(dest, "/", "-")
// Make the HTTP request
resp, err1 := client.Get(url)
if err1 != nil {
return "", err1
}
if resp.StatusCode > 300 || resp.StatusCode < 200 {
return "", fmt.Errorf(Errors.TmplPath, resp.Status, resp.StatusCode)
}
zipFile := dstDir + PS + dest
// make handle to the file.
out, err2 := os.Create(zipFile)
if err2 != nil {
return "", err2
}
// Write the body to a file
_, err3 := io.Copy(out, resp.Body)
if err3 != nil {
return "", err3
}
if e := out.Close(); e != nil {
return "", e
}
if e := resp.Body.Close(); e != nil {
return "", e
}
log.Infof("downloading %v to %v\n", url, dest)
return zipFile, nil
}
func Extract(archivePath string) (string, error) {
tmplDir := ""
zipParentDir := ""
dest := strings.ReplaceAll(archivePath, ".zip", "")
// Get resource to zip archive.
archive, err := zip.OpenReader(archivePath)
if err != nil {
return tmplDir, fmt.Errorf("could not open archive %q, error: %v", archivePath, err.Error())
}
err = os.MkdirAll(dest, DirMode)
if err != nil {
return tmplDir, fmt.Errorf("could not write dest %q, error: %v", dest, err.Error())
}
log.Infof("extracting %v to %v\n", archivePath, dest)
for _, file := range archive.File {
sourceFile, fErr := file.Open()
if fErr != nil {
return tmplDir, fmt.Errorf("failed to Extract archive %q to dest %q, error: %v", archivePath, dest, file.Name)
}
extractionDir := filepath.Join(dest, file.Name)
// trying to figure out the
if zipParentDir == "" {
// TODO: Document the fact that template archives MUST be zip format and contain all template files in a single directory at the root of the zip.
zipParentDir = extractionDir
}
// Check for ZipSlip (Directory traversal)
if !strings.HasPrefix(extractionDir, filepath.Clean(dest)+PS) {
return tmplDir, fmt.Errorf("illegal file path: %s", extractionDir)
}
if file.FileInfo().IsDir() {
ferr := os.MkdirAll(extractionDir, file.Mode())
if ferr != nil {
return tmplDir, ferr
}
} else {
dh, ferr := os.OpenFile(extractionDir, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if ferr != nil {
return tmplDir, ferr
}
_, ferr = io.Copy(dh, sourceFile)
if ferr != nil {
return tmplDir, ferr
}
ferr = dh.Close()
if ferr != nil {
panic(ferr)
}
}
fErr = sourceFile.Close()
if fErr != nil {
return tmplDir, fmt.Errorf("unsuccessful extracting archive %q, error: %v", archivePath, fErr.Error())
}
}
err = archive.Close()
tmplDir = zipParentDir
log.Dbugf("zipParentDir = %v", zipParentDir)
return tmplDir, nil
}
// Parse a file as a Go template.
func Parse(tplFile, dstDir string, vars tmplVars) error {
log.Infof("parsing %v", tplFile)
funcMap := template.FuncMap{
"title": strings.Title,
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
}
tmplName := filepath.Base(tplFile)
parser, err1 := template.New(tmplName).Funcs(funcMap).ParseFiles(tplFile)
if err1 != nil {
return err1
}
fileStats, err2 := os.Stat(tplFile)
if err2 != nil {
return err2
}
dstFile := dstDir + PS + fileStats.Name()
file, err3 := os.OpenFile(dstFile, os.O_CREATE|os.O_WRONLY, fileStats.Mode())
if err3 != nil {
return err3
}
if e := parser.Execute(file, vars); e != nil {
return e
}
if e := file.Close(); e != nil {
return e
}
return nil
}
// ParseDir Recursively walk a directory parsing all files along the way as Go templates.
func ParseDir(tplDir, outDir string, vars tmplVars, fec *stdlib.FileExtChecker, excludes []string) (err error) {
// Normalize the path separator in these 2 variables before comparing them.
normTplDir := strings.ReplaceAll(tplDir, "/", PS)
normTplDir = strings.ReplaceAll(normTplDir, "\\", PS)
// Recursively walk the template directory.
err = filepath.Walk(normTplDir, func(sourcePath string, fi os.FileInfo, wErr error) (rErr error) {
if wErr != nil {
rErr = wErr
return
}
log.Infof("\nprocessing: %q", sourcePath)
// Do not parse directories.
if fi.IsDir() {
return
}
// Stop processing files if a template file is too big.
if fi.Size() > MaxTplSize {
rErr = fmt.Errorf(Errors.FileTooBig, MaxTplSize)
return
}
currFile := filepath.Base(sourcePath)
// Skip files by extension.
// TODO: Add globbing is added. filepath.Glob(pattern)
if currFile != EmptyFile && !fec.IsValid(sourcePath) { // Use an exclusion list, include every file by default.
log.Infof(Messages.UnknownFileType, sourcePath)
return
}
// Normalize the path separator in these 2 variables before comparing them.
normSourcePath := strings.ReplaceAll(sourcePath, "/", PS)
normSourcePath = strings.ReplaceAll(normSourcePath, "\\", PS)
// Get the subdirectory from the template source and append it to the
// output directory, so that files are placed in the correct
// subdirectories in the output directory.
partial := strings.ReplaceAll(normSourcePath, normTplDir, "")
//partial = strings.ReplaceAll(partial, PS, "/")
saveDir := filepath.Clean(outDir + filepath.Dir(partial))
log.Infof("partial dir: %v", partial)
log.Infof("save dir: %v", saveDir)
// skip certain files/directories
if currFile == TmplManifest || strings.Contains(partial, PS+gitDir+PS) {
log.Infof(Messages.SkipFile, partial)
return
}
// Make the subdirectories in the new savePath.
err = os.MkdirAll(saveDir, DirMode)
if err != nil || currFile == EmptyFile {
return
}
// exclude from parsing, but copy as-is.
if excludes != nil {
// TODO: Replace with better method of comparing files.
fileToCheck := strings.ReplaceAll(normSourcePath, normTplDir, "")
log.Infof("fileToCheck: %q against excludes", fileToCheck)
fileToCheck = strings.ReplaceAll(fileToCheck, PS, "")
for _, exclude := range excludes {
fileToCheckB := strings.ReplaceAll(exclude, "\\", "")
fileToCheckB = strings.ReplaceAll(exclude, "/", "")
if fileToCheckB == fileToCheck {
log.Infof("will copy as-is: %q", sourcePath)
_, errC := copyToDir(sourcePath, saveDir, PS)
return errC
}
}
}
rErr = Parse(sourcePath, saveDir, vars)
return
})
return
}
// ReadTemplateJson read variables needed from the template.json file.
func ReadTemplateJson(filePath string) (*TmplJson, error) {
log.Dbugf("\ntemplate manifest path: %q\n", filePath)
// Verify the TMPL_MANIFEST file is present.
if !stdlib.PathExist(filePath) {
return nil, fmt.Errorf(Errors.TmplManifest404, TmplManifest)
}
content, err1 := ioutil.ReadFile(filePath)
if err1 != nil {
return nil, err1
}
log.Infof("content = %s \n", content)
q := TmplJson{}
if err2 := json.Unmarshal(content, &q); err2 != nil {
return nil, err2
}
log.Dbugf("TmplJson.Version = %v", q.Version)
if q.Version == "" {
return nil, fmt.Errorf("missing the Version propery in template.json")
}
log.Dbugf("TmplJson.Placeholders = %v", len(q.Placeholders))
if q.Placeholders == nil {
return nil, fmt.Errorf("missing the placeholders propery in template.json")
}
return &q, nil
}
func ShowAllPlaceholderValues(placeholders *TmplJson, tmplValues *tmplVars) {
tVals := *tmplValues
log.Logf("the following values have been provided\n")
for placeholder, _ := range placeholders.Placeholders {
log.Logf(Messages.PlaceholderAnswer, placeholder, tVals[placeholder])
}
}
|
package bst
import (
"errors"
"github.com/ag0st/binarytree"
"log"
)
// BST struct used to store a binary search tree
type BST struct {
tree *binarytree.BinaryTree
crtSize int
}
type Comparable interface {
// CompareTo returns "< 0" if this > other; ">0" if this > other; "0" if this == other
CompareTo(other Comparable) int
}
// NewBSTReady creates new Binary Search Tree with values in sorted.
// Method to use when the data are ready: sorted and no duplicates
// PRE: sorted, no duplicate
func NewBSTReady(sorted []Comparable) *BST {
return &BST{
tree: optimalBST(sorted, 0, len(sorted)-1),
crtSize: len(sorted),
}
}
// NewBST creates an empty Binary Search Tree
func NewBST() *BST {
return &BST{
tree: &binarytree.BinaryTree{},
crtSize: 0,
}
}
// Add a new element in the tree if not present (use CompareTo method)
func (bst *BST) Add(e Comparable) {
itr := bst.locate(e)
if !itr.IsBottom() {
return // Already present in the structure
}
itr.Insert(e)
bst.crtSize++
}
// Remove remove the element if present (use CompareTo method)
func (bst *BST) Remove(e Comparable) {
itr := bst.locate(e)
if itr.IsBottom() {
return // nothing to remove, do not exists
}
bst.crtSize--
// Push the element as leaf with rotation to keep order
for itr.HasRight() {
itr.RotateLeft()
itr = itr.Left()
}
// remove the element and paste subtree if not leaf
if !itr.IsLeaf() {
l := itr.Left().Cut()
itr.Cut()
err := itr.Paste(l)
if err != nil {
log.Fatalln("CANNOT CUT AND PASTE WHEN REMOVING")
}
} else {
itr.Cut()
}
}
// Contains tells if the BST contains the element (use CompareTo)
func (bst *BST) Contains(e Comparable) bool {
itr := bst.locate(e)
return !itr.IsBottom()
}
// Size returns the size of the tree
func (bst *BST) Size() int {
return bst.crtSize
}
// IntervalSearch returns all elements in the interval [min, max] (inclusive)
func (bst *BST) IntervalSearch(min, max Comparable) []Comparable {
return intervalSearch(bst.tree.Root(), min, max)
}
func (bst *BST) Get(e Comparable) (Comparable, error) {
itr := bst.locate(e)
if itr.IsBottom() {
return nil, errors.New("element not present, please use Contains method before")
}
return itr.Consult().(Comparable), nil
}
func (bst *BST) GetPredSucc(e Comparable) (pred, ele, succ Comparable) {
itr := bst.tree.Root()
for !itr.IsBottom() {
current := itr.Consult().(Comparable)
if e.CompareTo(current) == 0 {
if itr.HasRight() {
succ = itr.Right().LeftMost().Up().Consult().(Comparable)
}
if itr.HasLeft() {
pred = itr.Left().RightMost().Up().Consult().(Comparable)
}
ele = itr.Consult().(Comparable)
break
} else if e.CompareTo(current) < 0 {
succ = itr.Consult().(Comparable)
itr = itr.Left()
} else {
pred = itr.Consult().(Comparable)
itr = itr.Right()
}
}
return pred, ele, succ
}
// intervalSearch returns all elements in the interval [min, max] (inclusive) from the iterator position
func intervalSearch(itr *binarytree.Iterator, min, max Comparable) []Comparable {
var res []Comparable
if itr.IsBottom() {
return res
}
current := itr.Consult().(Comparable)
if current.CompareTo(min) >= 0 && current.CompareTo(max) <= 0 {
res = append(res, current)
}
if itr.IsLeaf() { // no more left or right subtree
return res
}
if current.CompareTo(max) < 0 { // if current < max --> check right
res = append(res, intervalSearch(itr.Right(), min, max)...)
}
if current.CompareTo(min) > 0 { // if current > min --> check left
res = append(res, intervalSearch(itr.Left(), min, max)...)
}
return res
}
// locate returns the position where the comparable is or where it must be added if not present
func (bst *BST) locate(e Comparable) *binarytree.Iterator {
itr := bst.tree.Root()
for !itr.IsBottom() {
current := itr.Consult().(Comparable)
if e.CompareTo(current) == 0 {
break
} else if e.CompareTo(current) < 0 {
itr = itr.Left()
} else {
itr = itr.Right()
}
}
return itr
}
// optimalBST creates a balanced BST with the sorted array given in parameter using the slice between left and right
func optimalBST(sorted []Comparable, left, right int) *binarytree.BinaryTree {
tree := &binarytree.BinaryTree{}
itr := tree.Root()
if left > right {
return tree
}
mid := (left + right) / 2
itr.Insert(sorted[mid])
err := itr.Left().Paste(optimalBST(sorted, left, mid-1))
if err != nil {
log.Fatalln("OPTIMAL BST: Cannot paste left")
}
err = itr.Right().Paste(optimalBST(sorted, mid+1, right))
if err != nil {
log.Fatalln("OPTIMAL BST: Cannot paste right")
}
return tree
}
|
package commands
import (
"fmt"
"log"
"os"
)
func ChangeDirectory(arguments []string) {
if len(arguments) < 2 {
fmt.Fprintln(os.Stderr, "Invalid path!")
return
}
if arguments[1] == "$HOME" {
homePath, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
if err := os.Chdir(homePath); err != nil {
fmt.Fprintln(os.Stderr, err)
}
} else {
if err := os.Chdir(arguments[1]); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
}
|
package splitter
import (
"bufio"
"errors"
"fmt"
"io"
"math"
"os"
"runtime"
"time"
"github.com/cinus-ue/securekit/common/bytesutil"
"github.com/cinus-ue/securekit/common/sync/parallel"
"github.com/cinus-ue/securekit/termui/ioprogress"
)
type ChunkFile struct {
total int64
offset int64
length int64
id int
file *os.File
}
func newChunkFile(file *os.File, id int, maxId int, chunkSize int64, fileSize int64) *ChunkFile {
var length int64
if id == maxId {
length = fileSize % fileSize
} else {
length = chunkSize
}
return &ChunkFile{
fileSize,
int64(id) * chunkSize,
length,
id,
file,
}
}
func (cf *ChunkFile) save() error {
splitFileName := fmt.Sprintf("%s.spt.%d", cf.file.Name(), cf.id)
file, err := os.Create(splitFileName)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
reader := io.NewSectionReader(cf.file, cf.offset, cf.length)
progressReader := &ioprogress.Reader{
Reader: reader,
Size: reader.Size(),
DrawFunc: ioprogress.DrawTerminalf(os.Stdout, func(progress, total int64) string {
return fmt.Sprintf(" Write to file:%s [%s/%s]", splitFileName, bytesutil.BinaryFormat(progress), bytesutil.BinaryFormat(total))
}),
DrawInterval: time.Microsecond,
}
if _, err = io.Copy(writer, progressReader); err != nil {
return err
}
if err = writer.Flush(); err != nil {
return err
}
return nil
}
func SplitFile(filepath string, chunkSize int64) error {
file, err := os.Open(filepath)
if err != nil {
return err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return err
}
fileSize := info.Size()
if fileSize <= chunkSize {
return errors.New("the file is too small to split")
}
fmt.Println(" Splitting file...")
maxId := int(math.Ceil(float64(fileSize) / float64(chunkSize)))
run := parallel.NewRun(runtime.NumCPU())
for i := 0; i < maxId; i++ {
run.Acquire()
go func(id int) {
defer run.Release()
if err := newChunkFile(file, id, maxId, chunkSize, fileSize).save(); err != nil {
run.Error(err)
}
}(i)
}
if err = run.Wait(); err != nil {
return err
}
fmt.Println(" Split file succeeded")
return nil
}
|
package merchant
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type ModifyMerchantChannelRateLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewModifyMerchantChannelRateLogic(ctx context.Context, svcCtx *svc.ServiceContext) ModifyMerchantChannelRateLogic {
return ModifyMerchantChannelRateLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ModifyMerchantChannelRateLogic) ModifyMerchantChannelRate(req types.ModifyMerchantChannelRateRequest) error {
data := model.MerchantChannel{
Rate: req.ChannelRate,
SingleFee: req.SingleFee,
}
if err := model.NewMerchantChannelModel(l.svcCtx.DbEngine).UpdateRate(req.ChannelId, data); err != nil {
l.Errorf("修改商户通道[%v]费率失败, err=%v", req.ChannelId, err)
return common.NewCodeError(common.SysDBUpdate)
}
return nil
}
|
// Copyright 2016 Walter Schulze
//
// 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 ast
import (
"strings"
)
//Format formats the spacing in the Grammar.
func (this *Grammar) Format() {
if this.TopPattern != nil {
this.TopPattern.format(false)
}
for i, p := range this.PatternDecls {
p.format(i != 0 || this.TopPattern != nil)
}
this.After.format(false)
}
func (this *PatternDecl) format(space bool) {
this.Hash.format(space)
this.Before.format(false)
this.Eq.format(true)
this.Pattern.format(true)
}
//Format formats the spacing in the Pattern.
func (this *Pattern) Format() {
this.format(false)
}
func (this *Pattern) format(space bool) {
v := this.GetValue()
v.(interface {
format(bool)
}).format(space)
}
func (this *Empty) format(space bool) {
this.Empty.format(space)
}
func (this *TreeNode) format(space bool) {
this.Name.format(space)
if this.Colon != nil {
this.Colon.format(false)
}
this.Pattern.format(this.Colon == nil)
}
func (this *Contains) format(space bool) {
this.Dot.format(space)
this.Pattern.format(false)
}
func (this *LeafNode) format(space bool) {
this.Expr.format(space)
}
func (this *Concat) format(space bool) {
this.OpenBracket.format(space)
this.LeftPattern.format(false)
this.Comma.format(false)
this.RightPattern.format(true)
if this.ExtraComma != nil {
this.ExtraComma.format(false)
}
this.CloseBracket.format(this.ExtraComma == nil)
}
func (this *Or) format(space bool) {
this.OpenParen.format(space)
this.LeftPattern.format(false)
this.Pipe.format(true)
this.RightPattern.format(true)
this.CloseParen.format(false)
}
func (this *And) format(space bool) {
this.OpenParen.format(space)
this.LeftPattern.format(false)
this.Ampersand.format(true)
this.RightPattern.format(true)
this.CloseParen.format(false)
}
func (this *ZeroOrMore) format(space bool) {
this.OpenParen.format(space)
this.Pattern.format(false)
this.CloseParen.format(false)
this.Star.format(false)
}
func (this *Reference) format(space bool) {
this.At.format(space)
}
func (this *Not) format(space bool) {
this.Exclamation.format(space)
this.OpenParen.format(false)
this.Pattern.format(false)
this.CloseParen.format(false)
}
func (this *ZAny) format(space bool) {
this.Star.format(space)
}
func (this *Optional) format(space bool) {
this.OpenParen.format(space)
this.Pattern.format(false)
this.CloseParen.format(false)
this.QuestionMark.format(false)
}
func (this *Interleave) format(space bool) {
this.OpenCurly.format(space)
this.LeftPattern.format(false)
this.SemiColon.format(false)
this.RightPattern.format(true)
if this.ExtraSemiColon != nil {
this.ExtraSemiColon.format(false)
}
this.CloseCurly.format(this.ExtraSemiColon == nil)
}
func (this *Expr) format(space bool) {
if this.RightArrow != nil {
this.RightArrow.format(space)
space = false
} else if this.Comma != nil {
this.Comma.format(space)
space = false
}
if this.Terminal != nil {
this.Terminal.format(space)
} else if this.List != nil {
this.List.format(space)
} else if this.Function != nil {
this.Function.format(space)
} else if this.BuiltIn != nil {
this.BuiltIn.format(space)
}
}
func (this *NameExpr) format(space bool) {
v := this.GetValue()
v.(interface {
format(bool)
}).format(space)
}
func (this *Name) format(space bool) {
this.Before.format(space)
}
func (this *AnyName) format(space bool) {
this.Underscore.format(space)
}
func (this *AnyNameExcept) format(space bool) {
this.Exclamation.format(space)
this.OpenParen.format(false)
this.Except.format(false)
this.CloseParen.format(false)
}
func (this *NameChoice) format(space bool) {
this.OpenParen.format(space)
this.Left.format(false)
this.Pipe.format(false)
this.Right.format(false)
this.CloseParen.format(false)
}
func (this *List) format(space bool) {
this.Before.format(space)
this.OpenCurly.format(false)
for i := range this.Elems {
this.Elems[i].format(i != 0)
}
this.CloseCurly.format(false)
}
func (this *Function) format(space bool) {
this.Before.format(space)
this.OpenParen.format(false)
for i := range this.Params {
this.Params[i].format(i != 0)
}
this.CloseParen.format(false)
}
func (this *BuiltIn) format(space bool) {
this.Symbol.format(space)
this.Expr.format(true)
}
func (this *Terminal) format(space bool) {
this.Before.format(space)
}
func (this *Keyword) format(space bool) {
if this == nil {
return
}
this.Before.format(space)
}
func (this *Space) Format() {
this.format(false)
}
func (this *Space) format(space bool) {
if this == nil {
return
}
newSpace := formatSpace(this.Space)
if space {
if len(this.Space) > 0 && strings.Contains(this.Space[len(this.Space)-1], "\n") {
newSpace = append(newSpace, "\n")
} else {
newSpace = append(newSpace, " ")
}
}
this.Space = newSpace
}
type state int
var startState = state(0)
var lineCommentState = state(1)
var blockCommentState = state(2)
func formatSpace(spaces []string) []string {
newlines := 0
current := startState
formatted := []string{}
for _, space := range spaces {
for _, c := range space {
if c == '\n' {
newlines++
}
}
if isComment(space) {
comment := strings.TrimSpace(space)
if isLineComment(space) {
comment = comment + "\n"
}
switch current {
case startState:
formatted = append(formatted, comment)
case lineCommentState:
if newlines >= 2 {
formatted = append(formatted, "\n")
}
formatted = append(formatted, comment)
case blockCommentState:
if newlines >= 2 {
formatted = append(formatted, "\n\n")
}
formatted = append(formatted, comment)
}
if isLineComment(space) {
current = lineCommentState
newlines = 1
} else {
current = blockCommentState
newlines = 0
}
}
}
return formatted
}
|
package cluster
import (
"reflect"
"strconv"
"testing"
"time"
"github.com/quilt/quilt/cluster/acl"
"github.com/quilt/quilt/cluster/machine"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/stitch"
"github.com/stretchr/testify/assert"
)
var FakeAmazon db.Provider = "FakeAmazon"
var FakeVagrant db.Provider = "FakeVagrant"
var amazonCloudConfig = "Amazon Cloud Config"
var vagrantCloudConfig = "Vagrant Cloud Config"
var testRegion = "Fake region"
type providerRequest struct {
request machine.Machine
provider provider
boot bool
}
type bootRequest struct {
size string
cloudConfig string
}
type ipRequest struct {
size string
cloudConfig string
ip string
}
type fakeProvider struct {
namespace string
machines map[string]machine.Machine
idCounter int
cloudConfig string
bootRequests []bootRequest
stopRequests []string
updateIPs []ipRequest
aclRequests []acl.ACL
}
func fakeValidRegions(p db.Provider) []string {
return []string{testRegion}
}
func newFakeProvider(p db.Provider, namespace, region string) (provider, error) {
var ret fakeProvider
ret.namespace = namespace
ret.machines = make(map[string]machine.Machine)
ret.clearLogs()
switch p {
case FakeAmazon:
ret.cloudConfig = amazonCloudConfig
case FakeVagrant:
ret.cloudConfig = vagrantCloudConfig
default:
panic("Unreached")
}
return &ret, nil
}
func (p *fakeProvider) clearLogs() {
p.bootRequests = []bootRequest{}
p.stopRequests = []string{}
p.aclRequests = []acl.ACL{}
p.updateIPs = []ipRequest{}
}
func (p *fakeProvider) List() ([]machine.Machine, error) {
var machines []machine.Machine
for _, machine := range p.machines {
machines = append(machines, machine)
}
return machines, nil
}
func (p *fakeProvider) Boot(bootSet []machine.Machine) error {
for _, bootSet := range bootSet {
p.idCounter++
idStr := strconv.Itoa(p.idCounter)
bootSet.ID = idStr
p.machines[idStr] = bootSet
p.bootRequests = append(p.bootRequests, bootRequest{size: bootSet.Size,
cloudConfig: p.cloudConfig})
}
return nil
}
func (p *fakeProvider) Stop(machines []machine.Machine) error {
for _, machine := range machines {
delete(p.machines, machine.ID)
p.stopRequests = append(p.stopRequests, machine.ID)
}
return nil
}
func (p *fakeProvider) SetACLs(acls []acl.ACL) error {
p.aclRequests = acls
return nil
}
func (p *fakeProvider) UpdateFloatingIPs(machines []machine.Machine) error {
for _, m := range machines {
p.updateIPs = append(p.updateIPs, ipRequest{
size: m.Size,
cloudConfig: p.cloudConfig,
ip: m.FloatingIP,
})
p.machines[m.ID] = m
}
return nil
}
func (p *fakeProvider) Connect(namespace string) error { return nil }
func (p *fakeProvider) ChooseSize(ram stitch.Range, cpu stitch.Range,
maxPrice float64) string {
return ""
}
func newTestCluster(namespace string) *cluster {
sleep = func(t time.Duration) {}
mock()
return newCluster(db.New(), namespace)
}
func TestPanicBadProvider(t *testing.T) {
temp := allProviders
defer func() {
r := recover()
assert.NotNil(t, r)
allProviders = temp
}()
allProviders = []db.Provider{FakeAmazon}
conn := db.New()
newCluster(conn, "test")
}
func TestSyncDB(t *testing.T) {
checkSyncDB := func(cloudMachines []machine.Machine,
databaseMachines []db.Machine, expected syncDBResult) {
dbRes := syncDB(cloudMachines, databaseMachines)
assert.Equal(t, expected.boot, dbRes.boot, "boot")
assert.Equal(t, expected.stop, dbRes.stop, "stop")
assert.Equal(t, expected.updateIPs, dbRes.updateIPs, "updateIPs")
}
var noMachines []machine.Machine
dbNoSize := db.Machine{Provider: FakeAmazon, Region: testRegion}
cmNoSize := machine.Machine{Provider: FakeAmazon, Region: testRegion}
dbLarge := db.Machine{Provider: FakeAmazon, Size: "m4.large", Region: testRegion}
cmLarge := machine.Machine{Provider: FakeAmazon, Size: "m4.large",
Region: testRegion}
cmNoIP := machine.Machine{Provider: FakeAmazon}
cmWithIP := machine.Machine{Provider: FakeAmazon, FloatingIP: "ip"}
dbNoIP := db.Machine{Provider: FakeAmazon}
dbWithIP := db.Machine{Provider: FakeAmazon, FloatingIP: "ip"}
// Test boot with no size
checkSyncDB(noMachines, []db.Machine{dbNoSize, dbNoSize}, syncDBResult{
boot: []machine.Machine{cmNoSize, cmNoSize},
})
// Test boot with size
checkSyncDB(noMachines, []db.Machine{dbLarge, dbLarge}, syncDBResult{
boot: []machine.Machine{cmLarge, cmLarge},
})
// Test mixed boot
checkSyncDB(noMachines, []db.Machine{dbNoSize, dbLarge}, syncDBResult{
boot: []machine.Machine{cmNoSize, cmLarge},
})
// Test partial boot
checkSyncDB([]machine.Machine{cmNoSize}, []db.Machine{dbNoSize, dbLarge},
syncDBResult{
boot: []machine.Machine{cmLarge},
},
)
// Test stop
checkSyncDB([]machine.Machine{cmNoSize, cmNoSize}, []db.Machine{}, syncDBResult{
stop: []machine.Machine{cmNoSize, cmNoSize},
})
// Test partial stop
checkSyncDB([]machine.Machine{cmNoSize, cmLarge}, []db.Machine{}, syncDBResult{
stop: []machine.Machine{cmNoSize, cmLarge},
})
// Test assign Floating IP
checkSyncDB([]machine.Machine{cmNoIP}, []db.Machine{dbWithIP}, syncDBResult{
updateIPs: []machine.Machine{cmWithIP},
})
// Test remove Floating IP
checkSyncDB([]machine.Machine{cmWithIP}, []db.Machine{dbNoIP}, syncDBResult{
updateIPs: []machine.Machine{cmNoIP},
})
// Test replace Floating IP
cNewIP := machine.Machine{Provider: FakeAmazon, FloatingIP: "ip^"}
checkSyncDB([]machine.Machine{cNewIP}, []db.Machine{dbWithIP}, syncDBResult{
updateIPs: []machine.Machine{cmWithIP},
})
// Test bad disk size
checkSyncDB([]machine.Machine{{DiskSize: 3}}, []db.Machine{{DiskSize: 4}},
syncDBResult{
stop: []machine.Machine{{DiskSize: 3}},
boot: []machine.Machine{{DiskSize: 4}},
})
}
func TestSync(t *testing.T) {
type assertion struct {
boot []bootRequest
stop []string
updateIPs []ipRequest
}
checkSync := func(clst *cluster, provider db.Provider, region string,
expected assertion) {
clst.runOnce()
inst := instance{provider, region}
providerInst := clst.providers[inst].(*fakeProvider)
if !emptySlices(expected.boot, providerInst.bootRequests) {
assert.Equal(t, expected.boot, providerInst.bootRequests,
"bootRequests")
}
if !emptySlices(expected.stop, providerInst.stopRequests) {
assert.Equal(t, expected.stop, providerInst.stopRequests,
"stopRequests")
}
if !emptySlices(expected.updateIPs, providerInst.updateIPs) {
assert.Equal(t, expected.updateIPs, providerInst.updateIPs,
"updateIPs")
}
providerInst.clearLogs()
}
amazonLargeBoot := bootRequest{size: "m4.large", cloudConfig: amazonCloudConfig}
amazonXLargeBoot := bootRequest{size: "m4.xlarge",
cloudConfig: amazonCloudConfig}
vagrantLargeBoot := bootRequest{size: "vagrant.large",
cloudConfig: vagrantCloudConfig}
// Test initial boot
clst := newTestCluster("ns")
setNamespace(clst.conn, "ns")
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.Provider = FakeAmazon
m.Region = testRegion
m.Size = "m4.large"
view.Commit(m)
return nil
})
checkSync(clst, FakeAmazon, testRegion,
assertion{boot: []bootRequest{amazonLargeBoot}})
// Test adding a machine with the same provider
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.Provider = FakeAmazon
m.Region = testRegion
m.Size = "m4.xlarge"
view.Commit(m)
return nil
})
checkSync(clst, FakeAmazon, testRegion,
assertion{boot: []bootRequest{amazonXLargeBoot}})
// Test adding a machine with a different provider
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.Provider = FakeVagrant
m.Region = testRegion
m.Size = "vagrant.large"
view.Commit(m)
return nil
})
checkSync(clst, FakeVagrant, testRegion,
assertion{boot: []bootRequest{vagrantLargeBoot}})
// Test removing a machine
var toRemove db.Machine
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
toRemove = view.SelectFromMachine(func(m db.Machine) bool {
return m.Provider == FakeAmazon && m.Size == "m4.xlarge"
})[0]
view.Remove(toRemove)
return nil
})
checkSync(clst, FakeAmazon, testRegion,
assertion{stop: []string{toRemove.CloudID}})
// Test booting a machine with floating IP
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.Provider = FakeAmazon
m.Size = "m4.large"
m.Region = testRegion
m.FloatingIP = "ip"
view.Commit(m)
return nil
})
checkSync(clst, FakeAmazon, testRegion, assertion{
boot: []bootRequest{amazonLargeBoot},
updateIPs: []ipRequest{{
size: "m4.large",
cloudConfig: amazonCloudConfig,
ip: "ip",
}},
})
// Test assigning a floating IP to an existing machine
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
toAssign := view.SelectFromMachine(func(m db.Machine) bool {
return m.Provider == FakeAmazon &&
m.Size == "m4.large" &&
m.FloatingIP == ""
})[0]
toAssign.FloatingIP = "another.ip"
view.Commit(toAssign)
return nil
})
checkSync(clst, FakeAmazon, testRegion, assertion{
updateIPs: []ipRequest{{
size: "m4.large",
cloudConfig: amazonCloudConfig,
ip: "another.ip",
}},
})
// Test removing a floating IP
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
toUpdate := view.SelectFromMachine(func(m db.Machine) bool {
return m.Provider == FakeAmazon &&
m.Size == "m4.large" &&
m.FloatingIP == "ip"
})[0]
toUpdate.FloatingIP = ""
view.Commit(toUpdate)
return nil
})
checkSync(clst, FakeAmazon, testRegion, assertion{
updateIPs: []ipRequest{{
size: "m4.large",
cloudConfig: amazonCloudConfig,
ip: "",
}},
})
// Test removing and adding a machine
clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
toRemove = view.SelectFromMachine(func(m db.Machine) bool {
return m.Provider == FakeAmazon && m.Size == "m4.large"
})[0]
view.Remove(toRemove)
m := view.InsertMachine()
m.Role = db.Worker
m.Provider = FakeAmazon
m.Size = "m4.xlarge"
m.Region = testRegion
view.Commit(m)
return nil
})
checkSync(clst, FakeAmazon, testRegion, assertion{
boot: []bootRequest{amazonXLargeBoot},
stop: []string{toRemove.CloudID},
})
}
func TestACLs(t *testing.T) {
myIP = func() (string, error) {
return "5.6.7.8", nil
}
clst := newTestCluster("ns")
clst.syncACLs([]string{"admin"},
[]db.PortRange{
{
MinPort: 80,
MaxPort: 80,
},
},
[]db.Machine{
{
Provider: FakeAmazon,
PublicIP: "8.8.8.8",
Region: testRegion,
},
{},
},
)
exp := []acl.ACL{
{
CidrIP: "admin",
MinPort: 1,
MaxPort: 65535,
},
{
CidrIP: "5.6.7.8/32",
MinPort: 1,
MaxPort: 65535,
},
{
CidrIP: "0.0.0.0/0",
MinPort: 80,
MaxPort: 80,
},
{
CidrIP: "8.8.8.8/32",
MinPort: 1,
MaxPort: 65535,
},
}
inst := instance{FakeAmazon, testRegion}
actual := clst.providers[inst].(*fakeProvider).aclRequests
assert.Equal(t, exp, actual)
}
func TestUpdateCluster(t *testing.T) {
conn := db.New()
clst := updateCluster(conn, nil)
assert.Nil(t, clst)
setNamespace(conn, "ns1")
clst = updateCluster(conn, clst)
assert.NotNil(t, clst)
assert.Equal(t, "ns1", clst.namespace)
inst := instance{FakeAmazon, testRegion}
amzn := clst.providers[inst].(*fakeProvider)
assert.Empty(t, amzn.bootRequests)
assert.Empty(t, amzn.stopRequests)
assert.Equal(t, "ns1", amzn.namespace)
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Provider = FakeAmazon
m.Size = "size1"
m.Region = testRegion
view.Commit(m)
return nil
})
oldClst := clst
oldAmzn := amzn
clst = updateCluster(conn, clst)
assert.NotNil(t, clst)
// Pointers shouldn't have changed
amzn = clst.providers[inst].(*fakeProvider)
assert.True(t, oldClst == clst)
assert.True(t, oldAmzn == amzn)
assert.Empty(t, amzn.stopRequests)
assert.Equal(t, []bootRequest{{
size: "size1",
cloudConfig: amazonCloudConfig,
}}, amzn.bootRequests)
assert.Equal(t, "ns1", amzn.namespace)
amzn.clearLogs()
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
dbms := view.SelectFromMachine(nil)
dbms[0].Size = "size2"
view.Commit(dbms[0])
return nil
})
oldClst = clst
oldAmzn = amzn
setNamespace(conn, "ns2")
clst = updateCluster(conn, clst)
assert.NotNil(t, clst)
// Pointers should have changed
amzn = clst.providers[inst].(*fakeProvider)
assert.True(t, oldClst != clst)
assert.True(t, oldAmzn != amzn)
assert.Equal(t, "ns1", oldAmzn.namespace)
assert.Empty(t, oldAmzn.bootRequests)
assert.Empty(t, oldAmzn.stopRequests)
assert.Equal(t, "ns2", amzn.namespace)
assert.Equal(t, []bootRequest{{
size: "size2",
cloudConfig: amazonCloudConfig,
}}, amzn.bootRequests)
assert.Empty(t, amzn.stopRequests)
}
func TestMultiRegionDeploy(t *testing.T) {
clst := newTestCluster("ns")
clst.conn.Txn(db.MachineTable,
db.ClusterTable).Run(func(view db.Database) error {
for _, p := range allProviders {
for _, r := range validRegions(p) {
m := view.InsertMachine()
m.Provider = p
m.Region = r
m.Size = "size1"
view.Commit(m)
}
}
c := view.InsertCluster()
c.Namespace = "ns"
view.Commit(c)
return nil
})
for i := 0; i < 2; i++ {
clst.runOnce()
cloudMachines, err := clst.get()
assert.NoError(t, err)
dbMachines := clst.conn.SelectFromMachine(nil)
joinResult := syncDB(cloudMachines, dbMachines)
// All machines should be booted
assert.Empty(t, joinResult.boot)
assert.Empty(t, joinResult.stop)
assert.Len(t, joinResult.pairs, len(dbMachines))
}
clst.conn.Txn(db.MachineTable).Run(func(view db.Database) error {
m := view.SelectFromMachine(func(m db.Machine) bool {
return m.Provider == FakeAmazon &&
m.Region == validRegions(FakeAmazon)[0]
})
assert.Len(t, m, 1)
view.Remove(m[0])
return nil
})
clst.runOnce()
machinesRemaining, err := clst.get()
assert.NoError(t, err)
assert.NotContains(t, machinesRemaining, machine.Machine{
Size: "size1",
Provider: FakeAmazon,
Region: validRegions(FakeAmazon)[0],
})
cloudMachines, err := clst.get()
assert.NoError(t, err)
dbMachines := clst.conn.SelectFromMachine(nil)
joinResult := syncDB(cloudMachines, dbMachines)
assert.Empty(t, joinResult.boot)
assert.Empty(t, joinResult.stop)
assert.Len(t, joinResult.pairs, len(dbMachines))
}
func setNamespace(conn db.Conn, ns string) {
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
clst, err := view.GetCluster()
if err != nil {
clst = view.InsertCluster()
}
clst.Namespace = ns
view.Commit(clst)
return nil
})
}
func mock() {
newProvider = newFakeProvider
validRegions = fakeValidRegions
allProviders = []db.Provider{FakeAmazon, FakeVagrant}
}
func emptySlices(slice1 interface{}, slice2 interface{}) bool {
return reflect.ValueOf(slice1).Len() == 0 && reflect.ValueOf(slice2).Len() == 0
}
|
package controllers
import (
"FinalProject/BlogApi/models"
"github.com/astaxie/beego"
)
// Operations about object
type ObjectController struct {
beego.Controller
}
// @Title Create
// @Description create object
// @Param body body models.Object true "The object content"
// @Success 200 {string} models.Object.Id
// @Failure 403 body is empty
// @Title GetAll
// @Description get all objects
// @Success 200 {object} models.Object
// @Failure 403 :objectId is empty
// @router / [get]
func (o *ObjectController) GetAll() {
obs := models.GetAll()
o.Data["json"] = obs
o.ServeJSON()
}
|
package test
import (
"fmt"
"testing"
"goStudy/lib/g"
)
func Test_is_zero(t *testing.T) {
i := 0
fmt.Println(g.IsZero(&i))
}
func Test_isZeroAll(t *testing.T) {
fmt.Println(g.IsZeroAll())
}
|
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"sync/atomic"
)
var count int64
var ch = make(chan (int))
func handler(res http.ResponseWriter, req *http.Request) {
atomic.AddInt64(&count, 1)
body, _ := ioutil.ReadAll(req.Body)
fmt.Println(string(body))
reses := []string{"success", "success"}
choice := []int{0, 0, 0, 0, 0, 0, 0, 1}
ret := reses[choice[rand.Intn(len(choice))]]
//time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
io.WriteString(res, ret)
}
func static(res http.ResponseWriter, req *http.Request) {
fmt.Fprintf(res, "count %d\n", count)
}
func server(port string) {
fmt.Println("listening on " + port)
http.ListenAndServe(":"+port, nil)
}
func main() {
http.HandleFunc("/get", handler)
http.HandleFunc("/", static)
flag.Parse()
port := flag.Arg(0)
if port == "" {
port = "8091"
}
go server(port)
<-ch
}
|
package main_camera
import (
util "github.com/verlandz/clustering-phone/utility"
"os"
"strconv"
"strings"
)
const (
DEFAULT_PATH = "main_camera/main_camera"
INPUT_PATH = DEFAULT_PATH + ".in"
OUTPUT_PATH = DEFAULT_PATH + ".out"
)
var (
arr []float64
mean = 0.000
valid = 0.00
def = -1.00
)
func Clean() {
// data preparation
data := strings.Split(util.GetData(INPUT_PATH), "\n")
for i, v := range data {
// skip header
if i == 0 {
continue
}
if v == "No" {
arr = append(arr, 0)
valid++
mean += 0
continue
} else if v == "" {
arr = append(arr, def)
} else {
temp := strings.Fields(v)
var a string
for i := range temp {
a = temp[i]
break
}
x, err := strconv.ParseFloat(a, 64)
if x != 0 && err == nil {
valid++
mean += x
} else {
x = def
}
arr = append(arr, x)
}
}
// if there's invalid data , we will use mean from all valid data
mean /= valid
// data output
f, err := os.Create(OUTPUT_PATH)
util.Check(err)
defer f.Close()
f.WriteString("Main Camera(MP)")
for _, v := range arr {
s := ""
if v == def {
s += strconv.FormatFloat(mean, 'f', -1, 64)
} else {
s += strconv.FormatFloat(v, 'f', -1, 64)
}
f.WriteString("\n" + s)
}
}
|
package identity
import (
"fmt"
"log"
"strings"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/databrickslabs/databricks-terraform/common"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func ResourceGroupInstanceProfile() *schema.Resource {
return &schema.Resource{
Create: resourceGroupInstanceProfileCreate,
Read: resourceGroupInstanceProfileRead,
Delete: resourceGroupInstanceProfileDelete,
Schema: map[string]*schema.Schema{
"group_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"instance_profile_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
ValidateFunc: ValidateInstanceProfileARN,
},
},
}
}
// ValidateInstanceProfileARN is a ValidateFunc that ensures the role id is a valid aws iam instance profile arn
func ValidateInstanceProfileARN(val interface{}, key string) (warns []string, errs []error) {
v := val.(string)
if v == "" {
return nil, []error{fmt.Errorf("%s is empty got: %s, must be an aws instance profile arn", key, v)}
}
// Parse and verify instance profiles
instanceProfileArn, err := arn.Parse(v)
if err != nil {
return nil, []error{fmt.Errorf("%s is invalid got: %s received error: %w", key, v, err)}
}
// Verify instance profile resource type, Resource gets parsed as instance-profile/<profile-name>
if !strings.HasPrefix(instanceProfileArn.Resource, "instance-profile") {
return nil, []error{fmt.Errorf("%s must be an instance profile resource, got: %s in %s",
key, instanceProfileArn.Resource, v)}
}
return nil, nil
}
func resourceGroupInstanceProfileCreate(d *schema.ResourceData, m interface{}) error {
client := m.(*common.DatabricksClient)
groupID := d.Get("group_id").(string)
instanceProfileID := d.Get("instance_profile_id").(string)
groupInstanceProfileID := &groupInstanceProfileID{
GroupID: groupID,
InstanceProfileID: instanceProfileID,
}
roleAddList := []string{groupInstanceProfileID.InstanceProfileID}
err := NewGroupsAPI(client).Patch(groupInstanceProfileID.GroupID, roleAddList, nil, GroupRolesPath)
if err != nil {
return err
}
d.SetId(groupInstanceProfileID.String())
return resourceGroupInstanceProfileRead(d, m)
}
func resourceGroupInstanceProfileRead(d *schema.ResourceData, m interface{}) error {
id := d.Id()
client := m.(*common.DatabricksClient)
groupInstanceProfileID := parsegroupInstanceProfileID(id)
group, err := NewGroupsAPI(client).Read(groupInstanceProfileID.GroupID)
// First verify if the group exists
if err != nil {
if e, ok := err.(common.APIError); ok && e.IsMissing() {
log.Printf("missing resource due to error: %v\n", e)
d.SetId("")
return nil
}
return err
}
// Set Id to null if instance profile is not in group
if !InstanceProfileInGroup(groupInstanceProfileID.InstanceProfileID, &group) {
log.Printf("Missing role %s in group with id: %s.", groupInstanceProfileID.InstanceProfileID, groupInstanceProfileID.GroupID)
d.SetId("")
return nil
}
err = d.Set("group_id", groupInstanceProfileID.GroupID)
if err != nil {
return err
}
err = d.Set("instance_profile_id", groupInstanceProfileID.InstanceProfileID)
return err
}
func resourceGroupInstanceProfileDelete(d *schema.ResourceData, m interface{}) error {
id := d.Id()
client := m.(*common.DatabricksClient)
groupInstanceProfileID := parsegroupInstanceProfileID(id)
roleRemoveList := []string{groupInstanceProfileID.InstanceProfileID}
// Patch op to remove role from group
err := NewGroupsAPI(client).Patch(groupInstanceProfileID.GroupID, nil, roleRemoveList, GroupRolesPath)
return err
}
type groupInstanceProfileID struct {
GroupID string
InstanceProfileID string
}
func (g groupInstanceProfileID) String() string {
return fmt.Sprintf("%s|%s", g.GroupID, g.InstanceProfileID)
}
func parsegroupInstanceProfileID(id string) *groupInstanceProfileID {
parts := strings.Split(id, "|")
return &groupInstanceProfileID{
GroupID: parts[0],
InstanceProfileID: parts[1],
}
}
func InstanceProfileInGroup(role string, group *Group) bool {
for _, groupRole := range group.Roles {
if groupRole.Value == role {
return true
}
}
return false
}
|
package tls
import (
"crypto/x509"
"crypto/x509/pkix"
"net"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSignedCertKeyGenerate(t *testing.T) {
tests := []struct {
name string
certCfg *CertCfg
filenameBase string
certFileName string
appendParent AppendParentChoice
errString string
}{
{
name: "simple ca",
certCfg: &CertCfg{
Subject: pkix.Name{CommonName: "test0-ca", OrganizationalUnit: []string{"openshift"}},
KeyUsages: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
Validity: ValidityTenYears,
DNSNames: []string{"test.openshift.io"},
},
filenameBase: "test0-ca",
appendParent: DoNotAppendParent,
},
{
name: "more complicated ca",
certCfg: &CertCfg{
Subject: pkix.Name{CommonName: "test1-ca", OrganizationalUnit: []string{"openshift"}},
KeyUsages: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
Validity: ValidityTenYears,
DNSNames: []string{"test.openshift.io"},
IPAddresses: []net.IP{net.ParseIP("10.0.0.1")},
},
filenameBase: "test1-ca",
appendParent: AppendParent,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rootCA := &RootCA{}
err := rootCA.Generate(nil)
assert.NoError(t, err, "failed to generate root CA")
certKey := &SignedCertKey{}
err = certKey.Generate(tt.certCfg, rootCA, tt.filenameBase, tt.appendParent)
if err != nil {
assert.EqualErrorf(t, err, tt.errString, tt.name)
return
} else if tt.errString != "" {
t.Errorf("expect error %v, saw nil", err)
}
actualFiles := certKey.Files()
assert.Equal(t, 2, len(actualFiles), "unexpected number of files")
assert.Equal(t, assetFilePath(tt.filenameBase+".key"), actualFiles[0].Filename, "unexpected key file name")
assert.Equal(t, assetFilePath(tt.filenameBase+".crt"), actualFiles[1].Filename, "unexpected cert file name")
assert.Equal(t, certKey.Key(), actualFiles[0].Data, "key file data does not match key")
assert.Equal(t, certKey.Cert(), actualFiles[1].Data, "cert file does not match cert")
// Briefly check the certs.
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certKey.Cert()) {
t.Error("failed to append certs from PEM")
}
opts := x509.VerifyOptions{
Roots: certPool,
DNSName: tt.certCfg.Subject.CommonName,
}
if tt.certCfg.DNSNames != nil {
opts.DNSName = "test.openshift.io"
}
cert, err := PemToCertificate(certKey.Cert())
assert.NoError(t, err, tt.name)
_, err = cert.Verify(opts)
assert.NoError(t, err, tt.name)
})
}
}
|
package osc
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
type Client struct {
Url string
Response *http.Response
}
func NewClient(url string) (client *Client, error error) {
client = new(Client)
client.Url = url
return
}
type Endpoints struct {
HttpPort *int
HttpUpdatesPort *int
HttpsPort *int
HttpsUpdatesPort *int
}
type Info struct {
Manufacturer *string
Model *string
SerialNumber *string
FirmwareVersion *string
SupportUrl *string
Gps *bool
Gyro *bool
Uptime *int
Api *[]string
Endpoints *Endpoints
}
func (client *Client) Info() (info Info, error error) {
client.Response, error = http.Get(client.Url + "/osc/info")
if error != nil {
return
}
body, error := ioutil.ReadAll(client.Response.Body)
defer client.Response.Body.Close()
if error != nil {
return
}
json.Unmarshal(body, &info)
return
}
type CameraState struct {
SessionId *string
BatteryLevel *float32
StorageChanged *bool
}
type State struct {
Fingerprint *string
State *CameraState
}
func (client *Client) State() (state State, error error) {
client.Response, error = http.PostForm(client.Url+"/osc/state", nil)
if error != nil {
return
}
body, error := ioutil.ReadAll(client.Response.Body)
defer client.Response.Body.Close()
if error != nil {
return
}
json.Unmarshal(body, &state)
return
}
type CheckForUpdatesResponse struct {
StateFingerprint *string
ThrottleTimeout *int
}
func (client *Client) CheckForUpdates(stateFingerprint string, waitTimeout *int) (response CheckForUpdatesResponse, error error) {
request_json := `{"stateFingerprint": "` + stateFingerprint + `"`
if waitTimeout != nil {
request_json += `,` + strconv.Itoa(*waitTimeout)
}
request_json = request_json + `}`
client.Response, error = http.Post(client.Url+"/osc/checkForUpdates", "application/json", strings.NewReader(request_json))
if error != nil {
return
}
body, error := ioutil.ReadAll(client.Response.Body)
defer client.Response.Body.Close()
json.Unmarshal(body, &response)
return
}
type CommandExecError struct {
Code *string
Message *string
}
type CommandExecProgress struct {
Completion *float32
}
type CommandExecResponse struct {
Name *string
State *string
Id *string
Results interface{}
Error *CommandExecError
Progress *CommandExecProgress
}
func (client *Client) CommandExecute(command Command) (response CommandExecResponse, error error) {
parameters_json, _ := json.Marshal(command.GetParameters())
request_json := `{"name": "` + command.GetName() + `", "parameters": ` + string(parameters_json) + `}`
client.Response, error = http.Post(client.Url+"/osc/commands/execute", "application/json", strings.NewReader(request_json))
if error != nil {
return
}
content_type := client.Response.Header.Get("Content-Type")
if strings.Contains(content_type, "json") {
body, _ := ioutil.ReadAll(client.Response.Body)
defer client.Response.Body.Close()
response.Results = command.GetResults()
json.Unmarshal(body, &response)
} else {
response.Results = client.Response.Body
}
return
}
func (client *Client) CommandStatus(id string, command Command) (response CommandExecResponse, error error) {
request_json := `{"id": "` + id + `"}`
client.Response, error = http.Post(client.Url+"/osc/commands/status", "application/json", strings.NewReader(request_json))
if error != nil {
return
}
body, error := ioutil.ReadAll(client.Response.Body)
defer client.Response.Body.Close()
response.Results = command.GetResults()
json.Unmarshal(body, &response)
return
}
|
package main
import (
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"k8s.io/api/core/v1"
)
// NodeStartUpObserver describes an observer which can observe the startup
// time duration of a node.
type NodeStartUpObserver interface {
ObserveNode(node v1.Node)
}
// ASGNodeStartUpObserver is a node startup duration oberserver which determines
// the statup time duration based on ec2 instance launch time.
type ASGNodeStartUpObserver struct {
ec2Client ec2iface.EC2API
nodesObserved sync.Map
startUpDurationSeconds prometheus.Summary
}
// NewASGNodeStartUpObserver registers a prometheus summary vec and returns a
// ASGNodeStartUpObserver.
func NewASGNodeStartUpObserver(sess *session.Session) (*ASGNodeStartUpObserver, error) {
startUpDurationSeconds := prometheus.NewSummary(
prometheus.SummaryOpts{
Name: "startup_duration_seconds",
Help: "The node startup latencies in seconds.",
Subsystem: "node",
Objectives: prometheus.DefObjectives,
},
)
err := prometheus.Register(startUpDurationSeconds)
if err != nil {
return nil, err
}
return &ASGNodeStartUpObserver{
ec2Client: ec2.New(sess),
startUpDurationSeconds: startUpDurationSeconds,
}, nil
}
// ObserveNode observes the node startup time duration based on the launch
// time of the underlying ec2 instance.
// The observation is executed in a go routine to not block the caller.
func (o *ASGNodeStartUpObserver) ObserveNode(node v1.Node) {
go func() {
now := time.Now().UTC()
if _, ok := o.nodesObserved.Load(node.Name); ok {
log.Infof("Ignoring node %s already observed", node.Name)
return
}
launchTime, err := o.nodeLaunchTime(node.Spec.ProviderID)
if err != nil {
log.Errorf("Failed to get node launch time: %v", err)
return
}
o.startUpDurationSeconds.Observe(now.Sub(launchTime).Seconds())
// record that node was observed
o.nodesObserved.Store(node.Name, nil)
}()
}
// nodeLaunchTime get the startup time of the underlying ec2 instance.
func (o *ASGNodeStartUpObserver) nodeLaunchTime(providerID string) (time.Time, error) {
instanceID, err := instanceIDFromProviderID(providerID)
if err != nil {
return time.Time{}, fmt.Errorf("Failed to get instanceID for node: %v", err)
}
params := &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
}
resp, err := o.ec2Client.DescribeInstances(params)
if err != nil {
return time.Time{}, fmt.Errorf("Failed to describe instance: %v", err)
}
if len(resp.Reservations) != 1 {
return time.Time{}, fmt.Errorf("Expected one reservation, got %d", len(resp.Reservations))
}
if len(resp.Reservations[0].Instances) != 1 {
return time.Time{}, fmt.Errorf("Expected one instance, got %d", len(resp.Reservations[0].Instances))
}
return aws.TimeValue(resp.Reservations[0].Instances[0].LaunchTime), nil
}
|
package setZeroes
import "testing"
func Test_setZeroes(t *testing.T) {
type args struct {
matrix [][]int
}
tests := []struct {
name string
args args
want [][]int
}{
// TODO: Add test cases.
{
name: "first",
args: args{
matrix: [][]int{
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
},
},
want: [][]int{
{1, 0, 1},
{0, 0, 0},
{1, 0, 1},
},
},
{
name: "second",
args: args{
matrix: [][]int{
{0, 1, 2, 0},
{3, 4, 5, 2},
{1, 3, 1, 5},
},
},
want: [][]int{
{0, 0, 0, 0},
{0, 4, 5, 0},
{0, 3, 1, 0},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setZeroes(tt.args.matrix)
if !isSame(tt.args.matrix, tt.want) {
t.Errorf("setZeroes() = %v, want %v", tt.args.matrix, tt.want)
}
})
}
}
func isSame(one, two [][]int) bool {
if len(one) != len(two) {
return false
}
for i := 0; i < len(one); i++ {
if len(one[i]) != len(two[i]) {
return false
}
for j := 0; j < len(one[i]); j++ {
if one[i][j] != two[i][j] {
return false
}
}
}
return true
}
|
package testing
import (
"errors"
surveypkg "github.com/devspace-cloud/devspace/pkg/util/survey"
)
// FakeSurvey is a fake survey that just returns predefined strings
type FakeSurvey struct {
nextAnswers []string
}
// NewFakeSurvey creates a new fake survey
func NewFakeSurvey() *FakeSurvey {
return &FakeSurvey{
nextAnswers: []string{},
}
}
// Question asks a question and returns a fake answer
func (f *FakeSurvey) Question(params *surveypkg.QuestionOptions) (string, error) {
if len(f.nextAnswers) != 0 {
answer := f.nextAnswers[0]
f.nextAnswers = f.nextAnswers[1:]
return answer, nil
} else if params.DefaultValue != "" {
return params.DefaultValue, nil
}
return "", errors.New("No answer to return specified")
}
// SetNextAnswer will set the next answer for the question function
func (f *FakeSurvey) SetNextAnswer(answer string) {
f.nextAnswers = append(f.nextAnswers, answer)
}
|
package http
import (
types "github.com/queueup-dev/qup-types"
)
func Delete(
client Client,
url string,
body types.PayloadWriter,
headers *Headers,
) (*Response, error) {
return Request(client, "DELETE", url, headers, body)
}
func Get(
client Client,
url string,
headers *Headers,
) (*Response, error) {
return Request(client, "GET", url, headers, nil)
}
func Head(
client Client,
url string,
headers *Headers,
) (*Response, error) {
return Request(client, "HEAD", url, headers, nil)
}
func Options(
client Client,
url string,
) (*Response, error) {
return Request(client, "OPTIONS", url, nil, nil)
}
func Patch(
client Client,
url string,
body types.PayloadWriter,
headers *Headers,
) (*Response, error) {
return Request(client, "PATCH", url, headers, body)
}
func Post(
client Client,
url string,
body types.PayloadWriter,
headers *Headers,
) (*Response, error) {
return Request(client, "POST", url, headers, body)
}
func Put(
client Client,
url string,
body types.PayloadWriter,
headers *Headers,
) (*Response, error) {
return Request(client, "PUT", url, headers, body)
}
|
package greetings
import (
"errors"
"fmt"
"math/rand"
"time"
)
// This function takes a name parameter whose type is string
// This function also returns a string
// In Go, a function that starts with a capital letter can be called by a function not in the same package (exported name)
func Hello(name string) (string, error) {
if name == "" {
return name, errors.New("empty name")
}
message := fmt.Sprintf(randomFormat(), name)
//message := fmt.Sprintf(randomFormat())
return message, nil
}
func Hellos(names []string) (map[string]string, error) {
messages := make(map[string]string)
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
messages[name] = message
}
return messages, nil
}
func init() {
rand.Seed(time.Now().UnixNano())
}
// randomFormat returns one of a set of greeting messages.
// The returned message is selected at random.
func randomFormat() string {
// A slice of message formats
formats := []string{
"Hi, %v. Welcome!",
"Halo, %v, Willkommen!",
"안녕하세요, %v, 반갑습니다!",
"你好,%v, 欢迎欢迎",
}
return formats[rand.Intn(len(formats))]
}
|
/*
Given an array A of distinct integers sorted in ascending order,
return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists.
Example 1:
Input: [-10,-5,0,3,7]
Output: 3
Explanation:
For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.
Example 2:
Input: [0,2,5,8,17]
Output: 0
Explanation:
A[0] = 0, thus the output is 0.
Example 3:
Input: [-10,-5,3,4,7,9]
Output: -1
Explanation:
There is no such i that A[i] = i, thus the output is -1.
Note:
1 <= A.length < 10^4
-10^9 <= A[i] <= 10^9
*/
package main
import (
"sort"
)
func main() {
assert(fixedpoint([]int{-10, -5, 0, 3, 7}) == 3)
assert(fixedpoint([]int{0, 2, 5, 8, 17}) == 0)
assert(fixedpoint([]int{-10, -5, 3, 4, 7, 9}) == -1)
assert(fixedpoint([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) == 0)
assert(fixedpoint([]int{0, 1, 1, 3}) == 3)
assert(fixedpoint([]int{}) == -1)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func fixedpoint(a []int) int {
n := sort.Search(len(a), func(i int) bool {
return i <= a[i]
})
if n >= len(a) || n != a[n] {
return -1
}
return n
}
|
package oidc
import (
"context"
"time"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/oauth2"
"github.com/ory/x/errorsx"
)
// ClientCredentialsGrantHandler handles access requests for the Client Credentials Flow.
type ClientCredentialsGrantHandler struct {
*oauth2.HandleHelper
Config interface {
fosite.ScopeStrategyProvider
fosite.AudienceStrategyProvider
fosite.AccessTokenLifespanProvider
}
}
// HandleTokenEndpointRequest implements https://tools.ietf.org/html/rfc6749#section-6 and the
// fosite.TokenEndpointHandler for the Client Credentials Flow.
func (c *ClientCredentialsGrantHandler) HandleTokenEndpointRequest(ctx context.Context, request fosite.AccessRequester) error {
if !c.CanHandleTokenEndpointRequest(ctx, request) {
return errorsx.WithStack(fosite.ErrUnknownRequest)
}
client := request.GetClient()
// The client MUST authenticate with the authorization server as described in Section 3.2.1.
// This requirement is already fulfilled because fosite requires all token requests to be authenticated as described
// in https://tools.ietf.org/html/rfc6749#section-3.2.1
if client.IsPublic() {
return errorsx.WithStack(fosite.ErrInvalidGrant.WithHint("The OAuth 2.0 Client is marked as public and is thus not allowed to use authorization grant 'client_credentials'."))
}
scopes := request.GetRequestedScopes()
if len(scopes) == 0 {
scopes = client.GetScopes()
}
for _, scope := range scopes {
if !c.Config.GetScopeStrategy(ctx)(client.GetScopes(), scope) {
return errorsx.WithStack(fosite.ErrInvalidScope.WithHintf("The OAuth 2.0 Client is not allowed to request scope '%s'.", scope))
}
request.GrantScope(scope)
}
if err := c.Config.GetAudienceStrategy(ctx)(client.GetAudience(), request.GetRequestedAudience()); err != nil {
return err
}
// if the client is not public, he has already been authenticated by the access request handler.
atLifespan := fosite.GetEffectiveLifespan(client, fosite.GrantTypeClientCredentials, fosite.AccessToken, c.Config.GetAccessTokenLifespan(ctx))
request.GetSession().SetExpiresAt(fosite.AccessToken, time.Now().UTC().Add(atLifespan))
return nil
}
// PopulateTokenEndpointResponse implements https://tools.ietf.org/html/rfc6749#section-4.4.3 and the
// fosite.TokenEndpointHandler for the Client Credentials Flow.
func (c *ClientCredentialsGrantHandler) PopulateTokenEndpointResponse(ctx context.Context, request fosite.AccessRequester, response fosite.AccessResponder) error {
if !c.CanHandleTokenEndpointRequest(ctx, request) {
return errorsx.WithStack(fosite.ErrUnknownRequest)
}
// TODO: remove?
if !request.GetClient().GetGrantTypes().Has("client_credentials") {
return errorsx.WithStack(fosite.ErrUnauthorizedClient.WithHint("The OAuth 2.0 Client is not allowed to use authorization grant 'client_credentials'."))
}
atLifespan := fosite.GetEffectiveLifespan(request.GetClient(), fosite.GrantTypeClientCredentials, fosite.AccessToken, c.Config.GetAccessTokenLifespan(ctx))
return c.IssueAccessToken(ctx, atLifespan, request, response)
}
// CanSkipClientAuth implements the fosite.TokenEndpointHandler for the Client Credentials Flow.
func (c *ClientCredentialsGrantHandler) CanSkipClientAuth(ctx context.Context, requester fosite.AccessRequester) bool {
return false
}
// CanHandleTokenEndpointRequest implements the fosite.TokenEndpointHandler for the Client Credentials Flow.
func (c *ClientCredentialsGrantHandler) CanHandleTokenEndpointRequest(ctx context.Context, requester fosite.AccessRequester) bool {
// grant_type REQUIRED.
// Value MUST be set to "client_credentials".
return requester.GetGrantTypes().ExactOne(GrantTypeClientCredentials)
}
var (
_ fosite.TokenEndpointHandler = (*ClientCredentialsGrantHandler)(nil)
)
|
// Package utils Common Strcutres, Constants etc that are being used in other packages
package utils
import (
"time"
"github.com/chaincode/demo-network/pkg/core/status"
"github.com/s7techlab/cckit/router"
)
// MetaData Strcuture: Contains the common fields which are used in all other Structures
type MetaData struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
DocType string `json:"doc_type"`
}
// ResponseID is used to return the response which contains only one ID field
type ResponseID struct {
ID string `json:"id"`
}
// ResponseIDs is used to return the response which contains only one ID field
type ResponseIDs struct {
IDs []string `json:"ids"`
}
// ResponseMessage is used to return the response which contains only one message field
type ResponseMessage struct {
Message string `json:"message"`
}
// Constants DocTypes the document which are stored inside the couchdb
const (
DocTypeUser string = "users" // For users
DocTypeAsset string = "assets" // For assets
DocTypeTransaction string = "transactions" // For transactions
DocTypeAddressBook string = "address_book" // For address_book
WalletCoinSymbol string = "ABTC" // Symbol for Wallet Coins
AssetTxnType string = "asset" // To define asset related transactions
CoinTxnType string = "coin" // To define coin related transactions
AssetCreatedTxn string = "asset_created" // To define asset_created related transactions
AssetTransferredTxn string = "asset_transferred" // To define asset_transferred related transactions
Send int32 = 1 // Flag to define send transaction
Receive int32 = 2 // Flag to define receive transaction
AddAssetFee int64 = 880 // Defined fee to add asset
TransferAssetFee int64 = 3 // Defined fee to transfer asset
)
// Get Finds the record by ID
func Get(c router.Context, query string, message string) ([]byte, string, error) {
stub := c.Stub()
// excecute the query
resultsIterator, err := stub.GetQueryResult(query)
// check if the query executed successfully?
if err != nil {
return nil, "", status.ErrInternal.WithError(err)
}
defer resultsIterator.Close()
// query has returned the results?
if !resultsIterator.HasNext() {
return nil, "", status.ErrNotFound.WithMessage(message)
}
// fetch the data and marshal it into struct
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, "", status.ErrInternal.WithError(err)
}
return queryResponse.Value, queryResponse.Key, nil
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Code generated from the elasticsearch-specification DO NOT EDIT.
// https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2
package types
import (
"bytes"
"encoding/json"
"errors"
"io"
"strconv"
)
// AutoFollowPatternSummary type.
//
// https://github.com/elastic/elasticsearch-specification/blob/33e8a1c9cad22a5946ac735c4fba31af2da2cec2/specification/ccr/get_auto_follow_pattern/types.ts#L28-L52
type AutoFollowPatternSummary struct {
Active bool `json:"active"`
// FollowIndexPattern The name of follower index.
FollowIndexPattern *string `json:"follow_index_pattern,omitempty"`
// LeaderIndexExclusionPatterns An array of simple index patterns that can be used to exclude indices from
// being auto-followed.
LeaderIndexExclusionPatterns []string `json:"leader_index_exclusion_patterns"`
// LeaderIndexPatterns An array of simple index patterns to match against indices in the remote
// cluster specified by the remote_cluster field.
LeaderIndexPatterns []string `json:"leader_index_patterns"`
// MaxOutstandingReadRequests The maximum number of outstanding reads requests from the remote cluster.
MaxOutstandingReadRequests int `json:"max_outstanding_read_requests"`
// RemoteCluster The remote cluster containing the leader indices to match against.
RemoteCluster string `json:"remote_cluster"`
}
func (s *AutoFollowPatternSummary) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
for {
t, err := dec.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
switch t {
case "active":
var tmp interface{}
dec.Decode(&tmp)
switch v := tmp.(type) {
case string:
value, err := strconv.ParseBool(v)
if err != nil {
return err
}
s.Active = value
case bool:
s.Active = v
}
case "follow_index_pattern":
if err := dec.Decode(&s.FollowIndexPattern); err != nil {
return err
}
case "leader_index_exclusion_patterns":
if err := dec.Decode(&s.LeaderIndexExclusionPatterns); err != nil {
return err
}
case "leader_index_patterns":
if err := dec.Decode(&s.LeaderIndexPatterns); err != nil {
return err
}
case "max_outstanding_read_requests":
var tmp interface{}
dec.Decode(&tmp)
switch v := tmp.(type) {
case string:
value, err := strconv.Atoi(v)
if err != nil {
return err
}
s.MaxOutstandingReadRequests = value
case float64:
f := int(v)
s.MaxOutstandingReadRequests = f
}
case "remote_cluster":
var tmp json.RawMessage
if err := dec.Decode(&tmp); err != nil {
return err
}
o := string(tmp[:])
o, err = strconv.Unquote(o)
if err != nil {
o = string(tmp[:])
}
s.RemoteCluster = o
}
}
return nil
}
// NewAutoFollowPatternSummary returns a AutoFollowPatternSummary.
func NewAutoFollowPatternSummary() *AutoFollowPatternSummary {
r := &AutoFollowPatternSummary{}
return r
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//257. Binary Tree Paths
//Given a binary tree, return all root-to-leaf paths.
//For example, given the following binary tree:
// 1
// / \
//2 3
// \
// 5
//All root-to-leaf paths are:
//["1->2->5", "1->3"]
//Credits:
//Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
///**
// * Definition for a binary tree node.
// * type TreeNode struct {
// * Val int
// * Left *TreeNode
// * Right *TreeNode
// * }
// */
//func binaryTreePaths(root *TreeNode) []string {
//}
// Time Is Money
|
package main
import (
"fmt"
"github.com/mombe090/utils/mongo_utils"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"log"
)
const (
databaseName = "test"
collectionName = "test-mongo_utils-go-driver"
)
type Test struct {
ID string `json:"id" bson:"_id"`
Name string `json:"name"`
}
func testInsertOne() {
res, err := mongo_utils.InsertOne(databaseName, collectionName, Test{Name: "test"})
if err != nil {
panic(err)
}
fmt.Sprintf(res)
}
func testInsertMany() {
var testData []interface{}
testData = append(testData, Test{Name: "Test 1"})
testData = append(testData, Test{Name: "Test 2"})
testData = append(testData, Test{Name: "Test 3"})
res, err := mongo_utils.InsertMany(databaseName, collectionName, testData)
if err != nil {
panic(err)
}
fmt.Println(res)
}
func testFindOne() {
ojb, err := primitive.ObjectIDFromHex("5e572453425958c7c44e1143")
_ = mongo_utils.FindOne(databaseName, collectionName, bson.M{"_id": ojb })
if err != nil {
panic(err)
}
}
func testFindMany() {
curr, ctx, err := mongo_utils.FindMany(databaseName, collectionName, Test{Name: "Test 1"})
if err != nil {
panic(err)
}
for curr.Next(*ctx) {
var resTmp map[string]interface{}
err := curr.Decode(&resTmp)
if err != nil {
log.Print(err)
}
fmt.Println(resTmp["_id"])
}
//log.Println("Finds", resultats)
}
func testUpdateOne() {
err := mongo_utils.UpdateOne(databaseName, collectionName,
bson.D{
{
"name", "test",
},
},
bson.D{
{"$set", bson.D{
{
"name", "tesssdfdsdfdsfdsfdst",
},
},
},
})
if err != nil {
panic(err)
}
}
func testUpdateMany() {
err := mongo_utils.UpdateOne(databaseName, collectionName,
bson.D{
{
"name", "tesssdfdsdfdsfdsfdst",
},
},
bson.D{
{"$set", bson.D{
{
"name", "MoneyDoing",
},
},
},
})
if err != nil {
panic(err)
}
}
func testDeleteOne() {
err := mongo_utils.DeleteOne(
databaseName,
collectionName,
bson.D{
{
"name", "MoneyDoing",
},
})
if err != nil {
panic(err)
}
}
func testDeleteMany() {
err := mongo_utils.DeleteMany(
databaseName,
collectionName,
bson.D{
{
"name", "test",
},
})
if err != nil {
panic(err)
}
}
func main() {
//testInsertOne()
//testInsertMany()
//testFindMany()
testFindOne()
//testUpdateMany()
//testDeleteOne()
//testDeleteMany()
}
|
// CookieJar - A contestant's algorithm toolbox
// Copyright (c) 2013 Peter Szilagyi. All rights reserved.
//
// CookieJar is dual licensed: use of this source code is governed by a BSD
// license that can be found in the LICENSE file. Alternatively, the CookieJar
// toolbox may be used in accordance with the terms and conditions contained
// in a signed written agreement between you and the author(s).
// Package set implements simple present/not data structure supporting arbitrary
// types (even a mixture).
//
// Internally it uses a simple map assigning zero-byte struct{}s to keys.
package set
// Set data structure.
type Set struct {
data map[interface{}]struct{}
}
// Creates a new empty set.
func New() *Set {
return &Set{make(map[interface{}]struct{})}
}
// Inserts an element into the set.
func (s *Set) Insert(val interface{}) {
s.data[val] = struct{}{}
}
// Removes an element from the set. If none was present, nothing is done.
func (s *Set) Remove(val interface{}) {
delete(s.data, val)
}
// Returns the number of elements in the set.
func (s *Set) Size() int {
return len(s.data)
}
// Checks whether an element is inside the set.
func (s *Set) Exists(val interface{}) bool {
_, ok := s.data[val]
return ok
}
// Executes a function for every element in the set.
func (s *Set) Do(f func(interface{})) {
for val, _ := range s.data {
f(val)
}
}
// Clears the contents of a set.
func (s *Set) Reset() {
*s = *New()
}
|
package tests
import (
mock "HttpBigFilesServer/MainApplication/test/mock_postgres"
"github.com/stretchr/testify/assert"
"testing"
)
func TestGet(t *testing.T) {
db, r := mock.MockFileDB()
query := mock.MockFile(db)
query.On("Where", "id=?", mock.FileInfoTest.Id).Return(query)
query.On("Select").Return(nil)
answerCorrect, err := r.Get(mock.FileInfoTest.Id)
assert.Nil(t, err)
assert.Equal(t, mock.FileInfoTest, answerCorrect)
}
func TestSave(t *testing.T) {
db, r := mock.MockFileDB()
query := mock.MockFile(db)
mockRes := mock.MockResult{}
query.On("Insert").Return(mockRes, nil)
err := r.Save(mock.FileInfoTest)
assert.Nil(t, err)
}
|
package main
import (
"os"
"github.com/jinmukeji/jiujiantang-services/jinmuid/config"
handler "github.com/jinmukeji/jiujiantang-services/jinmuid/handler"
"github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb"
jinmuMysql "github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb"
logger "github.com/jinmukeji/jiujiantang-services/pkg/rpc"
dbutilmysql "github.com/jinmukeji/plat-pkg/v2/dbutil/mysql"
storemysql "github.com/jinmukeji/plat-pkg/v2/store/mysql"
corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
semProto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/sem/v1"
smsProto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/sms/v1"
subscriptionpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1"
jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/micro/cli/v2"
micro "github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/client"
)
const (
rpcSmsServiceName = "com.himalife.srv.svc-sms-gw"
rpcSemServiceName = "com.himalife.srv.svc-sem-gw"
rpcServiceName = "com.himalife.srv.svc-jinmuid"
rpcBizServiceName = "com.himalife.srv.svc-biz-core"
subscriptionServiceName = "com.himalife.srv.svc-subscription"
)
func main() {
versionMeta := config.NewVersionMetadata()
// Create a new service. Optionally include some options here.
authenticationWrapper := new(handler.AuthenticationWrapper)
service := micro.NewService(
// Service Basic Info
micro.Name(config.FullServiceName()),
micro.Version(config.ProductVersion),
// Fault Tolerance - Heartbeating
// See also: https://micro.mu/docs/fault-tolerance.html#heartbeating
micro.RegisterTTL(config.DefaultRegisterTTL),
micro.RegisterInterval(config.DefaultRegisterInterval),
// Setup wrappers
micro.WrapHandler(logger.LogWrapper, authenticationWrapper.HandleWrapper()),
// // Setup runtime flags
dbClientOptions(), encryptKeyOptions(),
// Setup --version flag
defaultVersionFlags(),
// Setup metadata
micro.Metadata(versionMeta),
)
// optionally setup command line usage
service.Init(
micro.Action(func(c *cli.Context) error {
if c.Bool("version") {
config.PrintFullVersionInfo()
os.Exit(0)
}
return nil
}),
)
log.Infof("Starting service: %s", config.FullServiceName())
log.Infof("Product Version: %s", config.ProductVersion)
log.Infof("Git SHA: %s", config.GitSHA)
log.Infof("Git Branch: %s", config.GitBranch)
log.Infof("Go Version: %s", config.GoVersion)
log.Infof("Build Version: %s", config.BuildVersion)
log.Infof("Build Time: %s", config.BuildTime)
// Register handler
server := service.Server()
db, err := newDbClient()
if err != nil {
log.Panicf("Failed to connect to MySQL instance at %s. Error: %v", dbAddress, err)
}
log.Infoln("Connected to MySQL instance at", dbAddress)
authenticationWrapper.SetDataStore(db)
smsSvc := smsProto.NewSmsAPIService(rpcSmsServiceName, client.DefaultClient)
semSvc := semProto.NewSemAPIService(rpcSemServiceName, client.DefaultClient)
rpcUserManagerSvc := jinmuidpb.NewUserManagerAPIService(rpcServiceName, client.DefaultClient)
bizSvc := corepb.NewXimaAPIService(rpcBizServiceName, client.DefaultClient)
subscriptionSvc := subscriptionpb.NewSubscriptionManagerAPIService(subscriptionServiceName, client.DefaultClient)
jinmuIDService := handler.NewJinmuIDService(db, smsSvc, semSvc, rpcUserManagerSvc, bizSvc, subscriptionSvc, encryptKey)
if err := jinmuidpb.RegisterUserManagerAPIHandler(server, jinmuIDService); err != nil {
log.Fatalln(err)
}
// Run the server
if err := service.Run(); err != nil {
log.Fatalln(err)
}
}
// 数据库和邮件服务器连接信息
var (
dbAddress string
dbUsername string
dbPassword string
dbDatabase string
dbEnableLog = false
dbMaxConns = 1
)
func defaultVersionFlags() micro.Option {
return micro.Flags(
&cli.BoolFlag{
Name: "version",
Usage: "Show version information",
},
)
}
// dbClientOptions 构建命令行启动参数
func dbClientOptions() micro.Option {
return micro.Flags(
&cli.StringFlag{
Name: "x_db_address",
Value: "localhost:3306",
Usage: "MySQL instance `ADDRESS` - [host]:[port]",
EnvVars: []string{"X_DB_ADDRESS"},
Destination: &dbAddress,
},
&cli.StringFlag{
Name: "x_db_username",
Usage: "MySQL login `USERNAME`",
EnvVars: []string{"X_DB_USERNAME"},
Destination: &dbUsername,
},
&cli.StringFlag{
Name: "x_db_password",
Usage: "MySQL login `PASSWORD`",
EnvVars: []string{"X_DB_PASSWORD"},
Destination: &dbPassword,
},
&cli.StringFlag{
Name: "x_db_database",
Usage: "MySQL database name",
EnvVars: []string{"X_DB_DATABASE"},
Destination: &dbDatabase,
},
&cli.BoolFlag{
Name: "x_db_enable_log",
Usage: "Enable MySQL client log",
EnvVars: []string{"X_DB_ENABLE_LOG"},
Destination: &dbEnableLog,
},
&cli.IntFlag{
Name: "x_db_max_connections",
Usage: "Max connections of MySQL client",
EnvVars: []string{"X_DB_MAX_CONNECTIONS"},
Value: 1,
Destination: &dbMaxConns,
},
)
}
// newDbClient 创建一个 DbClient
func newDbClient() (*jinmuMysql.DbClient, error) {
cfg := dbutilmysql.NewConfig()
cfg.User = dbUsername
cfg.Passwd = dbPassword
cfg.Net = "tcp"
cfg.Addr = dbAddress
cfg.DBName = dbDatabase
db, err := dbutilmysql.OpenGormDB(
dbutilmysql.WithMySQLConfig(cfg),
)
if err != nil {
return nil, err
}
return mysqldb.NewDbClient(*storemysql.NewStore(db))
}
var encryptKey string
func encryptKeyOptions() micro.Option {
return micro.Flags(
&cli.StringFlag{
Name: "x_encrypt_key",
Value: "",
Usage: "加密的key",
EnvVars: []string{"X_ENCRYPT_KEY"},
Destination: &encryptKey,
},
)
}
|
package hash
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/gob"
"fmt"
"hash"
"io"
)
var (
gobFormat bool = false
)
func SetGobFormat(flag bool) {
gobFormat = flag
}
func New(name string) hash.Hash {
switch name {
case "md5":
return md5.New()
case "sha1":
return sha1.New()
case "sha256":
return sha256.New()
case "sha512":
return sha512.New()
}
return nil
}
func Write(h hash.Hash, args ...interface{}) (int, error) {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
for _, arg := range args {
switch result := arg.(type) {
case string:
if _, err := b.WriteString(result); nil != err {
return 0, err
}
case []byte:
if _, err := b.Write(result); nil != err {
return 0, err
}
case byte:
if err := b.WriteByte(result); nil != err {
return 0, err
}
default:
if r, ok := arg.(io.Reader); ok {
var buffer [1024]byte
io.CopyBuffer(&b, r, buffer[:])
} else if data, ok := arg.(interface {
Bytes() []byte
}); ok {
if _, err := b.Write(data.Bytes()); nil != err {
return 0, err
}
} else {
if gobFormat {
if err := enc.Encode(arg); nil != err {
return 0, err
}
} else {
if _, err := b.WriteString(fmt.Sprint(arg)); nil != err {
return 0, err
}
}
}
}
}
if 0 < b.Len() {
return h.Write(b.Bytes())
}
return 0, fmt.Errorf("empty write")
}
func WriteString(h hash.Hash, args ...string) {
if nil != h {
for _, item := range args {
io.WriteString(h, item)
}
}
}
func SumString(h hash.Hash) string {
return fmt.Sprintf("%x", h.Sum(nil))
}
func HashToBytes(name string, args ...interface{}) []byte {
if h := New(name); nil != h {
Write(h, args...)
return h.Sum(nil)[:]
}
return nil
}
func HashToString(name string, args ...interface{}) string {
if h := New(name); nil != h {
Write(h, args...)
return SumString(h)
}
return ""
}
|
package piscine
func AlphaCount(str string) int {
var count int = 0
for _, chars := range str {
if (chars >= 'A' && chars <= 'Z') || (chars >= 'a' && chars <= 'z') {
count++
}
}
return count
}
|
package main
import "fmt"
// https://leetcode-cn.com/problems/powx-n/
func myPow(x float64, n int) float64 {
if n == 0 {
return 1.0
}
if n < 0 {
return myPow(1.0/x, -n)
}
if n == 1 {
return x
}
i, res := 1, x
for ; i*2 <= n; i *= 2 {
res *= res
}
return res * myPow(x, n-i)
}
func main() {
cases := [][]int{
{2, 3},
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(myPow(float64(c[0]), c[1]))
}
}
|
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
io_prometheus_client "github.com/prometheus/client_model/go"
)
//SagaTimeoutCounter is the prometheus counter counting timed out saga instances
var SagaTimeoutCounter = newSagaTimeoutCounter()
//GetSagaTimeoutCounterValue gets the counter value of timed out sagas reported to prometheus
func GetSagaTimeoutCounterValue() (float64, error) {
m := &io_prometheus_client.Metric{}
err := SagaTimeoutCounter.Write(m)
if err != nil {
return 0, err
}
return m.GetCounter().GetValue(), nil
}
func newSagaTimeoutCounter() prometheus.Counter {
return promauto.NewCounter(prometheus.CounterOpts{
Namespace: grabbitPrefix,
Subsystem: "saga",
Name: "timedout_sagas",
Help: "counting the number of timedout saga instances",
})
}
|
package leetcode
// In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.
// You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.
func findPoisonedDuration(timeSeries []int, duration int) int {
l := len(timeSeries)
if l == 0 {
return 0
}
total := duration
for i := 0; i < l-1; i++ {
dif := timeSeries[i+1] - timeSeries[i]
if dif < duration {
total += dif
} else {
total += duration
}
}
return total
}
|
// handlers.go
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
func GetAllHandler(w http.ResponseWriter, r *http.Request) {
u := new(User)
users, err := u.GetAllUsers()
if err != nil {
http.Error(w, err.Error(), http.StatusFound)
return
}
j, err := json.Marshal(users)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "aplication/json")
w.Write(j)
}
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
http.Error(w, "Query id is required", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Query id must be a number", http.StatusBadRequest)
return
}
u := new(User)
user, err := u.GetUser(id)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
j, err := json.Marshal(user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = user.CreateUser()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
// Notes
func CreateNoteHandler(w http.ResponseWriter, r *http.Request) {
var note Note
err := json.NewDecoder(r.Body).Decode(¬e)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
err = note.CreateNote()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func GetUserNotesHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
http.Error(w, "Query id is required", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Query id must be a number", http.StatusBadRequest)
return
}
n := new(Note)
note, err := n.GetNote(id)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
j, err := json.Marshal(note)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
// List
func ListPostRequest(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var list List
err := decoder.Decode(&list)
if err != nil {
fmt.Fprintf(w, "error: %v", err)
return
}
list.order()
response, err := list.ToJson()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
|
package leetcode
func GenerateParenthesis(n int) []string {
res := make([]string, 0, 2*n)
if n == 0 {
return []string{}
}
if n == 1 {
return []string{"()"}
}
add("(", n, n, "", &res)
return res
}
func add(op string, remainLeft int, remainRight int, path string, res *[]string) {
if op == "(" {
remainLeft -= 1
} else {
remainRight -= 1
}
if remainLeft > remainRight {
return
}
path += op
if remainLeft > 0 {
add("(", remainLeft, remainRight, path, res)
}
if remainRight > 0 {
add(")", remainLeft, remainRight, path, res)
}
if remainLeft == 0 && remainRight == 0 {
*res = append(*res, path)
return
}
}
|
package main
import (
"net/http"
"fmt"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/hello/{name}", handleSayHello).Methods("GET")
http.ListenAndServe(":8080", router)
}
func handleSayHello(rw http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
msg := fmt.Sprint("Hello ", vars["name"])
fmt.Fprint(rw, msg)
}
|
package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"strings"
)
type UUID []byte
func (uuid UUID) String() string {
if uuid == nil || len(uuid) != 16 {
return ""
}
b := []byte(uuid)
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func NewRandom() UUID {
uuid := make([]byte, 16)
randomBits([]byte(uuid))
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid
}
func Parse(s string) UUID {
if len(s) == 36+9 {
if strings.ToLower(s[:9]) != "urn:uuid:" {
return nil
}
s = s[9:]
} else if len(s) != 36 {
return nil
}
if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
return nil
}
uuid := make([]byte, 16)
for i, x := range []int{
0, 2, 4, 6,
9, 11,
14, 16,
19, 21,
24, 26, 28, 30, 32, 34} {
if v, ok := xtob(s[x:]); !ok {
return nil
} else {
uuid[i] = v
}
}
return uuid
}
func randomBits(b []byte) {
if _, err := io.ReadFull(rander, b); err != nil {
panic(err.Error()) // rand should never fail
}
}
// xvalues returns the value of a byte as a hexadecimal digit or 255.
var xvalues = []byte{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
}
// xtob converts the the first two hex bytes of x into a byte.
func xtob(x string) (byte, bool) {
b1 := xvalues[x[0]]
b2 := xvalues[x[1]]
return (b1 << 4) | b2, b1 != 255 && b2 != 255
}
var rander = rand.Reader // random function
func (uuid UUID) MarshalJSON() ([]byte, error) {
return json.Marshal(uuid.String())
}
func (uuid *UUID) UnmarshalJSON(in []byte) error {
var str string
err := json.Unmarshal(in, &str)
if err != nil {
return err
}
*uuid = (*uuid)[:0]
id := Parse(str)
if id != nil {
*uuid = append(*uuid, id...)
} else {
// return an error here
}
return nil
}
func main() {
id := NewRandom()
fmt.Println("First ID:", id)
b, err := json.Marshal(id)
if err != nil {
panic(err)
}
fmt.Println("JSON:", string(b))
var newId UUID
err = json.Unmarshal(b, &newId)
if err != nil {
panic(err)
}
fmt.Println("Second ID:", newId)
}
|
package models
type Auth struct {
ID int `gorm:"primary_key" json:"id"`
PubDesc int `json:"pub_desc"`
Username string `json:"username"`
Password string `json:"password"`
}
func CheckAuth(username string, password string) (authResult *Auth, ok bool) {
var auth Auth
db.Select("id, pub_desc").Where(Auth{Username: username, Password: password}).First(&auth)
return &auth, auth.ID > 0
}
|
package main
import (
"fmt"
observer2 "github.com/NGunthor/go_test/pkg/patterns/observer"
)
func main() {
pub := observer2.NewPublisher()
a := observer2.NewObserverA(10)
pub.Attach(a)
pub.Attach(observer2.NewObserverB(20))
pub.Notify()
pub.Attach(observer2.NewObserverB(30))
pub.Notify()
pub.Show()
fmt.Println("============", a)
pub.Unpin(a)
pub.Notify()
pub.Show()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.