text
stringlengths
11
4.05M
package max func maxDepth(s string) int { var m, k int for _, c := range s { switch c { case '(': k++ if k > m { m = k } case ')': k-- } } return m }
package main import "sort" //1584. 连接所有点的最小费用 //给你一个points数组,表示 2D 平面上的一些点,其中points[i] = [xi, yi]。 // //连接点[xi, yi] 和点[xj, yj]的费用为它们之间的 曼哈顿距离:|xi - xj| + |yi - yj|,其中|val|表示val的绝对值。 // //请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有一条简单路径时,才认为所有点都已连接。 // //示例 2: // //输入:points = [[3,12],[-2,5],[-4,1]] //输出:18 //示例 3: // //输入:points = [[0,0],[1,1],[1,0],[-1,1]] //输出:4 //示例 4: // //输入:points = [[-1000000,-1000000],[1000000,1000000]] //输出:4000000 //示例 5: // //输入:points = [[0,0]] //输出:0 // // //提示: // //1 <= points.length <= 1000 //-106<= xi, yi <= 106 //所有点(xi, yi)两两不同。 //思路 Kruskal算法 ,并查集 // Kruskal算法是最小生成树的经典算法 // Kruskal算法是从小到大加入边的贪心算法 func minCostConnectPoints(points [][]int) int { edges := make([]edge, 0) n := len(points) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { edges = append(edges, edge{ x: i, y: j, cost: abs(points[i][0]-points[j][0]) + abs(points[i][1]-points[j][1]), }) } } sort.Slice(edges, func(i, j int) bool { return edges[i].cost < edges[j].cost }) parent := make([]int, n) count := make([]int, n) for i := range parent { parent[i] = i count[i] = 1 } var find func(x int) int find = func(x int) int { if parent[x] != x { parent[x] = find(parent[x]) } return parent[x] } union := func(from, to int) bool { from, to = find(from), find(to) if from == to { return false } if count[from] > count[to] { from, to = to, from } count[to] += count[from] parent[from] = to return true } var result int for _, v := range edges { if union(v.x, v.y) { result += v.cost } } return result } type edge struct { x, y int cost int }
package controllers import ( "encoding/json" "io" "io/ioutil" "log" "net/http" "atlas-api/config/schema" "atlas-api/db" "atlas-api/helpers" ) // AuthenticatePostData will hold the email and password of the request // that was sent up by the clientf type AuthenticatePostData struct { Email string Password string } // Authenticate - POST // Will accept an Email and Password. Query the database for Email // and grab salt and hash from user in the database with the same // Email. It will then hash the requested password with the existing // salt and compare the two. func Authenticate(rw http.ResponseWriter, req *http.Request) { var ( data AuthenticatePostData user schema.User userID int ) body, err := ioutil.ReadAll(io.LimitReader(req.Body, 1048576)) if err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } err = req.Body.Close() if err != nil { return } if err = json.Unmarshal(body, &data); err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } database, err := db.Connection() if err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } rows, err := database.Query("SELECT * FROM users WHERE email=$1", data.Email) if err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } defer rows.Close() for rows.Next() { err := rows.Scan(&userID, &user.FirstName, &user.LastName, &user.Email, &user.PasswordHash, &user.PasswordSalt, &user.Disabled) if err != nil { log.Fatal(err) } } err = database.Close() if err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } if err = helper.Compare(data.Password, user); err != nil { helper.CreateResponse(rw, req, 500, nil, err) return } helper.CreateResponse(rw, req, 500, user, err) }
package SaleProvider type ISale interface { GetId() string GetItemName() string GetItemDescription() string GetAmountGross() float32 IsAuthorized() bool UpdateSaleAsAuthorizedCompleted(payfastPaymentId string, amountFee, amountNet float32) UpdateSaleAsFailed(payfastPaymentId string) UpdateSaleAsPending(payfastPaymentId string) }
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use // of this source code is governed by the MIT license that can be found in // the LICENSE file. package girc import ( "encoding/base64" "fmt" ) // SASLMech is an representation of what a SASL mechanism should support. // See SASLExternal and SASLPlain for implementations of this. type SASLMech interface { // Method returns the uppercase version of the SASL mechanism name. Method() string // Encode returns the response that the SASL mechanism wants to use. If // the returned string is empty (e.g. the mechanism gives up), the handler // will attempt to panic, as expectation is that if SASL authentication // fails, the client will disconnect. Encode(params []string) (output string) } // SASLExternal implements the "EXTERNAL" SASL type. type SASLExternal struct { // Identity is an optional field which allows the client to specify // pre-authentication identification. This means that EXTERNAL will // supply this in the initial response. This usually isn't needed (e.g. // CertFP). Identity string `json:"identity"` } // Method identifies what type of SASL this implements. func (sasl *SASLExternal) Method() string { return "EXTERNAL" } // Encode for external SALS authentication should really only return a "+", // unless the user has specified pre-authentication or identification data. // See https://tools.ietf.org/html/rfc4422#appendix-A for more info. func (sasl *SASLExternal) Encode(params []string) string { if len(params) != 1 || params[0] != "+" { return "" } if sasl.Identity != "" { return sasl.Identity } return "+" } // SASLPlain contains the user and password needed for PLAIN SASL authentication. type SASLPlain struct { User string `json:"user"` // User is the username for SASL. Pass string `json:"pass"` // Pass is the password for SASL. } // Method identifies what type of SASL this implements. func (sasl *SASLPlain) Method() string { return "PLAIN" } // Encode encodes the plain user+password into a SASL PLAIN implementation. // See https://tools.ietf.org/rfc/rfc4422.txt for more info. func (sasl *SASLPlain) Encode(params []string) string { if len(params) != 1 || params[0] != "+" { return "" } in := []byte(sasl.User) in = append(in, 0x0) in = append(in, []byte(sasl.User)...) in = append(in, 0x0) in = append(in, []byte(sasl.Pass)...) return base64.StdEncoding.EncodeToString(in) } const saslChunkSize = 400 func handleSASL(c *Client, e Event) { if e.Command == RPL_SASLSUCCESS || e.Command == ERR_SASLALREADY { // Let the server know that we're done. c.write(&Event{Command: CAP, Params: []string{CAP_END}}) return } // Assume they want us to handle sending auth. auth := c.Config.SASL.Encode(e.Params) if auth == "" { // Assume the SASL authentication method doesn't want to respond for // some reason. The SASL spec and IRCv3 spec do not define a clear // way to abort a SASL exchange, other than to disconnect, or proceed // with CAP END. c.receive(&Event{Command: ERROR, Params: []string{ fmt.Sprintf("closing connection: SASL %s failed: %s", c.Config.SASL.Method(), e.Last()), }}) return } // Send in "saslChunkSize"-length byte chunks. If the last chuck is // exactly "saslChunkSize" bytes, send a "AUTHENTICATE +" 0-byte // acknowledgement response to let the server know that we're done. for { if len(auth) > saslChunkSize { c.write(&Event{Command: AUTHENTICATE, Params: []string{auth[0 : saslChunkSize-1]}, Sensitive: true}) auth = auth[saslChunkSize:] continue } if len(auth) <= saslChunkSize { c.write(&Event{Command: AUTHENTICATE, Params: []string{auth}, Sensitive: true}) if len(auth) == 400 { c.write(&Event{Command: AUTHENTICATE, Params: []string{"+"}}) } break } } } func handleSASLError(c *Client, e Event) { if c.Config.SASL == nil { c.write(&Event{Command: CAP, Params: []string{CAP_END}}) return } // Authentication failed. The SASL spec and IRCv3 spec do not define a // clear way to abort a SASL exchange, other than to disconnect, or // proceed with CAP END. c.receive(&Event{Command: ERROR, Params: []string{"closing connection: " + e.Last()}}) }
package main import "fmt" type avpair_type int type avpairs map[avpair_type] [][]byte func (a avpairs) Add(key avpair_type, value []byte) { a[key] = append(a[key], value) } func (a avpairs) rc_pack_avpair_list(b []byte) { for curr_type, avpair_data := range a{ /* TLV Format (type = 1 byte, length = 1byte, value= attribute size) */ for _, curr_valuepair := range avpair_data { size := 1 + 1 + len(curr_valuepair) b[0] = byte(curr_type) b[1] = byte(size) copy(b[2:], curr_valuepair) fmt.Println("bytes:", b) // move forward buffer b = b[size:] } } } func (a avpairs) rc_avpair_size() int{ for curr_type, avpair_data := range a{ /* TLV Format (type = 1 byte, length = 1byte, value= attribute size) */ for _, curr_valuepair := range avpair_data { size := 1 + 1 + len(curr_valuepair) } } return size } func sample_main() { av := avpairs{} username := []byte("test") av.Add(1,username) password := []byte("test123") av.Add(2, password) b:= make([]byte, 1024) av.rc_pack_avpair_list(b) fmt.Println("b:", b) }
package main import ( "io" "bytes" "net/http" "golang.org/x/net/html" ) type Fetcher interface { // Fetch returns the body of a url and a slice of urls on that page Fetch(url string) (body string, urls []string, err error) } type SimpleFetcher struct { } func (f SimpleFetcher) Fetch(url string) (body string, urls []string, err error) { resp, err := http.Get(url) if err != nil { return "", nil, err } defer resp.Body.Close() z := html.NewTokenizer(resp.Body) // ongoing buffer write, instead of string appends // idea suggested by // http://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go var bodyb *bytes.Buffer // looking for the opening <body>, so ignoring links in <head> for tt, tagname := z.Next(), "" ; tagname != "body"; tt = z.Next() { if tt == html.ErrorToken { return bodyb.String(), urls, z.Err() } if tt == html.StartTagToken { bodyb = bytes.NewBuffer(z.Raw()) tn, _ := z.TagName() tagname = string(tn) if err != nil { return bodyb.String(), urls, err } } } for { tt := z.Next() switch tt { case html.ErrorToken: // z.Next() returns io.EOF, not really error // so no need to scare the caller if err = z.Err(); err == io.EOF { return bodyb.String(), urls, nil } else { return bodyb.String(), urls, err } break; case html.EndTagToken: // if <html> isn't in body, than </html> shouldn't be either // also, if we find </body>, that's a good time to stop if tn, _ := z.TagName(); string(tn) == "html" { return bodyb.String(), urls, err } else { bodyb.Write(z.Raw()) if string(tn) == "body" { return bodyb.String(), urls, err } } break; case html.StartTagToken: // TODO: javascript links, like onclick redirects // TODO: filter out links to non-text (images, videos, etc) // TODO: cut script tags out of body return? nobody wants to analyze that tn, hasa := z.TagName() if hasa && len(tn) == 1 && tn[0] == 'a' { tak, tav, hasa := z.TagAttr() // walk through tag attributes until we get a href for string(tak) != "href" && hasa { tak, tav, hasa = z.TagAttr() } if string(tak) == "href" { if bytes.Compare(tav[:7], []byte("http://")) == 0 || bytes.Compare(tav[:8], []byte("https://")) == 0 { urls = append(urls, string(tav)) } } } default: bodyb.Write(z.Raw()) } } }
// Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. package Vault import ( "math/big" "strings" ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" ) // Reference imports to suppress errors if they are not otherwise used. var ( _ = big.NewInt _ = strings.NewReader _ = ethereum.NotFound _ = abi.U256 _ = bind.Bind _ = common.Big1 _ = types.BloomLookup _ = event.NewSubscription ) // VaultABI is the input ABI used to generate the binding from. const VaultABI = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"ipfsHash\",\"type\":\"string\"}],\"name\":\"Added\",\"type\":\"event\"},{\"constant\":false,\"inputs\":[{\"name\":\"_ipfsHash\",\"type\":\"string\"}],\"name\":\"add\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" // Vault is an auto generated Go binding around an Ethereum contract. type Vault struct { VaultCaller // Read-only binding to the contract VaultTransactor // Write-only binding to the contract VaultFilterer // Log filterer for contract events } // VaultCaller is an auto generated read-only Go binding around an Ethereum contract. type VaultCaller struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } // VaultTransactor is an auto generated write-only Go binding around an Ethereum contract. type VaultTransactor struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } // VaultFilterer is an auto generated log filtering Go binding around an Ethereum contract events. type VaultFilterer struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } // VaultSession is an auto generated Go binding around an Ethereum contract, // with pre-set call and transact options. type VaultSession struct { Contract *Vault // Generic contract binding to set the session for CallOpts bind.CallOpts // Call options to use throughout this session TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session } // VaultCallerSession is an auto generated read-only Go binding around an Ethereum contract, // with pre-set call options. type VaultCallerSession struct { Contract *VaultCaller // Generic contract caller binding to set the session for CallOpts bind.CallOpts // Call options to use throughout this session } // VaultTransactorSession is an auto generated write-only Go binding around an Ethereum contract, // with pre-set transact options. type VaultTransactorSession struct { Contract *VaultTransactor // Generic contract transactor binding to set the session for TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session } // VaultRaw is an auto generated low-level Go binding around an Ethereum contract. type VaultRaw struct { Contract *Vault // Generic contract binding to access the raw methods on } // VaultCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. type VaultCallerRaw struct { Contract *VaultCaller // Generic read-only contract binding to access the raw methods on } // VaultTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. type VaultTransactorRaw struct { Contract *VaultTransactor // Generic write-only contract binding to access the raw methods on } // NewVault creates a new instance of Vault, bound to a specific deployed contract. func NewVault(address common.Address, backend bind.ContractBackend) (*Vault, error) { contract, err := bindVault(address, backend, backend, backend) if err != nil { return nil, err } return &Vault{VaultCaller: VaultCaller{contract: contract}, VaultTransactor: VaultTransactor{contract: contract}, VaultFilterer: VaultFilterer{contract: contract}}, nil } // NewVaultCaller creates a new read-only instance of Vault, bound to a specific deployed contract. func NewVaultCaller(address common.Address, caller bind.ContractCaller) (*VaultCaller, error) { contract, err := bindVault(address, caller, nil, nil) if err != nil { return nil, err } return &VaultCaller{contract: contract}, nil } // NewVaultTransactor creates a new write-only instance of Vault, bound to a specific deployed contract. func NewVaultTransactor(address common.Address, transactor bind.ContractTransactor) (*VaultTransactor, error) { contract, err := bindVault(address, nil, transactor, nil) if err != nil { return nil, err } return &VaultTransactor{contract: contract}, nil } // NewVaultFilterer creates a new log filterer instance of Vault, bound to a specific deployed contract. func NewVaultFilterer(address common.Address, filterer bind.ContractFilterer) (*VaultFilterer, error) { contract, err := bindVault(address, nil, nil, filterer) if err != nil { return nil, err } return &VaultFilterer{contract: contract}, nil } // bindVault binds a generic wrapper to an already deployed contract. func bindVault(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(VaultABI)) if err != nil { return nil, err } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil } // Call invokes the (constant) contract method with params as input values and // sets the output to result. The result type might be a single field for simple // returns, a slice of interfaces for anonymous returns and a struct for named // returns. func (_Vault *VaultRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { return _Vault.Contract.VaultCaller.contract.Call(opts, result, method, params...) } // Transfer initiates a plain transaction to move funds to the contract, calling // its default method if one is available. func (_Vault *VaultRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { return _Vault.Contract.VaultTransactor.contract.Transfer(opts) } // Transact invokes the (paid) contract method with params as input values. func (_Vault *VaultRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { return _Vault.Contract.VaultTransactor.contract.Transact(opts, method, params...) } // Call invokes the (constant) contract method with params as input values and // sets the output to result. The result type might be a single field for simple // returns, a slice of interfaces for anonymous returns and a struct for named // returns. func (_Vault *VaultCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { return _Vault.Contract.contract.Call(opts, result, method, params...) } // Transfer initiates a plain transaction to move funds to the contract, calling // its default method if one is available. func (_Vault *VaultTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { return _Vault.Contract.contract.Transfer(opts) } // Transact invokes the (paid) contract method with params as input values. func (_Vault *VaultTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { return _Vault.Contract.contract.Transact(opts, method, params...) } // Get is a free data retrieval call binding the contract method 0x6d4ce63c. // // Solidity: function get() constant returns(string) func (_Vault *VaultCaller) Get(opts *bind.CallOpts) (string, error) { var ( ret0 = new(string) ) out := ret0 err := _Vault.contract.Call(opts, out, "get") return *ret0, err } // Get is a free data retrieval call binding the contract method 0x6d4ce63c. // // Solidity: function get() constant returns(string) func (_Vault *VaultSession) Get() (string, error) { return _Vault.Contract.Get(&_Vault.CallOpts) } // Get is a free data retrieval call binding the contract method 0x6d4ce63c. // // Solidity: function get() constant returns(string) func (_Vault *VaultCallerSession) Get() (string, error) { return _Vault.Contract.Get(&_Vault.CallOpts) } // Add is a paid mutator transaction binding the contract method 0xb0c8f9dc. // // Solidity: function add(string _ipfsHash) returns() func (_Vault *VaultTransactor) Add(opts *bind.TransactOpts, _ipfsHash string) (*types.Transaction, error) { return _Vault.contract.Transact(opts, "add", _ipfsHash) } // Add is a paid mutator transaction binding the contract method 0xb0c8f9dc. // // Solidity: function add(string _ipfsHash) returns() func (_Vault *VaultSession) Add(_ipfsHash string) (*types.Transaction, error) { return _Vault.Contract.Add(&_Vault.TransactOpts, _ipfsHash) } // Add is a paid mutator transaction binding the contract method 0xb0c8f9dc. // // Solidity: function add(string _ipfsHash) returns() func (_Vault *VaultTransactorSession) Add(_ipfsHash string) (*types.Transaction, error) { return _Vault.Contract.Add(&_Vault.TransactOpts, _ipfsHash) } // VaultAddedIterator is returned from FilterAdded and is used to iterate over the raw logs and unpacked data for Added events raised by the Vault contract. type VaultAddedIterator struct { Event *VaultAdded // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data logs chan types.Log // Log channel receiving the found contract events sub ethereum.Subscription // Subscription for errors, completion and termination done bool // Whether the subscription completed delivering logs fail error // Occurred error to stop iteration } // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. func (it *VaultAddedIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false } // If the iterator completed, deliver directly whatever's available if it.done { select { case log := <-it.logs: it.Event = new(VaultAdded) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false } it.Event.Raw = log return true default: return false } } // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: it.Event = new(VaultAdded) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false } it.Event.Raw = log return true case err := <-it.sub.Err(): it.done = true it.fail = err return it.Next() } } // Error returns any retrieval or parsing error occurred during filtering. func (it *VaultAddedIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. func (it *VaultAddedIterator) Close() error { it.sub.Unsubscribe() return nil } // VaultAdded represents a Added event raised by the Vault contract. type VaultAdded struct { IpfsHash string Raw types.Log // Blockchain specific contextual infos } // FilterAdded is a free log retrieval operation binding the contract event 0x844e4fccb87d6d1843733397bf5d41ce3551716260f6e90263dbbed3bda32f4f. // // Solidity: event Added(string ipfsHash) func (_Vault *VaultFilterer) FilterAdded(opts *bind.FilterOpts) (*VaultAddedIterator, error) { logs, sub, err := _Vault.contract.FilterLogs(opts, "Added") if err != nil { return nil, err } return &VaultAddedIterator{contract: _Vault.contract, event: "Added", logs: logs, sub: sub}, nil } // WatchAdded is a free log subscription operation binding the contract event 0x844e4fccb87d6d1843733397bf5d41ce3551716260f6e90263dbbed3bda32f4f. // // Solidity: event Added(string ipfsHash) func (_Vault *VaultFilterer) WatchAdded(opts *bind.WatchOpts, sink chan<- *VaultAdded) (event.Subscription, error) { logs, sub, err := _Vault.contract.WatchLogs(opts, "Added") if err != nil { return nil, err } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe() for { select { case log := <-logs: // New log arrived, parse the event and forward to the user event := new(VaultAdded) if err := _Vault.contract.UnpackLog(event, "Added", log); err != nil { return err } event.Raw = log select { case sink <- event: case err := <-sub.Err(): return err case <-quit: return nil } case err := <-sub.Err(): return err case <-quit: return nil } } }), nil } // ParseAdded is a log parse operation binding the contract event 0x844e4fccb87d6d1843733397bf5d41ce3551716260f6e90263dbbed3bda32f4f. // // Solidity: event Added(string ipfsHash) func (_Vault *VaultFilterer) ParseAdded(log types.Log) (*VaultAdded, error) { event := new(VaultAdded) if err := _Vault.contract.UnpackLog(event, "Added", log); err != nil { return nil, err } return event, nil }
package tgo var RpcURL = "http://192.168.1.241:8732"
package data type Filter int const ( // FilterLt represents strictly Less than FilterLt Filter = iota // FilterLe represents Less than or equal FilterLe // FilterEq represents equal FilterEq // FilterGe represent greater than or equal FilterGe // FilterGt represents strictly greater than FilterGt )
package clingon import ( "fmt" "github.com/scottferg/Go-SDL/sdl" "github.com/scottferg/Go-SDL/ttf" "testing" ) var ( appSurface *sdl.Surface sdlrenderer *SDLRenderer ) func initSDL() { if sdl.Init(sdl.INIT_VIDEO) != 0 { panic(sdl.GetError()) } if ttf.Init() != 0 { panic(sdl.GetError()) } font := ttf.OpenFont("testdata/VeraMono.ttf", 20) if font == nil { panic(sdl.GetError()) } appSurface = sdl.SetVideoMode(640, 480, 32, 0) sdlrenderer = NewSDLRenderer(sdl.CreateRGBSurface(sdl.SRCALPHA, 640, 480, 32, 0, 0, 0, 0), font) sdlrenderer.GetSurface().SetAlpha(sdl.SRCALPHA, 0xaa) console = NewConsole(nil) go func() { for { select { case rects := <-sdlrenderer.UpdatedRectsCh(): render(rects) } } }() render(nil) } func render(updatedRects []sdl.Rect) { if updatedRects == nil { appSurface.Flip() } else { for _, r := range updatedRects { appSurface.Blit(&r, sdlrenderer.GetSurface(), &r) appSurface.UpdateRect(int32(r.X), int32(r.Y), uint32(r.W), uint32(r.H)) } } } func BenchmarkRenderConsoleBlended(b *testing.B) { b.StopTimer() initSDL() var strings []string = make([]string, 0) for i := 0; i < 1000; i++ { strings = append(strings, fmt.Sprintf("Line %d %s", i, "The quick brown fox jumps over the lazy dog")) } console.appendLines(strings) sdlrenderer.Blended = true b.StartTimer() for i := 0; i < b.N; i++ { sdlrenderer.renderConsole(console) sdlrenderer.render(nil) } } func BenchmarkRenderConsoleSolid(b *testing.B) { b.StopTimer() initSDL() var strings []string = make([]string, 0) for i := 0; i < 1000; i++ { strings = append(strings, fmt.Sprintf("Line %d %s", i, "The quick brown fox jumps over the lazy dog")) } console.appendLines(strings) b.StartTimer() for i := 0; i < b.N; i++ { sdlrenderer.renderConsole(console) sdlrenderer.render(nil) } }
package main import "./greeting" import "fmt" func RenameToFrog(r greeting.Renamable) { r.Rename("Frog") } func main() { //var s = greeting.Salutation{"Bob", "Hello"} salutations := greeting.Salutations{ {"Bob", "Hello"}, {"Joe", "Hi"}, {"Mary", "What is up?"}, } //salutations[0].Rename("John") //RenameToFrog(&salutations[0]) fmt.Fprintf(&salutations[0], "The count is %d", 10) salutations.Greet(greeting.CreatePrintFunction("?"), true, 6) //greeting.Greet(slice, greeting.CreatePrintFunction("?"), true, 5) }
package prime import "math" func isPrime(x int) bool { if x == 2 { return true } for i := 2; i <= int(math.Sqrt(float64(x))); i++ { if x%i == 0 { return false } } return true } // Nth returns n-th prime number. func Nth(n int) (int, bool) { if n <= 0 { return 0, false } var i int for i = 2; n > 0; i++ { if isPrime(i) { n-- } } return i - 1, true }
package rpcclient import ( "context" "fmt" "kto/rpcclient/message" "kto/transaction" "kto/types" "kto/until" "testing" "time" "google.golang.org/grpc" ) var ctx context.Context var client message.GreeterClient func init() { from := types.BytesToAddress([]byte("CNtyeiE8RkTy26ufueMnvvbkEJ5qQL7tjD8Su5BP8PLY")) to := types.BytesToAddress([]byte("HRBfv2SA5BBiweBShPMbDYFfr6kKwyk9c9pxpD481fMc")) fromPri := until.Decode("ziNi4JJCU29sWRFUVyeTZRkhbZetNd39wGaEbMikGTg2y3EjASoafN1ArnTMqk1AovGTVUT8o8RdBRPSTNa162Y") tx := transaction.New() tx = tx.NewTransaction(uint64(1), 200000, from, to, "") tx = tx.SignTx(fromPri) _, err := tx.SendTransaction() if err != nil { fmt.Println(err) } conn, err := grpc.Dial("106.13.188.227:8545", grpc.WithInsecure(), grpc.WithBlock()) if err != nil { fmt.Println("fail to dail:", err) return } client = message.NewGreeterClient(conn) ctx = context.Background() } func TestSetLockBalance(t *testing.T) { time.Sleep(5 * time.Second) var reqData = &message.ReqLockBalance{Address: "CNtyeiE8RkTy26ufueMnvvbkEJ5qQL7tjD8Su5BP8PLY", Amount: uint64(10000)} respdata, err := client.SetLockBalance(ctx, reqData) if err != nil { t.Error("fail to set lcok:", err) } t.Log(respdata.Status) } func TestSetUnlockBalance(t *testing.T) { var reqData = &message.ReqUnlockBalance{Address: "CNtyeiE8RkTy26ufueMnvvbkEJ5qQL7tjD8Su5BP8PLY", Amount: uint64(5000)} respdata, err := client.SetUnlockBalance(ctx, reqData) if err != nil { t.Error("fail to set unlock:", err) } t.Log(respdata.Status) } func TestGetBalance(t *testing.T) { _, err := client.GetBalance(context.Background(), &message.ReqBalance{Address: "Kto3fwLDibEp5Ggx51A9fJ2h5KAJvargAA31JWae7D6PPbj"}) if err != nil { t.Errorf("failed,error:%v", err) return } //t.Log("balance:", respdata.Balnce) }
package v1 import ( "fmt" "github.com/gin-gonic/gin" "github.com/mihail-1212/todo-project-backend/internal/service" "github.com/mihail-1212/todo-project-backend/pkg/auth" "github.com/mihail-1212/todo-project-backend/pkg/auth/models" "github.com/mihail-1212/todo-project-backend/pkg/domain" "github.com/mihail-1212/todo-project-backend/pkg/logger" ) var log, _ = logger.NewLoggerDev() const ( authorizationHeader = "Authorization" userCtx = "currentUser" ) type Handler struct { services *service.Services authorizer *auth.Authorizer } func NewHandler(services *service.Services, authorizer *auth.Authorizer) *Handler { return &Handler{ services: services, authorizer: authorizer, } } func (h *Handler) Init(api *gin.RouterGroup) { v1 := api.Group("/v1") { h.initTaskRoutes(v1) h.initAuthRoutes(v1) } } func (h *Handler) getCurrentUser(c *gin.Context) (*domain.User, error) { userInterface, isUserFound := c.Get(userCtx) if !isUserFound { return nil, UserContextIsEmptyError{"User context was not found! User is not auth."} } user, _ := userInterface.(*domain.User) return user, nil } func (h *Handler) SignIn(login, password string) (string, error) { user := models.User{ Username: login, Password: password, } return h.authorizer.SignInReturnToken(&user) } type UserContextIsEmptyError struct { Message string } func (e UserContextIsEmptyError) Error() string { return fmt.Sprintf("%s", e.Message) }
package lc // Time: O(n) // Benchmark: 12ms 5.8mb | 90% 78% func maxArea(height []int) int { var current, max int l, r := 0, len(height)-1 for l < r { if height[l] < height[r] { current = height[l] * (r - l) l++ } else { current = height[r] * (r - l) r-- } if current > max { max = current } } return max }
func removeElement(nums []int, val int) int { cur := 0 right := 0 for right < len(nums) { if nums[right] != val { nums[cur] = nums[right] cur++ } right++ } return cur }
package appointments import ( "Scheduler/models/db" "errors" "fmt" "log" mathRand "math/rand" "time" ) type Appointment struct { ID int UserID int StartTime time.Time EndTime time.Time Date time.Time Active bool } var Appointments []Appointment func GetAppointments(date time.Time) (err error) { fmt.Println("Fuck!") rows, err := db.Conn.Query(`SELECT id, userid, starttime, endtime, date, active FROM appointments WHERE date = ?`, string(date.Year())+"-"+string(date.Month())+"-"+string(date.Day())) if err != nil { log.Println(err.Error()) return } defer rows.Close() for rows.Next() { fmt.Println("rows") var appointment Appointment err = rows.Scan(&appointment.ID, &appointment.UserID, &appointment.StartTime, &appointment.EndTime, &appointment.Date, &appointment.Active) if err != nil { log.Println(err.Error()) return } fmt.Println(appointment.ID, appointment.StartTime, appointment.Date, appointment.Active) } if err = rows.Err(); err != nil { log.Println(err.Error()) return } return } func CheckGeneratedIDExits(ID int) (err error) { var ExistingID int stmt, err := db.Conn.Prepare(`SELECT id FROM appointments WHERE id=?`) if err != nil { err = errors.New("ea1001") return } defer stmt.Close() err = stmt.QueryRow(ID).Scan(&ExistingID) if err != nil { err = errors.New("ea1002") return } err = errors.New("ea1003") return } func GenerateAppointmentID() (ID int, err error) { min := 100000000 max := 999999999 mathRand.Seed(time.Now().UnixNano()) for { ID = mathRand.Intn(max-min+1) + min err = CheckGeneratedIDExits(ID) if err.Error() == "ea1001" { return } if err.Error() == "ea1002" { log.Println("Generated user ID:", ID) break } } return }
package main import ( "fmt" "time" "regexp" "strings" d "github.com/bwmarrin/discordgo" r "gopkg.in/rethinkdb/rethinkdb-go.v6" ) func botRefresh(state State) { ticker := time.NewTicker(1 * time.Hour) for _ = range ticker.C { for _, bot := range state.GetBots() { state.ValidateBotToken(bot) } } } func channelRefresh(state State) { ticker := time.NewTicker(1 * time.Hour) for _ = range ticker.C { for _, channel := range state.GetChannels() { state.ValidateChannelToken(channel) } } } func spotifyRefresh(state State) { ticker := time.NewTicker(1 * time.Hour) for ; true; <- ticker.C { for _, channel := range state.GetChannels() { state.SpotifyRefresh(channel) } } } func viewerbotRefresh(state State) { ticker := time.NewTicker(1 * time.Hour) for ; true; <- ticker.C { state.RefreshViewerBots() } } func updateWatchtimes(state State) { ticker := time.NewTicker(1 * time.Minute) for _ = range ticker.C { for _, channel := range state.GetChannels() { cbot, err := state.GetChannelBot(channel) if err != nil { Logger(state, "ERROR", err.Error(), channel.Name, "updateWatchtimes") } else { if cbot.Enabled && channel.Enabled && channel.Live { c := Channel{ Name: "global" } data, _ := state.GetBData(channel, "channel:viewerstats") bots, _ := state.GetASData(c, "viewerbots") if data.Value { if client, ok := state.Clients[channel.Bot]; ok { usernames, err := client.Userlist(channel.Name) if err == nil { for _, username := range usernames { if username != channel.Name && username != channel.Bot { bot := false for _, name := range bots.Value { if name == username { bot = true } } if !bot { state.UpdateWatchtime(channel, username) } } } } } } } } } } } func auth(state State) { ticker := time.NewTicker(60 * time.Second) for _ = range ticker.C { for _, channel := range state.GetChannels() { bot, err := state.GetChannelBot(channel) if err != nil { Logger(state, "ERROR", err.Error(), channel.Name, "auth") } else { if bot.Enabled && channel.Enabled && !channel.Auth { if client, ok := state.Clients[bot.Name]; ok { client.Depart(channel.Name) client.Join(channel.Name) } } } } } } func live(state State) { ticker := time.NewTicker(60 * time.Second) for _ = range ticker.C { s, err := state.GetKrakenStreams() // TODO: will need to incorporate pagination at 100+ bots if err == nil { channels := state.GetChannels() for _, channel := range channels { bot, err := state.GetChannelBot(channel) if err != nil { Logger(state, "ERROR", err.Error(), channel.Name, "live") } else { var data KrakenStream online := false for _, stream := range s.Streams { if channel.Name == stream.Channel.Name { online = true data = stream } } if online && !channel.Live && channel.Enabled && bot.Enabled { state.SetLive(channel, online) state.DiscordAnnounce(channel, data) state.UpdatePUBGID(channel) } else if !online && channel.Live { state.SetLive(channel, online) state.ResetPUBGStats(channel) state.ResetNotices(channel) } } } } } } func notices(state State) { ticker := time.NewTicker(30 * time.Second) for _ = range ticker.C { for _, channel := range state.GetChannels() { bot, err := state.GetChannelBot(channel) if err != nil { Logger(state, "ERROR", err.Error(), channel.Name, "notices") } else { if bot.Enabled && channel.Enabled && channel.Auth && channel.Live { state.UpdateNoticeCountdowns(channel) group, err := state.GetReadyNoticeGroup(channel) if err == nil { command, err := state.GetCommand(channel, group.Commands[0]) if err == nil { if client, ok := state.Clients[channel.Bot]; ok { go state.ParseTwitchCommand(channel, command, client, "", "") } else { Logger(state, "ERROR", `client not found`, bot.Name, "notices") } } state.RotateNotices(channel, group) } } } } } } func commercials(state State) { ticker := time.NewTicker(10 * time.Minute) for _ = range ticker.C { for _, channel := range state.GetChannels() { bot, err := state.GetChannelBot(channel) if err != nil { Logger(state, "ERROR", err.Error(), channel.Name, "commercials") } else { if bot.Enabled && channel.Enabled && channel.Live && channel.Auth { hourly, err := state.GetIData(channel, "commercials:hourly") if err == nil { count, err := state.GetHourlyCommercials(channel) if (err == nil || err == r.ErrEmptyResult) && count < hourly.Value { remaining := hourly.Value - count err = state.KrakenRunCommercials(channel, remaining) if client, ok := state.Clients[channel.Bot]; ok && err == nil { client.Say(channel.Name, fmt.Sprintf(`%d commercials have been run`, remaining)) notice, err := state.GetSData(channel, "commercials:notice") if err == nil { command, err := state.GetCommand(channel, notice.Value) if err == nil { go state.ParseTwitchCommand(channel, command, client, "", "") } } submode, _ := state.GetBData(channel, "commercials:submode") if submode.Value { client.Say(channel.Name, "/subscribers") go state.SayAfter(channel, "/subscribersoff", remaining * 30) } } else { Logger(state, "ERROR", `client not found`, bot.Name, "commercials") } } } } } } } } func pubg(state State) { ticker := time.NewTicker(60 * time.Second) for _ = range ticker.C { for _, channel := range state.GetChannels() { if channel.Live { _, err := state.GetSData(channel, "pubg:id") if err == nil { player, err := state.PUBGPlayer(channel) if err == nil { var firstImport time.Time stats, _ := state.GetPUBGStats(channel) for _, data := range player.Data.Relationships.Matches.Data { match, err := state.PUBGMatch(channel, data.ID) if err != nil { break } else { match_created, err := time.Parse(time.RFC3339, match.Data.Attributes.CreatedAt) if err != nil { break } else { if stats.Cursor.IsZero() { state.UpdatePUBGCursor(channel, match_created) break } else { if match_created.After(stats.Cursor) { match_stats, err := state.GetPUBGMatchStats(channel, match) if err == nil { state.UpdatePUBGStats(channel, match_stats) } if firstImport.IsZero() { firstImport = match_created } } else { if !firstImport.IsZero() { state.UpdatePUBGCursor(channel, firstImport) } break } } } } } } } } } } } func discord(state State) { for { for _, channel := range state.GetChannels() { if _, ok := state.Discord[channel.Name]; !ok { token, err := state.GetSData(channel, "discord:token") if err == nil { dclient, err := d.New(fmt.Sprintf(`Bot %s`, token.Value)) if err != nil { state.AddNotification(channel, "error", "discord_api_failure", "Discord api failure", "Make sure your discord:token setting is up to date.") } else { dclient.AddHandler(dMessageCreate(state, channel)) dclient.Identify.Intents = d.MakeIntent(d.IntentsGuildMessages) err = dclient.Open() if err == nil { state.Discord[channel.Name] = dclient defer dclient.Close() } } } } } time.Sleep(1 * time.Minute) } } func dMessageCreate(state State, channel Channel) func(s *d.Session, m *d.MessageCreate) { return func(s *d.Session, m *d.MessageCreate) { if m.Author.ID == s.State.User.ID { return } modChan, err := state.GetSData(channel, "discord:mod-channel") if m.ChannelID == modChan.Value { if client, ok := state.Clients[channel.Bot]; ok { aliases := state.GetAliases(channel) for _, alias := range aliases { if strings.Split(m.Content, " ")[0] == alias.Name { m.Content = strings.Replace(m.Content, alias.Name, alias.Command, 1) break } } regex := regexp.MustCompile(`<:(\w+):\d+>`) matches := regex.FindAllStringSubmatch(m.Content, -1) for _, match := range matches { m.Content = strings.ReplaceAll(m.Content, match[0], match[1]) } for _, command := range native_commands { if strings.Split(m.Content, " ")[0] == fmt.Sprintf(`%s%s`, state.GetPrefix(channel), command.Name) { args := strings.Split(m.Content, " ")[1:] go command.Func(state, client, channel, args) return } } } } command, err := state.GetCommand(channel, strings.Split(m.Content, " ")[0]) if err == nil { go state.ParseDiscordCommand(channel, command, s, m) } } }
/* package xmodel provides a post-compiled representation of the scripts. It is used internally by the compiler, and has been superseded by sashimi/compiler/model. ( It should probably be assumed to be internally consistent. ) The table version of things would also build,merge into this same code. The script callbacks currently must always be re-compiled. The idea is that they could be extracted somehow via the ast, and perhaps recompiled as ( And if not, probably not the end of the world -- new data could still be merged into the model from tables, the original scripts just couldnt be serialized out to non-go files. ) */ package xmodel
package thorchain import ( "fmt" "testing" . "gopkg.in/check.v1" "github.com/zlyzol/xchaingo/common" ) /* func TestHttpGet(t *testing.T) { address := "tthor1fs5jqvwp9u05802vfsru8zndmq5ucanrw8gg96" c := NewHttpClient("https://testnet.thornode.thorchain.info") _, _, err := c.Get("/bank/balances/" + string(address)) assert.NoError(t, err, "NewHttpClient") } */ //func TestSetParameters(t *testing.T) { // Hook up gocheck into the "go test" runner. func TestAll(t *testing.T) { TestingT(t) } type TestSuite struct{} var _ = Suite(&TestSuite{}) func (s *TestSuite) TestSetParameters(c *C) { t, err := NewThorchainClient(testnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") c.Assert(err, IsNil) c.Log("NewThorchainClient OK") x := t.GetXChainClient() x.SetNetwork(mainnet) c.Check(x.GetNetwork(), Equals, mainnet) x.SetNetwork(testnet) c.Check(x.GetNetwork(), Equals, testnet) c.Log("SetNetwork OK") c.Check(x.GetExplorerUrl(), Equals, "https://viewblock.io/thorchain") x.SetNetwork(testnet) a := "tthor1249ujrfl6pnhzxarwhqxpfu3k53hrndax2xs59" c.Check(x.GetExplorerAddressUrl(a), Equals, "https://viewblock.io/thorchain/address/"+a+"?network=testnet") tx := "D820AD9F3C1580EF8DD5DEB0909DC33520EF6793DA59EFCD666C6A5E8E6CA1DA" c.Check(x.GetExplorerTxUrl(tx), Equals, "https://viewblock.io/thorchain/tx/"+tx+"?network=testnet") c.Log("GetExplorerUrl & co OK") c.Check(x.GetFees(nil), Equals, defaultFees) } func (s *TestSuite) TestValidateAddress(c *C) { t, err := NewThorchainClient(testnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") c.Assert(err, IsNil) x := t.GetXChainClient() a := common.Address("tthor1249ujrfl6pnhzxarwhqxpfu3k53hrndax2xs59") c.Check(x.ValidateAddress(a), Equals, true) } func (s *TestSuite) TestGetTestnetAddress(c *C) { t, err := NewThorchainClient(testnet, "penalty guard brown luxury move bar wrong hero trick update grow bitter") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() address1, err := x.SetPhrase("flip portion grant body mad mountain infant edit pig execute tired ridge") c.Assert(err, IsNil) address2, err := x.GetAddress() c.Assert(err, IsNil) c.Check(string(address1), Equals, "tthor1249ujrfl6pnhzxarwhqxpfu3k53hrndax2xs59") c.Check(string(address1), Equals, string(address2)) } func (s *TestSuite) TestGetMainnetAddress(c *C) { t, err := NewThorchainClient(mainnet, "penalty guard brown luxury move bar wrong hero trick update grow bitter") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() address1, err := x.SetPhrase("flip portion grant body mad mountain infant edit pig execute tired ridge") c.Assert(err, IsNil) address2, err := x.GetAddress() c.Assert(err, IsNil) c.Check(string(address1), Equals, "thor1249ujrfl6pnhzxarwhqxpfu3k53hrndazahqdq") c.Check(string(address1), Equals, string(address2)) } func (s *TestSuite) TestGetMainnetBalance(c *C) { t, err := NewThorchainClient(mainnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() address, err := x.GetAddress() c.Assert(err, IsNil) balances, err := x.GetBalance(address, nil) c.Assert(err, IsNil) c.Log(fmt.Sprintf("Mainnet balances: %+v", balances)) c.Assert(len(balances) > 0, Equals, true) c.Check(balances[0].Asset.String(), Equals, common.RuneAsset().String()) c.Check(balances[0].Amount.String(), Equals, common.NewUintFromFloat(1).String()) } func (s *TestSuite) TestGetTestnetBalance(c *C) { t, err := NewThorchainClient(testnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() address, err := x.GetAddress() c.Assert(err, IsNil) balances, err := x.GetBalance(address, nil) c.Assert(err, IsNil) c.Log(fmt.Sprintf("Testnet balances: %+v", balances)) c.Assert(len(balances) > 0, Equals, true) c.Check(balances[0].Asset.String(), Equals, common.RuneAsset().String()) } func (s *TestSuite) xTestTransfer(c *C) { t, err := NewThorchainClient(testnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() params := common.TxParams{ Asset: AssetRune, Amount: common.NewUintFromFloat(0.1), Recipient: "tthor1fnzhjcnqn33fahdywf7t5azcapjry83r3h5j3g", } hash, err := x.Transfer(params) c.Assert(err, IsNil) c.Assert(len(hash) > 0, Equals, true) } func (s *TestSuite) TestPurgeClient(c *C) { t, err := NewThorchainClient(testnet, "flip portion grant body mad mountain infant edit pig execute tired ridge") // random passphrase c.Assert(err, IsNil) x := t.GetXChainClient() params := common.TxParams{ Asset: AssetRune, Amount: common.NewUintFromFloat(0.1), Recipient: "tthor1fnzhjcnqn33fahdywf7t5azcapjry83r3h5j3g", } x.PurgeClient() _, err = x.Transfer(params) c.Assert(err, NotNil) }
package util import ( "fmt" apps "k8s.io/api/apps/v1beta1" "k8s.io/api/core/v1" "k8s.io/api/extensions/v1beta1" "k8s.io/client-go/kubernetes/scheme" "kolihub.io/koli/pkg/spec" ) // StatefulSetDeepCopy creates a deep-copy from a StatefulSet // https://github.com/kubernetes/kubernetes/blob/master/docs/devel/controllers.md func StatefulSetDeepCopy(petset *apps.StatefulSet) (*apps.StatefulSet, error) { objCopy, err := scheme.Scheme.DeepCopy(petset) if err != nil { return nil, err } copied, ok := objCopy.(*apps.StatefulSet) if !ok { return nil, fmt.Errorf("expected StatefulSet, got %#v", objCopy) } return copied, nil } // NamespaceDeepCopy creates a deep-copy from a Namespace func NamespaceDeepCopy(ns *v1.Namespace) (*v1.Namespace, error) { objCopy, err := scheme.Scheme.DeepCopy(ns) if err != nil { return nil, err } copied, ok := objCopy.(*v1.Namespace) if !ok { return nil, fmt.Errorf("expected Namespace, got %#v", objCopy) } return copied, nil } // DeploymentDeepCopy creates a deep-copy from the specified resource func DeploymentDeepCopy(d *v1beta1.Deployment) (*v1beta1.Deployment, error) { objCopy, err := scheme.Scheme.DeepCopy(d) if err != nil { return nil, err } copied, ok := objCopy.(*v1beta1.Deployment) if !ok { return nil, fmt.Errorf("expected Deployment, got %#v", objCopy) } return copied, nil } // ServicePlanDeepCopy creates a deep-copy from the specified resource func ServicePlanDeepCopy(sp *spec.Plan) (*spec.Plan, error) { objCopy, err := scheme.Scheme.DeepCopy(sp) if err != nil { return nil, err } copied, ok := objCopy.(*spec.Plan) if !ok { return nil, fmt.Errorf("expected Service Plan, got %#v", objCopy) } return copied, nil } // ReleaseDeepCopy creates a deep-copy from the specified resource func ReleaseDeepCopy(r *spec.Release) (*spec.Release, error) { objCopy, err := scheme.Scheme.DeepCopy(r) if err != nil { return nil, err } copied, ok := objCopy.(*spec.Release) if !ok { return nil, fmt.Errorf("expected Release, got %#v", objCopy) } return copied, nil }
package parallel import ( "fmt" "math/rand" "sync" ) var count int var rw sync.RWMutex func Read(n int, ch chan struct{}) { rw.RLock() fmt.Printf("goroutine %d 进入读操作...\n", n) v := count fmt.Printf("goroutine %d 读取结束,值为:%d\n", n, v) rw.RUnlock() ch <- struct{}{} } func Write(n int, ch chan struct{}) { rw.Lock() fmt.Printf("goroutine %d 进入写操作...\n", n) v := rand.Intn(1000) count = v fmt.Printf("goroutine %d 写入结束,新值为:%d\n", n, v) rw.Unlock() ch <- struct{}{} }
package main import "fmt" // ********************************************* // when using channels in function parameters, // you can specify if a channel is meant to only // send or receive values. // ********************************************* // ping function only accept a channel for sending values. // this increases type-safety func ping(pings chan<- string, msg string) { pings <- msg } // pong function accepts one channel for receives (pings) // and a second for sends (pongs) func pong(pings <-chan string, pongs chan<- string) { msg := <-pings pongs <- msg } func main() { pings := make(chan string, 1) pongs := make(chan string, 1) ping(pings, "message passed") pong(pings, pongs) fmt.Println(<-pongs) }
/* * @lc app=leetcode id=204 lang=golang * * [204] Count Primes * * https://leetcode.com/problems/count-primes/description/ * * algorithms * Easy (31.23%) * Likes: 2064 * Dislikes: 619 * Total Accepted: 366.6K * Total Submissions: 1.2M * Testcase Example: '10' * * Count the number of prime numbers less than a non-negative number, n. * * Example: * * * Input: 10 * Output: 4 * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. * * */ // 10000 // @lc code=start func countPrimes(n int) int { return countPrimes2(n) } func countPrimes2(n int) int { if n < 2 { return 0 } // line array overmatch map // hash := make(map[int]bool, n) hash := make([]bool, n) for i := 2; i < n; i++ { hash[i] = true } for i := 2; i*i < n; i++ { if hash[i] { for j := 2 * i; j < n; j += i { hash[j] = false } } } count := 0 for i := 2; i < n; i++ { if hash[i] { count++ } } return count } // time limit exceeded: 499979 func countPrimes1(n int) int { hash := map[int]bool{} for i := 2; i < n; i++ { hash[i] = true } count := 0 for i := 2; i < n; i++ { if isPrime1(i) { count++ } } return count } func isPrime1(n int) bool { for i := 2; i < n; i++ { if n%i == 0 { return false } } return true } // @lc code=end
package steps_test import ( "testing" "github.com/joshuacrass/online-upgrade/steps" "github.com/joshuacrass/online-upgrade/testutil" "github.com/joshuacrass/online-upgrade/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestRestoreRedundancy test redundancy was able to be restored func TestRestoreRedundancy(t *testing.T) { // Build test cluster defer testutil.ClusterHA(t)() // Create a testing database require.Nil(t, util.ConnectToMemSQL(util.ParseFlags())) defer testutil.CreateDatabase(t, "online")() defer testutil.CreateDatabase(t, "upgrade")() // Run restore redundancy on all user databases t.Run("RestoreRedundancy", func(t *testing.T) { err := steps.RestoreRedundancy() assert.Nil(t, err) }) // Run rebalance partitions on all user databases t.Run("RebalancePartitions", func(t *testing.T) { err := steps.RebalancePartitions() assert.Nil(t, err) }) }
package vue_test import ( "testing" sitter "github.com/kiteco/go-tree-sitter" "github.com/kiteco/go-tree-sitter/vue" "github.com/stretchr/testify/assert" ) func TestGrammar(t *testing.T) { assert := assert.New(t) parser := sitter.NewParser() parser.SetLanguage(vue.GetLanguage()) sourceCode := []byte(` <template> <div class="split"></div> </template> <script> export default { name: 'split' } </script>`) tree := parser.Parse(sourceCode) assert.Equal( "(component (template_element (start_tag (tag_name)) (text) (element (start_tag (tag_name) (attribute (attribute_name) (quoted_attribute_value (attribute_value)))) (end_tag (tag_name))) (text) (end_tag (tag_name))) (script_element (start_tag (tag_name)) (raw_text) (end_tag (tag_name))))", tree.RootNode().String(), ) }
// Copyright © 2017 @telecoda // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" "os" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/telecoda/pico-go/console" "github.com/telecoda/pico-go/generate" ) func er(err interface{}) { msg := fmt.Sprintf("Error: %s\n", err) color.Red(msg) os.Exit(-1) } var projectName string var consoleType string // newCmd represents the new command var newCmd = &cobra.Command{ Use: "new", Short: "Create a new pico-go project", Long: `This command will create a new pico-go game project in the current directory. Run the command in an empty directory into your $GOPATH Where you want the initial project code to be generated.append eg. $GOPATH/src/github.com/<your-github-profile>/<project-name> This will generate all the scaffolding files to run your project with pico-go. `, Run: func(cmd *cobra.Command, args []string) { fmt.Println("pico-go Create new project:") if len(args) != 1 { er("`new` command needs a name for the project") } if err := generate.NewProject(args[0], consoleType); err != nil { fmt.Printf("Failed to create new pico project: %s\n", err) } }, } func init() { RootCmd.AddCommand(newCmd) newCmd.Flags().StringVar(&consoleType, "type", console.PICO8, "default console type") }
package host import ( "context" "encoding/json" "fmt" "github.com/choria-io/go-choria/protocol" "github.com/choria-io/go-choria/providers/agent/mcorpc" rpc "github.com/choria-io/go-choria/providers/agent/mcorpc/client" addl "github.com/choria-io/go-choria/providers/agent/mcorpc/ddl/agent" "github.com/choria-io/go-choria/providers/agent/mcorpc/golang/provision" "github.com/prometheus/client_golang/prometheus" ) func (h *Host) rpcDo(ctx context.Context, agent string, action string, input interface{}, cb rpc.Handler) (*rpc.Stats, error) { name := fmt.Sprintf("%s#%s", agent, action) obs := prometheus.NewTimer(rpcDuration.WithLabelValues(h.cfg.Site, name)) defer obs.ObserveDuration() if h.cfg.Paused() { return nil, fmt.Errorf("Provisioning is paused, cannot perform %s", name) } ddl, err := addl.CachedDDL("choria_provision") if err != nil { return nil, fmt.Errorf("could not find DDL for agent choria_provision in the agent cache") } prov, err := rpc.New(h.fw, agent, rpc.DDL(ddl)) if err != nil { rpcErrCtr.WithLabelValues(h.cfg.Site, name).Inc() return nil, fmt.Errorf("could not create %s client: %s", agent, err) } handler := func(pr protocol.Reply, reply *rpc.RPCReply) { h.replylock.Lock() defer h.replylock.Unlock() if reply.Statuscode != mcorpc.OK { rpcErrCtr.WithLabelValues(h.cfg.Site, name).Inc() h.log.Errorf("Failed reply from %s: %s", pr.SenderID(), reply.Statusmsg) return } if pr.SenderID() == h.Identity { cb(pr, reply) } } result, err := prov.Do(ctx, action, input, rpc.Targets([]string{h.Identity}), rpc.Collective("provisioning"), rpc.ReplyHandler(handler), rpc.Workers(1)) if err != nil { rpcErrCtr.WithLabelValues(h.cfg.Site, name).Inc() return nil, fmt.Errorf("could not perform %s#%s: %s", agent, action, err) } if result.Stats().ResponsesCount() != 1 { rpcErrCtr.WithLabelValues(h.cfg.Site, name).Inc() return nil, fmt.Errorf("could not perform %s#%s: received %d responses while expecting a response from %s", agent, action, result.Stats().ResponsesCount(), h.Identity) } return result.Stats(), nil } func (h *Host) restart(ctx context.Context) error { h.log.Info("Restarting node") creq := &provision.RestartRequest{ Token: h.token, Splay: 1, } _, err := h.rpcDo(ctx, "choria_provision", "restart", creq, func(pr protocol.Reply, reply *rpc.RPCReply) { r := &provision.Reply{} err := json.Unmarshal(reply.Data, r) if err != nil { h.log.Errorf("Could not parse reply from %s: %s", pr.SenderID(), err) return } h.log.Infof("Restart response: %s", r.Message) }) return err } func (h *Host) configure(ctx context.Context) error { if len(h.config) == 0 { return fmt.Errorf("empty configuration") } h.log.Info("Configuring node") cj, err := json.Marshal(h.config) if err != nil { return fmt.Errorf("could not encode configuration: %s", err) } creq := &provision.ConfigureRequest{ Token: h.token, CA: h.ca, Certificate: h.cert, Configuration: string(cj), } if h.CSR != nil { creq.SSLDir = h.CSR.SSLDir } _, err = h.rpcDo(ctx, "choria_provision", "configure", creq, func(pr protocol.Reply, reply *rpc.RPCReply) { r := &provision.Reply{} err := json.Unmarshal(reply.Data, r) if err != nil { h.log.Errorf("Could not parse reply from %s: %s", pr.SenderID(), err) return } h.log.Infof("Configuration response: %s", r.Message) }) return err } func (h *Host) fetchJWT(ctx context.Context) (err error) { if h.rawJWT != "" { h.log.Infof("Already have JWT for %s, not retrieving again", h.Identity) return nil } h.log.Info("Fetching JWT") jwtreq := &provision.JWTRequest{ Token: h.token, } for try := 1; try <= 5; try++ { if ctx.Err() != nil { return ctx.Err() } _, err = h.rpcDo(ctx, "choria_provision", "jwt", jwtreq, func(pr protocol.Reply, reply *rpc.RPCReply) { resp := &provision.JWTReply{} err := json.Unmarshal(reply.Data, resp) if err != nil { h.log.Errorf("Invalid JSON data: %s", err) return } h.rawJWT = resp.JWT }) if err == nil { if len(h.rawJWT) == 0 { return fmt.Errorf("received an empty JWT") } return nil } } return err } func (h *Host) fetchInventory(ctx context.Context) (err error) { if len(h.Metadata) > 0 { h.log.Infof("Already have metadata for %s, not retrieving again", h.Identity) return nil } h.log.Info("Fetching Inventory") for try := 1; try <= 5; try++ { if ctx.Err() != nil { return ctx.Err() } if try > 1 { h.log.Warnf("Could not fetch rpcutil#inventory from %s on try %d / 5, retrying", h.Identity, try-1) } _, err = h.rpcDo(ctx, "rpcutil", "inventory", struct{}{}, func(pr protocol.Reply, reply *rpc.RPCReply) { h.Metadata = string(reply.Data) }) if err == nil { return nil } } return err } func (h *Host) fetchCSR(ctx context.Context) error { h.log.Info("Fetching CSR") csreq := &provision.CSRRequest{ Token: h.token, CN: h.Identity, } _, err := h.rpcDo(ctx, "choria_provision", "gencsr", csreq, func(pr protocol.Reply, reply *rpc.RPCReply) { h.CSR = &provision.CSRReply{} err := json.Unmarshal(reply.Data, h.CSR) if err != nil { h.log.Errorf("Could not parse reply from %s: %s", pr.SenderID(), err) return } }) return err }
package main import ( "fmt" "os" "github.com/drone/drone-go/drone" "github.com/drone/drone-go/plugin" "github.com/drone/drone-go/template" ) var ( buildCommit string defaultTemplate = `<strong>{{ uppercasefirst build.status }}</strong> <a href="{{ system.link_url }}/{{ repo.owner }}/{{ repo.name }}/{{ build.number }}">{{ repo.owner }}/{{ repo.name }}#{{ truncate build.commit 8 }}</a> ({{ build.branch }}) by {{ build.author }} in {{ duration build.started_at build.finished_at }} </br> - {{ build.message }}` defaultTitleTemplate = `by {{ build.author }} in {{ duration build.started_at build.finished_at }}` defaultDescTemplate = `<a href="{{ build.link_url }}">{{ truncate build.commit 8 }}</a> - <i>{{ build.message }}</i>` defaultActivityTemplate = `<a href="{{ system.link_url }}/{{ repo.owner }}/{{ repo.name }}/{{ build.number }}"><strong>{{ build.status }}</strong> {{ repo.name }} ({{ build.branch }})</a>` defaultIcon = "http://readme.drone.io/logos/downstream.svg" ) func main() { fmt.Printf("Drone HipChat Plugin built from %s\n", buildCommit) system := drone.System{} repo := drone.Repo{} build := drone.Build{} vargs := Params{} plugin.Param("system", &system) plugin.Param("repo", &repo) plugin.Param("build", &build) plugin.Param("vargs", &vargs) plugin.MustParse() if len(vargs.Template) == 0 { vargs.Template = defaultTemplate } message := &Message{ From: vargs.From, Notify: vargs.Notify, Color: Color(&build), Message: BuildTemplate( &system, &repo, &build, vargs.Template, ), } if vargs.UseCard { message.Card = BuildCard( &system, &repo, &build, &vargs, ) } client := NewClient( vargs.URL, vargs.Room.String(), vargs.Token, ) if err := client.Send(message); err != nil { fmt.Println(err) os.Exit(1) return } } // BuildCard creates the HipChat card func BuildCard(system *drone.System, repo *drone.Repo, build *drone.Build, vargs *Params) *Card { if len(vargs.TitleTemplate) == 0 { vargs.TitleTemplate = defaultTitleTemplate } if len(vargs.Icon) == 0 { vargs.Icon = defaultIcon } if len(vargs.DescTemplate) == 0 { vargs.DescTemplate = defaultDescTemplate } if len(vargs.ActivityTemplate) == 0 { vargs.ActivityTemplate = defaultActivityTemplate } card := &Card{ ID: build.Commit, Style: "application", Format: "medium", Title: BuildTemplate( system, repo, build, vargs.TitleTemplate, ), URL: BuildTemplate( system, repo, build, "{{ system.link_url }}/{{ repo.owner }}/{{ repo.name }}/{{ build.number }}", ), Activity: Activity{ Icon: vargs.Icon, HTML: BuildTemplate( system, repo, build, vargs.ActivityTemplate, ), }, } if len(build.Avatar) > 0 { card.Icon = &build.Avatar } if len(vargs.DescTemplate) > 0 { card.Description = &Description{ Format: "html", Value: BuildTemplate( system, repo, build, vargs.DescTemplate, ), } } return card } // BuildMessage renders the HipChat message from a template. func BuildTemplate(system *drone.System, repo *drone.Repo, build *drone.Build, tmpl string) string { payload := &drone.Payload{ System: system, Repo: repo, Build: build, } msg, err := template.RenderTrim(tmpl, payload) if err != nil { return err.Error() } return msg } // Color determins the notfication color based upon the current build status. func Color(build *drone.Build) string { switch build.Status { case drone.StatusSuccess: return "green" case drone.StatusFailure, drone.StatusError, drone.StatusKilled: return "red" default: return "yellow" } }
package task import ( "fmt" "io" "os" "github.com/go-task/task/v3/errors" "github.com/go-task/task/v3/internal/filepathext" ) const defaultTaskfile = `# https://taskfile.dev version: '3' vars: GREETING: Hello, World! tasks: default: cmds: - echo "{{.GREETING}}" silent: true ` const defaultTaskfileName = "Taskfile.yml" // InitTaskfile Taskfile creates a new Taskfile func InitTaskfile(w io.Writer, dir string) error { f := filepathext.SmartJoin(dir, defaultTaskfileName) if _, err := os.Stat(f); err == nil { return errors.TaskfileAlreadyExistsError{} } if err := os.WriteFile(f, []byte(defaultTaskfile), 0o644); err != nil { return err } fmt.Fprintf(w, "%s created in the current directory\n", defaultTaskfile) return nil }
package main import ( "fmt" "log" "net/http" "os" "time" _ "net/http/pprof" "github.com/pivotal-cf/terminalboard/api" capi "github.com/pivotal-cf/terminalboard/concourse/api" "golang.org/x/oauth2" ) const ( concourseHostEnvKey = "CONCOURSE_HOST" concourseUsernameEnvKey = "CONCOURSE_USERNAME" concoursePasswordEnvKey = "CONCOURSE_PASSWORD" portEnvKey = "PORT" defaultTeam = "main" ) func main() { concourseHost := os.Getenv(concourseHostEnvKey) concourseUsername := os.Getenv(concourseUsernameEnvKey) concoursePassword := os.Getenv(concoursePasswordEnvKey) port := os.Getenv(portEnvKey) if concourseHost == "" { panic(fmt.Sprintf("concourseHost must be provided via %s", concourseHostEnvKey)) } if concourseUsername == "" { panic(fmt.Sprintf("concourseUsername must be provided via %s", concourseUsernameEnvKey)) } if concoursePassword == "" { panic(fmt.Sprintf("concoursePassword must be provided via %s", concoursePasswordEnvKey)) } if port == "" { panic(fmt.Sprintf("port must be provided via %s", portEnvKey)) } go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() cts := concourseTokenSource{ concourseHost: concourseHost, concourseUsername: concourseUsername, concoursePassword: concoursePassword, defaultTeam: defaultTeam, } httpClient := capi.OAuthHTTPClient(oauth2.ReuseTokenSource(nil, cts), true) checker := api.NewChecker(concourseHost, defaultTeam, httpClient) router, err := api.NewRouter(checker) if err != nil { panic(err) } address := fmt.Sprintf(":%s", port) fmt.Println(fmt.Sprintf("Listening on %s", address)) err = http.ListenAndServe(address, router) if err != nil { panic(err) } } type concourseTokenSource struct { concourseHost string defaultTeam string concourseUsername string concoursePassword string } func (c concourseTokenSource) Token() (*oauth2.Token, error) { token, err := capi.LoginWithBasicAuth( c.concourseHost, c.defaultTeam, c.concourseUsername, c.concoursePassword, true, ) if err != nil { fmt.Fprintln(os.Stderr, fmt.Sprintf( "Error getting token: '%s'", err.Error(), )) return nil, err } oAuthToken := &oauth2.Token{ TokenType: token.Type, AccessToken: token.Value, Expiry: time.Now().Add(24 * time.Hour), } return oAuthToken, nil }
package main import ( "log" "net/http" "github.com/gorilla/mux" people "./controllers" ) // The person Type (more like an object) // Display all from the people var // main function to boot up everything func main() { inicialize() router := mux.NewRouter() router.HandleFunc("/people", people.GetPeople).Methods("GET") router.HandleFunc("/people/{id}", people.GetPerson).Methods("GET") router.HandleFunc("/people/{id}", people.CreatePerson).Methods("POST") router.HandleFunc("/people/{id}", people.DeletePerson).Methods("DELETE") log.Fatal(http.ListenAndServe(":8000", router)) } func inicialize() { people.LoadData() }
package lc // Time: O(n) // Benchmark: 0ms 2.2mb | 100% func subsets(nums []int) [][]int { subs := [][]int{} var search func(set []int, k int) search = func(set []int, k int) { if k == len(nums) { subs = append(subs, append([]int{}, set...)) return } set = append(set, nums[k]) search(set, k+1) set = set[:len(set)-1] search(set, k+1) } search([]int{}, 0) return subs }
package main import ( "bytes" "flag" "fmt" "html/template" "io/ioutil" "log" "path/filepath" "regexp" ) const ( tmplFile = "index-tmpl.html" tmplAnalyticsHTML = "analytics.html" ) var ( devFlag = flag.Bool("dev", false, "Generate development index.html") prodFlag = flag.Bool("prod", false, "Generate production index.html") prefix = flag.String("prefix", "dist", "Prefix where JavaScript file are loaded. Could be e.g. through CDN") templates = []string{ filepath.Join("tmpl", tmplFile), filepath.Join("tmpl", tmplAnalyticsHTML), } ) func main() { flag.Parse() if flag.NArg() != 1 { flag.Usage() return } t, err := template. New(tmplFile). ParseFiles(templates...) if err != nil { log.Fatalln(err) return } distPath := flag.Arg(0) data, err := resolveData(distPath) if err != nil { log.Fatalln(err) } indexHTML, err := toTemplate(t, data) if err != nil { log.Fatalln(err) } fmt.Println(indexHTML) } type IndexHTMLData struct { ManifestJS string VueVendorJS string AppJS string Analytics bool } func resolveData(path string) (*IndexHTMLData, error) { switch { case *devFlag: return &IndexHTMLData{ ManifestJS: fmt.Sprintf("%s/manifest.js", *prefix), VueVendorJS: fmt.Sprintf("%s/vuevendor.js", *prefix), AppJS: fmt.Sprintf("%s/app.js", *prefix), Analytics: false, }, nil case *prodFlag: return resolveProdData(path) default: return nil, fmt.Errorf("Define --dev or --prod flag") } } func resolveProdData(path string) (*IndexHTMLData, error) { manifestJS, err := findLatest(path, regexp.MustCompile(`^\S+-manifest\.js$`)) if err != nil { return nil, err } vuevendorJS, err := findLatest(path, regexp.MustCompile(`^\S+-vuevendor\.js$`)) if err != nil { return nil, err } appJS, err := findLatest(path, regexp.MustCompile(`^\S+-app\.js$`)) if err != nil { return nil, err } return &IndexHTMLData{ ManifestJS: filepath.Join(*prefix, manifestJS), VueVendorJS: filepath.Join(*prefix, vuevendorJS), AppJS: filepath.Join(*prefix, appJS), Analytics: true, }, nil } func toTemplate(t *template.Template, data interface{}) (string, error) { var result = &bytes.Buffer{} err := t.Execute(result, data) if err != nil { return "", err } return result.String(), nil } func findLatest(dir string, fileRegExp *regexp.Regexp) (string, error) { files, err := ioutil.ReadDir(dir) if err != nil { return "", err } var latest int64 thefile := "" for _, file := range files { if fileRegExp.MatchString(file.Name()) && file.ModTime().UnixNano() > latest { latest = file.ModTime().UnixNano() thefile = file.Name() } } if latest == 0 { return "", fmt.Errorf("File not found %s/%+v", dir, fileRegExp) } return thefile, nil }
package common import ( "io" "os" "time" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) const LogMsgCtxKey = "common_log_info" var log = logrus.New() type Log struct { entry *logrus.Entry } func NewLogger(serviceName string) *Log { entry := log.WithFields(logrus.Fields{ "service": serviceName, }) log.SetFormatter(&logrus.JSONFormatter{}) log.SetOutput(os.Stdout) return &Log{entry} } func (l *Log) SetOutput(output io.Writer) { log.SetOutput(output) } func (l *Log) Entry() *logrus.Entry { return l.entry } func (l *Log) RequestMiddleware() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Next() finish := time.Now() statusCode := c.Writer.Status() logMessage := "" i, ok := c.Get(LogMsgCtxKey) if ok { switch v := i.(type) { case string: logMessage = v case error: logMessage = v.Error() default: } } e := l.entry.WithFields(logrus.Fields{ "StatusCode": statusCode, "ClientIP": c.ClientIP(), "Method": c.Request.Method, "Path": c.Request.URL.Path, "Message": logMessage, "Latency": finish.Sub(start), }) switch v := statusCode; { case v < 400: e.Info() case v < 500: e.Warn() default: e.Error() } } }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package power import ( "context" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/servo" "chromiumos/tast/common/usbutils" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/remote/powercontrol" "chromiumos/tast/rpc" "chromiumos/tast/services/cros/ui" "chromiumos/tast/testing" "chromiumos/tast/testing/hwdep" ) type usbDeviceTestParam struct { iter int usbSpeed string noOfConnectedDevice int usbDeviceClassName string } func init() { testing.AddTest(&testing.Test{ Func: USBDeviceFunctionality, LacrosStatus: testing.LacrosVariantUnneeded, Desc: "Verifies USB device functionality before and after cold boot", Contacts: []string{"ambalavanan.m.m@intel.com", "intel-chrome-system-automation-team@intel.com"}, ServiceDeps: []string{"tast.cros.ui.AudioService"}, SoftwareDeps: []string{"chrome", "reboot"}, VarDeps: []string{"servo"}, Vars: []string{"power.usbDeviceName"}, HardwareDeps: hwdep.D(hwdep.ChromeEC()), Params: []testing.Param{{ Name: "hid_coldboot", Val: usbDeviceTestParam{ iter: 1, usbSpeed: "1.5M", noOfConnectedDevice: 1, // Test H/W tolopoly requires One USB Type-A Human Interface Device like Keyboard/Mouse. usbDeviceClassName: "Human Interface Device", }, Timeout: 5 * time.Minute, }, { Name: "hid_coldboot_stress", Val: usbDeviceTestParam{ iter: 10, usbSpeed: "1.5M", noOfConnectedDevice: 2, // Test H/W tolopoly requires Two USB Type-A Human Interface Device like Keyboard/Mouse. usbDeviceClassName: "Human Interface Device", }, Timeout: 20 * time.Minute, }, { Name: "usb2_pendrive_coldboot", Val: usbDeviceTestParam{ iter: 10, usbSpeed: "480M", noOfConnectedDevice: 1, // Test H/W tolopoly requires One USB Type-A 2.0 pendrive. usbDeviceClassName: "Mass Storage", }, Timeout: 20 * time.Minute, }, { Name: "usb3_pendrive_coldboot", Val: usbDeviceTestParam{ iter: 10, usbSpeed: "5000M", noOfConnectedDevice: 1, // Test H/W tolopoly requires One USB Type-A 3.0 pendrive. usbDeviceClassName: "Mass Storage", }, Timeout: 20 * time.Minute, }, }}) } func USBDeviceFunctionality(ctx context.Context, s *testing.State) { ctxForCleanUp := ctx ctx, cancel := ctxutil.Shorten(ctx, 2*time.Minute) defer cancel() dut := s.DUT() testParam := s.Param().(usbDeviceTestParam) servoSpec := s.RequiredVar("servo") pxy, err := servo.NewProxy(ctx, servoSpec, dut.KeyFile(), dut.KeyDir()) if err != nil { s.Fatal("Failed to connect to servo: ", err) } defer pxy.Close(ctxForCleanUp) defer func(ctx context.Context) { testing.ContextLog(ctx, "Performing cleanup") if !dut.Connected(ctx) { if err := powercontrol.PowerOntoDUT(ctx, pxy, dut); err != nil { s.Fatal("Failed to power-on DUT at cleanup: ", err) } } }(ctxForCleanUp) // Performs a Chrome login. loginChrome := func() (*rpc.Client, error) { testing.ContextLog(ctx, "Login to Chrome") cl, err := rpc.Dial(ctx, dut, s.RPCHint()) if err != nil { return nil, errors.Wrap(err, "failed to connect to the RPC service on the DUT") } audioService := ui.NewAudioServiceClient(cl.Conn) if _, err := audioService.New(ctx, &empty.Empty{}); err != nil { s.Fatal("Failed to login Chrome: ", err) } return cl, nil } // Perform initial Chrome login. cl, err := loginChrome() if err != nil { s.Fatal("Failed to login Chrome: ", err) } // power.usbDeviceName variable is required for USB storage related tests. usbStorageName, _ := s.Var("power.usbDeviceName") iter := testParam.iter for i := 1; i <= iter; i++ { testing.ContextLogf(ctx, "Iteration: %d/%d", i, iter) // Check for USB device(s) detection before cold boot. usbDevicesList, err := usbutils.ListDevicesInfo(ctx, dut) if err != nil { s.Fatal("Failed to get USB devices list: ", err) } got := usbutils.NumberOfUSBDevicesConnected(usbDevicesList, testParam.usbDeviceClassName, testParam.usbSpeed) if want := testParam.noOfConnectedDevice; got != want { s.Fatalf("Unexpected number of USB devices connected: got %d, want %d", got, want) } // Check USB storage device is shown in filesapp before cold boot. if testParam.usbDeviceClassName == "Mass Storage" { audioService := ui.NewAudioServiceClient(cl.Conn) dirName := &ui.AudioServiceRequest{DirectoryName: usbStorageName, FileName: ""} if _, err := audioService.OpenDirectoryAndFile(ctx, dirName); err != nil { s.Fatalf("Failed to open %q directory: %v", usbStorageName, err) } } powerState := "S5" if err := powercontrol.ShutdownAndWaitForPowerState(ctx, pxy, dut, powerState); err != nil { s.Fatalf("Failed to shutdown and wait for %q powerstate: %v", powerState, err) } if err := powercontrol.PowerOntoDUT(ctx, pxy, dut); err != nil { s.Fatal("Failed to power on DUT: ", err) } // Performing chrome login after powering on DUT from cold boot. cl, err = loginChrome() if err != nil { s.Fatal("Failed to login Chrome: ", err) } // Check for USB device(s) detection after cold boot. usbDevicesList, err = usbutils.ListDevicesInfo(ctx, dut) if err != nil { s.Fatal("Failed to get USB devices list: ", err) } got = usbutils.NumberOfUSBDevicesConnected(usbDevicesList, testParam.usbDeviceClassName, testParam.usbSpeed) if want := testParam.noOfConnectedDevice; got != want { s.Fatalf("Unexpected number of USB devices connected after cold boot: got %d, want %d", got, want) } // Check USB storage device is shown in filesapp after cold boot. if testParam.usbDeviceClassName == "Mass Storage" { audioService := ui.NewAudioServiceClient(cl.Conn) dirName := &ui.AudioServiceRequest{DirectoryName: usbStorageName, FileName: ""} if _, err := audioService.OpenDirectoryAndFile(ctx, dirName); err != nil { s.Fatalf("Failed to open %q directory after cold boot: %v", usbStorageName, err) } } // Perfoming prev_sleep_state check. expectedPrevSleepState := 5 if err := powercontrol.ValidatePrevSleepState(ctx, dut, expectedPrevSleepState); err != nil { s.Fatal("Failed to validate previous sleep state: ", err) } } }
// Copyright 2016-2017 Authors of Cilium // // 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 common import ( "testing" "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { check.TestingT(t) } type CommonSuite struct{} var _ = check.Suite(&CommonSuite{}) func (s *CommonSuite) TestGoArray2C(c *check.C) { c.Assert(goArray2C([]byte{0, 0x01, 0x02, 0x03}), check.Equals, "0x0, 0x1, 0x2, 0x3") c.Assert(goArray2C([]byte{0, 0xFF, 0xFF, 0xFF}), check.Equals, "0x0, 0xff, 0xff, 0xff") c.Assert(goArray2C([]byte{0xa, 0xbc, 0xde, 0xf1}), check.Equals, "0xa, 0xbc, 0xde, 0xf1") c.Assert(goArray2C([]byte{0}), check.Equals, "0x0") c.Assert(goArray2C([]byte{}), check.Equals, "") } func (s *CommonSuite) TestFmtDefineComma(c *check.C) { c.Assert(FmtDefineComma("foo", []byte{1, 2, 3}), check.Equals, "#define foo 0x1, 0x2, 0x3\n") c.Assert(FmtDefineComma("foo", []byte{}), check.Equals, "#define foo \n") } func (s *CommonSuite) TestFmtDefineAddress(c *check.C) { c.Assert(FmtDefineAddress("foo", []byte{1, 2, 3}), check.Equals, "#define foo { .addr = { 0x1, 0x2, 0x3 } }\n") c.Assert(FmtDefineAddress("foo", []byte{}), check.Equals, "#define foo { .addr = { } }\n") } func (s *CommonSuite) TestFmtDefineArray(c *check.C) { c.Assert(FmtDefineArray("foo", []byte{1, 2, 3}), check.Equals, "#define foo { 0x1, 0x2, 0x3 }\n") c.Assert(FmtDefineArray("foo", []byte{}), check.Equals, "#define foo { }\n") }
package main import ( "fmt" ) func main() { x := factorial(4) fmt.Println(x) } func factorial(x int) int { if x == 0 { return 1 } return x * factorial(x-1) } //function calls itself is called recursion and factorial is recursive function eg // ie factorial of 4 is 4*3*2*1
package event import ( "github.com/go-redis/redis/v8" "log" "shared/utility/global" "shared/utility/glog" "shared/utility/param" "testing" ) func TestEventLooper_Get(t *testing.T) { glog.InitLog() Redis := &redis.Options{ Username: "root", Password: "", Addr: ":6379", } RedisClient := redis.NewClient(Redis) eventLooper := NewEventQueue(RedisClient, global.NewGlobal(RedisClient)) UserEventHandler.Register(1, 1, func(Param *param.Param) error { log.Println(Param.GetString(0)) return nil }) eventLooper.Push(1, NewEvent(1, "test1")) eventLooper.Push(1, NewEvent(1, "test2")) eventLooper.ExecuteEventsInQueue(1) }
// Copyright 2015 go-swagger maintainers // // 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 client import "github.com/go-swagger/go-swagger/strfmt" // AuthInfoWriterFunc converts a function to a request writer interface type AuthInfoWriterFunc func(Request, strfmt.Registry) error // AuthenticateRequest adds authentication data to the request func (fn AuthInfoWriterFunc) AuthenticateRequest(req Request, reg strfmt.Registry) error { return fn(req, reg) } // An AuthInfoWriter implementor knows how to write authentication info to a request type AuthInfoWriter interface { AuthenticateRequest(Request, strfmt.Registry) error }
package worker import ( "fmt" "github.com/CleverTap/cfstack/internal/pkg/aws/cloudformation" "github.com/CleverTap/cfstack/internal/pkg/aws/s3" "github.com/CleverTap/cfstack/internal/pkg/aws/session" "github.com/CleverTap/cfstack/internal/pkg/stack" "github.com/Jeffail/gabs" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/fatih/color" "github.com/golang/glog" "github.com/pkg/errors" "os" "sort" "strings" "sync" "time" ) var ( MaxWorker = 50 MinWorker = 1 ) type RegionDiffWorkerJob struct { Region string Stacks []stack.Stack Profile string StackDiffWorker int Uid string TemplatesRoot string Values *gabs.Container Role string } type RegionDiffWorkerResult struct { Region string Stacks []stack.Stack Err error } type StackDiffJob struct { Stack *stack.Stack } type stackDiffWorkerJob struct { region string bucket string stack stack.Stack } type stackDiffWorkerResult struct { Stack stack.Stack Err error } func RegionDiffWorker(id int, wg *sync.WaitGroup, regionWorkerJobs <-chan RegionDiffWorkerJob, regionWorkerResults chan<- *RegionDiffWorkerResult) { var errResult error for regionWorkerJob := range regionWorkerJobs { //glog.Infof("region-worker-%d: starting diff for stacks in in region %s\n", id, regionWorkerJob.Region) region := regionWorkerJob.Region profile := regionWorkerJob.Profile templateRoot := regionWorkerJob.TemplatesRoot values := regionWorkerJob.Values role := regionWorkerJob.Role stacks := regionWorkerJob.Stacks out := make([]stack.Stack, 0) sess, err := session.NewSession(&session.Opts{ Profile: profile, Region: region, }) if err != nil { regionWorkerResults <- &RegionDiffWorkerResult{ Region: region, Stacks: out, Err: err, } wg.Done() } uploader := s3.New(sess) deployer := cloudformation.New(sess, values) bucket, err := deployer.GetStackResourcePhysicalId("cfstack-Init", "TemplatesS3Bucket") if err != nil { regionWorkerResults <- &RegionDiffWorkerResult{ Region: region, Stacks: out, Err: err, } wg.Done() } stackDiffWorkerJobs := make(chan stackDiffWorkerJob, len(stacks)) stackDiffWorkerResults := make(chan *stackDiffWorkerResult, len(stacks)) // start workers stackDiffWorkerWaitGroup := sync.WaitGroup{} workers := regionWorkerJob.StackDiffWorker if len(stacks) < MaxWorker { workers = len(stacks) } for i := 1; i <= workers; i++ { go stackDiffWorker(i, &stackDiffWorkerWaitGroup, stackDiffWorkerJobs, stackDiffWorkerResults) } limiter := time.Tick(50 * time.Millisecond) for i, s := range stacks { <-limiter s.SetRegion(regionWorkerJob.Region) s.SetUuid(regionWorkerJob.Uid) s.SetBucket(bucket) s.SetDeploymentOrder(i) s.TemplateRootPath = templateRoot s.Changes = &cloudformation.Changes{ Status: "", StatusReason: "", Resources: []cloudformation.ChangeResource{}, StackPolicyChange: false, } s.Uploader = uploader s.Deployer = deployer s.RoleArn = role stackDiffWorkerJobs <- stackDiffWorkerJob{ region: region, bucket: bucket, stack: s, } stackDiffWorkerWaitGroup.Add(1) } close(stackDiffWorkerJobs) stackDiffWorkerWaitGroup.Wait() for n := 0; n < len(stacks); n++ { select { case diffWorkerResult := <-stackDiffWorkerResults: err := diffWorkerResult.Err s := diffWorkerResult.Stack if err != nil { if strings.Contains(err.Error(), "No updates are to be performed") { continue } s.Changes.Status = stack.DiffFailStatus s.Changes.StatusReason = err.Error() if aerr, ok := err.(awserr.Error); ok { s.Changes.StatusReason = aerr.Message() switch aerr.Code() { case "ValidationError": if strings.Contains(aerr.Message(), "IN_PROGRESS") { color.New(color.FgYellow).Fprintf(os.Stdout, " %s\n", aerr.Message()) s.Changes.Status = stack.DiffUnknownStatus s.Changes.StatusReason = aerr.Message() } else { s.Changes.StatusReason = fmt.Sprintf("Unhandled AWS ValidationError for stack %s\n%s", s.StackName, aerr.Message()) } default: } } if s.Changes.Status == stack.DiffFailStatus { color.New(color.FgRed).Fprintf(os.Stdout, " diff failed for stack %s : %v\n", s.StackName, s.Changes.StatusReason) errResult = fmt.Errorf("diff for few stacks in %s region has failed", region) } out = append(out, s) continue } if s.Changes.StackPolicyChange || s.Changes.ForceStackUpdate || len(s.Changes.Resources) > 0 { s.Changes.Status = stack.DiffSuccessStatus out = append(out, s) } } } sort.Slice(out, func(i, j int) bool { return out[i].DeploymentOrder < out[j].DeploymentOrder }) regionWorkerResults <- &RegionDiffWorkerResult{ Region: region, Stacks: out, Err: errResult, } //glog.Infof("region-worker-%d: finishing diff for stacks in in region %s\n", id, regionWorkerJob.Region) wg.Done() } } func stackDiffWorker(id int, waitGroup *sync.WaitGroup, stackDiffWorkerJobs <-chan stackDiffWorkerJob, stackDiffWorkerResults chan<- *stackDiffWorkerResult) { for diffWorkerJob := range stackDiffWorkerJobs { s := diffWorkerJob.stack //glog.Infof("worker-%d: fetching diff for stack %s in region %s\n", id, s.StackName, s.Region) timeout := time.After(24 * time.Hour) ticker := time.Tick(10 * time.Second) diffComplete := false for diffComplete == false { select { case <-timeout: stackDiffWorkerResults <- &stackDiffWorkerResult{Err: errors.New("too many AWS API calls. Try again later")} case <-ticker: err := s.Diff() if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case "Throttling": glog.Warningf("AWS rate limit error for stack %s, retrying..", s.StackName) continue case "ValidationError": if strings.Contains(aerr.Message(), "S3 error: Access Denied") { glog.Warningf("AWS request error for stack %s, retrying..", s.StackName) continue } case "RequestError": glog.Warningf("AWS request error for stack %s - %s, retrying..", s.StackName, aerr.Message()) continue case "ChangeSetNotFound": glog.Warningf("Looks like changeset not found for stack %s, retrying..", s.StackName) continue default: glog.Errorf("unhandled AWS error for stack %s\n%s : %s", s.StackName, aerr.Code(), aerr.Message()) } } } stackDiffWorkerResults <- &stackDiffWorkerResult{ Stack: s, Err: err, } diffComplete = true } } //glog.Infof("worker-%d: Received diff for stack %s in region %s\n", id, s.StackName, s.Region) waitGroup.Done() } }
package main import ( "./GmailCredentialManager" "encoding/base64" "fmt" "google.golang.org/api/gmail/v1" "strings" ) func main() { client := GmailCredentialManager.GetService() _ = GetAllMessagesFromUser(client, "", 4) } func GetLastNMessages(srv *gmail.Service, n int) []*gmail.Message { s := make([]*gmail.Message, n) r, e := srv.Users.Messages.List("me").Do() c(e) for i, e := range r.Messages { if i == n { break } t, x := srv.Users.Messages.Get("me", e.Id).Do() c(x) s[i] = t } return s } func GetLastNMessagesAsString(srv *gmail.Service, n int) []string { msgs := GetLastNMessages(srv, n) s := make([]string, n) for i, e := range msgs { parts := e.Payload.Parts t := make([]string, n) for _, k := range parts { b, err := base64.URLEncoding.DecodeString(k.Body.Data) c(err) t = append(t, string(b)) } s[i] = strings.Join(t, "\n") } return s } func GetMessageBodyAsString(msg *gmail.Message) string { parts := msg.Payload.Parts t := make([]string, len(msg.Payload.Parts)) for _, k := range parts { b, err := base64.URLEncoding.DecodeString(k.Body.Data) c(err) t = append(t, string(b)) } return strings.Join(t, "\n") } func GetAllMessagesFromUser(srv *gmail.Service, sender string, depth int) []*gmail.Message { msgs := GetLastNMessages(srv, depth) t := make([]*gmail.Message, depth) tmp := 0 for i, e := range msgs { if e.Payload.Headers[20].Value == sender { t = append(t, e) } fmt.Print(i) tmp = i } if len(t) != depth { x := make([]*gmail.Message, tmp) for _, e := range t { if e == nil { return x } x = append(x, e) } return x } return t } func GetAllMessagesFromUserAsStrings(client *gmail.Service, sender string, depth int) []string { msgs := GetAllMessagesFromUser(client, sender, depth) s := make([]string, len(msgs)) for _, e := range msgs { s = append(s, GetMessageBodyAsString(e)) } return s } //c checks that an error has not been thrown. func c(e error) { if e != nil { fmt.Println(e) panic(9) } }
package main import "fmt" type Vertex struct { x int //, 这里不能有逗号 y int } func main() { fmt.Println(Vertex{1, 2}) var a Vertex a.x = 1 a.y = 2 fmt.Println(a) }
package query const ( // DBProtoVersion is the cassandra protocol version used by gophr. DBProtoVersion = 4 // DBKeyspaceName is the name of the gophr cassandra keyspace. DBKeyspaceName = "gophr" )
package main import "fmt" func main() { t := 10 fmt.Print(t / 3) } type ListNode struct { Val int Next *ListNode } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { ret := &ListNode{ Val: 0, } left := 0 retHead := ret for l1 != nil || l2 != nil { sum := left if l1 != nil { sum += l1.Val l1 = l1.Next } if l2 != nil { sum += l2.Val l2 = l2.Next } tmp := &ListNode{ Val: sum % 10, } ret.Next = tmp ret = ret.Next left = sum / 10 } if left == 1 { ret.Next = &ListNode{ Val: 1, } } return retHead.Next }
/* 1. Program that prints out all numbers between 1 and 100 that are divisible by 3 2. Program that prints the numbers from 1 to 100, but for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers that are multiples of both three and five, print "FizzBuzz." */ package main import "fmt" func main() { fmt.Println("Running function one...") functionOne() fmt.Println("-----------------------") fmt.Println("Running function two...") functionTwo() fmt.Println("-----------------------") } func functionOne() { for i := 1; i <= 100; i++ { if i%3 == 0 { fmt.Println(i) } } } func functionTwo() { fizz := "Fizz" buzz := "Buzz" for i := 1; i <= 100; i++ { if i%3 == 0 && i%5 == 0 { fmt.Println(fizz + buzz) } else if i%3 == 0 { fmt.Println(fizz) } else if i%5 == 0 { fmt.Println(buzz) } } }
// Copyright 2017 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package sql_test import ( "context" "fmt" "regexp" "testing" "github.com/cockroachdb/cockroach/pkg/keys" "github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv" "github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb" "github.com/cockroachdb/cockroach/pkg/sql/tests" "github.com/cockroachdb/cockroach/pkg/testutils/serverutils" "github.com/cockroachdb/cockroach/pkg/util/leaktest" "github.com/cockroachdb/cockroach/pkg/util/log" ) func TestTableRefs(t *testing.T) { defer leaktest.AfterTest(t)() defer log.Scope(t).Close(t) params, _ := tests.CreateTestServerParams() s, db, kvDB := serverutils.StartServer(t, params) defer s.Stopper().Stop(context.Background()) // Populate the test database. stmt := ` CREATE DATABASE test; CREATE TABLE test.t(a INT PRIMARY KEY, xx INT, b INT, c INT); CREATE TABLE test.hidden(a INT, b INT); CREATE INDEX bc ON test.t(b, c); ` _, err := db.Exec(stmt) if err != nil { t.Fatal(err) } // Retrieve the numeric descriptors. tableDesc := catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, "test", "t") tID := tableDesc.GetID() var aID, bID, cID descpb.ColumnID for _, c := range tableDesc.PublicColumns() { switch c.GetName() { case "a": aID = c.GetID() case "b": bID = c.GetID() case "c": cID = c.GetID() } } pkID := tableDesc.GetPrimaryIndexID() secID := tableDesc.PublicNonPrimaryIndexes()[0].GetID() // Retrieve the numeric descriptors. tableDesc = catalogkv.TestingGetTableDescriptor(kvDB, keys.SystemSQLCodec, "test", "hidden") tIDHidden := tableDesc.GetID() var rowIDHidden descpb.ColumnID for _, c := range tableDesc.PublicColumns() { switch c.GetName() { case "rowid": rowIDHidden = c.GetID() } } // Make some schema changes meant to shuffle the ID/name mapping. stmt = ` ALTER TABLE test.t RENAME COLUMN b TO d; ALTER TABLE test.t RENAME COLUMN a TO p; ALTER TABLE test.t DROP COLUMN xx; ` _, err = db.Exec(stmt) if err != nil { t.Fatal(err) } // Check the table references. testData := []struct { tableExpr string expectedColumns string expectedError string }{ {fmt.Sprintf("[%d as t]", tID), `(p, d, c)`, ``}, {fmt.Sprintf("[%d(%d) as t]", tID, aID), `(p)`, ``}, {fmt.Sprintf("[%d(%d) as t]", tID, bID), `(d)`, ``}, {fmt.Sprintf("[%d(%d) as t]", tID, cID), `(c)`, ``}, {fmt.Sprintf("[%d as t]@bc", tID), `(p, d, c)`, ``}, {fmt.Sprintf("[%d(%d) as t]@bc", tID, aID), `(p)`, ``}, {fmt.Sprintf("[%d(%d) as t]@bc", tID, bID), `(d)`, ``}, {fmt.Sprintf("[%d(%d) as t]@bc", tID, cID), `(c)`, ``}, {fmt.Sprintf("[%d(%d, %d, %d) as t]", tID, cID, bID, aID), `(c, d, p)`, ``}, {fmt.Sprintf("[%d(%d, %d, %d) as t(c, b, a)]", tID, cID, bID, aID), `(c, b, a)`, ``}, {fmt.Sprintf("[%d() as t]", tID), ``, `pq: an explicit list of column IDs must include at least one column`}, {`[666() as t]`, ``, `pq: [666() AS t]: relation "[666]" does not exist`}, {fmt.Sprintf("[%d(666) as t]", tID), ``, `pq: column [666] does not exist`}, {fmt.Sprintf("test.t@[%d]", pkID), `(p, d, c)`, ``}, {fmt.Sprintf("test.t@[%d]", secID), `(p, d, c)`, ``}, {`test.t@[666]`, ``, `pq: index [666] not found`}, {fmt.Sprintf("[%d as t]@[%d]", tID, pkID), `(p, d, c)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, aID, pkID), `(p)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, bID, pkID), `(d)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, cID, pkID), `(c)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, aID, secID), `(p)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, bID, secID), `(d)`, ``}, {fmt.Sprintf("[%d(%d) as t]@[%d]", tID, cID, secID), `(c)`, ``}, {fmt.Sprintf("[%d(%d) as t]", tIDHidden, rowIDHidden), `()`, ``}, } for i, d := range testData { t.Run(d.tableExpr, func(t *testing.T) { sql := `SELECT info FROM [EXPLAIN(VERBOSE) SELECT * FROM ` + d.tableExpr + `] WHERE info LIKE '%columns:%'` var columns string if err := db.QueryRow(sql).Scan(&columns); err != nil { if d.expectedError != "" { if err.Error() != d.expectedError { t.Fatalf("%d: %s: expected error: %s, got: %v", i, d.tableExpr, d.expectedError, err) } } else { t.Fatalf("%d: %s: query failed: %v", i, d.tableExpr, err) } } r := regexp.MustCompile("^.*columns: ") columns = r.ReplaceAllString(columns, "") if columns != d.expectedColumns { t.Fatalf("%d: %s: expected: %s, got: %s", i, d.tableExpr, d.expectedColumns, columns) } }) } }
package main import ( "CurrencyConverter/converters" "CurrencyConverter/validate" "fmt" "strconv" ) func main() { c := &converters.CAD{Label: "CAD", Symbol: "$", Amount: 0} u := &converters.USD{Label: "USD", Symbol: "$", Amount: 0} e := &converters.EUR{Label: "EUR", Symbol: "€", Amount: 0} converters := []converters.Converter{c, u, e} fmt.Println("Select your base currency:") for i, v := range converters { fmt.Printf("[%v] %v\n", i+1, v.GetLabel()) } var baseCurrency int fmt.Scanln(&baseCurrency) for validate.OutsideSelectionRange(baseCurrency, len(converters)) { fmt.Println("Invalid selection, try again:") fmt.Scanln(&baseCurrency) } selectedCurrency := converters[baseCurrency-1] currencyLabel := selectedCurrency.GetLabel() currencySymbol := selectedCurrency.GetSymbol() fmt.Printf("Selected base currency: %v\n\n", currencyLabel) fmt.Println("Select your currency to convert to:") // for i := 0; i < len(converters); i++ { for i, v := range converters { if i != (baseCurrency - 1) { fmt.Printf("[%v] %v\n", i+1, v.GetLabel()) } } var selectedConverter int fmt.Scanln(&selectedConverter) for selectedConverter == baseCurrency || selectedConverter < 1 || selectedConverter > len(converters) { fmt.Println("Invalid selection, try again:") fmt.Scanln(&selectedConverter) } converter := converters[selectedConverter-1] converterLabel := converter.GetLabel() converterSymbol := converter.GetSymbol() fmt.Printf("Selected conversion currency: %v\n\n", converterLabel) fmt.Printf("Enter %v amount to convert:\n", currencyLabel) fmt.Printf("%v", currencySymbol) var amount float64 fmt.Scanln(&amount) converter.SetAmount(amount) convertedAmount := converter.Convert(currencyLabel) fmt.Printf("%v%v %v -> %v%v %v\n", currencySymbol, amount, currencyLabel, converterSymbol, strconv.FormatFloat(convertedAmount, 'f', 2, 64), converterLabel) }
package jwt_auth import ( "finance/plugins/redis" "fmt" ) // 校验token是否被刷新 func (claims *CustomClaims) AuthToken() bool { redis_key := fmt.Sprintf("FinanceIat_%s", claims.Phone) redis_iat, _ := redis.Get(redis_key) if claims.Iat != redis_iat { return false } else { return true } } func (claims *CustomClaims) Clear() { redis_key := claims.RedisKey() redis.Delete(redis_key) } func (claims *CustomClaims) RedisKey() string { return fmt.Sprintf("FinanceIat_%s", claims.Phone) }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package main import "github.com/spf13/cobra" type clusterInstallationGetFlags struct { clusterFlags clusterInstallationID string } func (flags *clusterInstallationGetFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation to be fetched.") _ = command.MarkFlagRequired("cluster-installation") } type clusterInstallationListFlags struct { clusterFlags pagingFlags tableOptions cluster string installation string } func (flags *clusterInstallationListFlags) addFlags(command *cobra.Command) { flags.pagingFlags.addFlags(command) flags.tableOptions.addFlags(command) command.Flags().StringVar(&flags.cluster, "cluster", "", "The cluster by which to filter cluster installations.") command.Flags().StringVar(&flags.installation, "installation", "", "The installation by which to filter cluster installations.") } type clusterInstallationConfigGetFlags struct { clusterFlags clusterInstallationID string } func (flags *clusterInstallationConfigGetFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") _ = command.MarkFlagRequired("cluster-installation") } type clusterInstallationStatusFlags struct { clusterFlags clusterInstallationID string } func (flags *clusterInstallationStatusFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") _ = command.MarkFlagRequired("cluster-installation") } type clusterInstallationConfigSetFlags struct { clusterFlags clusterInstallationID string key string val string } func (flags *clusterInstallationConfigSetFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") command.Flags().StringVar(&flags.key, "key", "", "The configuration key to update (e.g. ServiceSettings.SiteURL).") command.Flags().StringVar(&flags.val, "value", "", "The value to write to the config.") _ = command.MarkFlagRequired("cluster-installation") _ = command.MarkFlagRequired("key") _ = command.MarkFlagRequired("value") } type clusterInstallationMMCTLFlags struct { clusterFlags clusterInstallationID string subcommand string } func (flags *clusterInstallationMMCTLFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") command.Flags().StringVar(&flags.subcommand, "command", "", "The mmctl subcommand to run.") _ = command.MarkFlagRequired("cluster-installation") _ = command.MarkFlagRequired("command") } type clusterInstallationMattermostCLIFlags struct { clusterFlags clusterInstallationID string subcommand string } func (flags *clusterInstallationMattermostCLIFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") command.Flags().StringVar(&flags.subcommand, "command", "", "The Mattermost CLI subcommand to run.") _ = command.MarkFlagRequired("cluster-installation") _ = command.MarkFlagRequired("command") } type clusterInstallationMigrationFlags struct { clusterFlags installation string sourceCluster string targetCluster string } func (flags *clusterInstallationMigrationFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.installation, "installation", "", "The specific installation ID to migrate from source cluster, default is ALL.") command.Flags().StringVar(&flags.sourceCluster, "source-cluster", "", "The source cluster for the migration to migrate cluster installations from.") command.Flags().StringVar(&flags.targetCluster, "target-cluster", "", "The target cluster for the migration to migrate cluster installation to.") _ = command.MarkFlagRequired("source-cluster") _ = command.MarkFlagRequired("target-cluster") } type clusterInstallationDNSMigrationFlags struct { clusterFlags installation string sourceCluster string targetCluster string lockInstallation bool } func (flags *clusterInstallationDNSMigrationFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.installation, "installation", "", "The specific installation ID to migrate from source cluster, default is ALL.") command.Flags().StringVar(&flags.sourceCluster, "source-cluster", "", "The source cluster for the migration to switch CNAME(s) from.") command.Flags().StringVar(&flags.targetCluster, "target-cluster", "", "The target cluster for the migration to switch CNAME to.") command.Flags().BoolVar(&flags.lockInstallation, "lock-installation", true, "The installation's lock flag during DNS migration process.") _ = command.MarkFlagRequired("source-cluster") _ = command.MarkFlagRequired("target-cluster") } type inActiveClusterInstallationDeleteFlags struct { clusterFlags cluster string clusterInstallationID string } func (flags *inActiveClusterInstallationDeleteFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.cluster, "cluster", "", "The cluster ID to delete stale cluster installations from.") command.Flags().StringVar(&flags.clusterInstallationID, "cluster-installation", "", "The id of the cluster installation.") _ = command.MarkFlagRequired("cluster") } type clusterRolesPostMigrationSwitchFlags struct { clusterFlags sourceCluster string targetCluster string } func (flags *clusterRolesPostMigrationSwitchFlags) addFlags(command *cobra.Command) { command.Flags().StringVar(&flags.sourceCluster, "source-cluster", "", "The source cluster to be mark as secondary cluster.") command.Flags().StringVar(&flags.targetCluster, "target-cluster", "", "The target cluster to be mark as primary cluster.") _ = command.MarkFlagRequired("source-cluster") _ = command.MarkFlagRequired("target-cluster") }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package coldata import ( "time" "github.com/cockroachdb/apd/v2" "github.com/cockroachdb/cockroach/pkg/util/duration" ) // Bools is a slice of bool. type Bools []bool // Int16s is a slice of int16. type Int16s []int16 // Int32s is a slice of int32. type Int32s []int32 // Int64s is a slice of int64. type Int64s []int64 // Float64s is a slice of float64. type Float64s []float64 // Decimals is a slice of apd.Decimal. type Decimals []apd.Decimal // Times is a slice of time.Time. type Times []time.Time // Durations is a slice of duration.Duration. type Durations []duration.Duration // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Bools) Get(idx int) bool { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Int16s) Get(idx int) int16 { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Int32s) Get(idx int) int32 { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Int64s) Get(idx int) int64 { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Float64s) Get(idx int) float64 { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Decimals) Get(idx int) apd.Decimal { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Times) Get(idx int) time.Time { return c[idx] } // Get returns the element at index idx of the vector. The element cannot be // used anymore once the vector is modified. //gcassert:inline func (c Durations) Get(idx int) duration.Duration { return c[idx] } // Len returns the length of the vector. func (c Bools) Len() int { return len(c) } // Len returns the length of the vector. func (c Int16s) Len() int { return len(c) } // Len returns the length of the vector. func (c Int32s) Len() int { return len(c) } // Len returns the length of the vector. func (c Int64s) Len() int { return len(c) } // Len returns the length of the vector. func (c Float64s) Len() int { return len(c) } // Len returns the length of the vector. func (c Decimals) Len() int { return len(c) } // Len returns the length of the vector. func (c Times) Len() int { return len(c) } // Len returns the length of the vector. func (c Durations) Len() int { return len(c) }
package util import ( "fmt" "github.com/appscode/go/types" core "k8s.io/api/core/v1" "kmodules.xyz/client-go/tools/cli" "kmodules.xyz/client-go/tools/clientcmd" "stash.appscode.dev/stash/apis" v1alpha1_api "stash.appscode.dev/stash/apis/stash/v1alpha1" v1beta1_api "stash.appscode.dev/stash/apis/stash/v1beta1" "stash.appscode.dev/stash/pkg/docker" ) func NewInitContainer(r *v1alpha1_api.Restic, workload v1alpha1_api.LocalTypedReference, image docker.Docker) core.Container { container := NewSidecarContainer(r, workload, image) container.Args = []string{ "backup", "--restic-name=" + r.Name, "--workload-kind=" + workload.Kind, "--workload-name=" + workload.Name, "--docker-registry=" + image.Registry, "--image-tag=" + image.Tag, "--pushgateway-url=" + PushgatewayURL(), fmt.Sprintf("--enable-status-subresource=%v", apis.EnableStatusSubresource), fmt.Sprintf("--use-kubeapiserver-fqdn-for-aks=%v", clientcmd.UseKubeAPIServerFQDNForAKS()), fmt.Sprintf("--enable-analytics=%v", cli.EnableAnalytics), } container.Args = append(container.Args, cli.LoggerOptions.ToFlags()...) container.Args = append(container.Args, "--enable-rbac=true") return container } func NewRestoreInitContainer(rs *v1beta1_api.RestoreSession, repository *v1alpha1_api.Repository, image docker.Docker) core.Container { initContainer := core.Container{ Name: StashInitContainer, Image: image.ToContainerImage(), Args: append([]string{ "restore", "--restore-session=" + rs.Name, "--secret-dir=" + StashSecretMountDir, fmt.Sprintf("--enable-cache=%v", !rs.Spec.TempDir.DisableCaching), fmt.Sprintf("--max-connections=%v", GetMaxConnections(repository.Spec.Backend)), "--metrics-enabled=true", "--pushgateway-url=" + PushgatewayURL(), fmt.Sprintf("--enable-status-subresource=%v", apis.EnableStatusSubresource), fmt.Sprintf("--use-kubeapiserver-fqdn-for-aks=%v", clientcmd.UseKubeAPIServerFQDNForAKS()), fmt.Sprintf("--enable-analytics=%v", cli.EnableAnalytics), }, cli.LoggerOptions.ToFlags()...), Env: []core.EnvVar{ { Name: KeyNodeName, ValueFrom: &core.EnvVarSource{ FieldRef: &core.ObjectFieldSelector{ FieldPath: "spec.nodeName", }, }, }, { Name: KeyPodName, ValueFrom: &core.EnvVarSource{ FieldRef: &core.ObjectFieldSelector{ FieldPath: "metadata.name", }, }, }, }, VolumeMounts: []core.VolumeMount{ { Name: StashSecretVolume, MountPath: StashSecretMountDir, }, }, } // mount tmp volume initContainer.VolumeMounts = UpsertTmpVolumeMount(initContainer.VolumeMounts) // mount the volumes specified in RestoreSession inside this init-container for _, srcVol := range rs.Spec.Target.VolumeMounts { initContainer.VolumeMounts = append(initContainer.VolumeMounts, core.VolumeMount{ Name: srcVol.Name, MountPath: srcVol.MountPath, SubPath: srcVol.SubPath, }) } // if Repository uses local volume as backend, we have to mount it inside the initContainer if repository.Spec.Backend.Local != nil { _, mnt := repository.Spec.Backend.Local.ToVolumeAndMount(LocalVolumeName) initContainer.VolumeMounts = append(initContainer.VolumeMounts, mnt) } // pass container runtime settings from RestoreSession to init-container if rs.Spec.RuntimeSettings.Container != nil { initContainer.Resources = rs.Spec.RuntimeSettings.Container.Resources if rs.Spec.RuntimeSettings.Container.LivenessProbe != nil { initContainer.LivenessProbe = rs.Spec.RuntimeSettings.Container.LivenessProbe } if rs.Spec.RuntimeSettings.Container.ReadinessProbe != nil { initContainer.ReadinessProbe = rs.Spec.RuntimeSettings.Container.ReadinessProbe } if rs.Spec.RuntimeSettings.Container.Lifecycle != nil { initContainer.Lifecycle = rs.Spec.RuntimeSettings.Container.Lifecycle } } // In order to preserve file ownership, restore process need to be run as root user. // Stash image uses non-root user "stash"(1005). We have to use securityContext to run stash as root user. // If a user specify securityContext either in pod level or container level in RuntimeSetting, // don't overwrite that. In this case, user must take the responsibility of possible file ownership modification. securityContext := &core.SecurityContext{ RunAsUser: types.Int64P(0), RunAsGroup: types.Int64P(0), } if rs.Spec.RuntimeSettings.Container != nil { securityContext = UpsertSecurityContext(securityContext, rs.Spec.RuntimeSettings.Container.SecurityContext) } initContainer.SecurityContext = UpsertSecurityContext(initContainer.SecurityContext, securityContext) return initContainer }
package main import ( "fmt" "github.com/aliyun/aliyun-datahub-sdk-go/datahub" ) func main() { dh = datahub.New(accessId, accessKey, endpoint) } func openOffset() { shardIds := []string{"0", "1", "2"} oss, err := dh.OpenSubscriptionSession(projectName, topicName, subId, shardIds) if err != nil { fmt.Println("open session failed") fmt.Println(err) } fmt.Println("open session successful") fmt.Println(oss) } func getOffset() { shardIds := []string{"0", "1", "2"} gss, err := dh.GetSubscriptionOffset(projectName, topicName, subId, shardIds) if err != nil { fmt.Println("get session failed") fmt.Println(err) } fmt.Println("get session successful") fmt.Println(gss) } func updateOffset() { shardIds := []string{"0", "1", "2"} oss, err := dh.OpenSubscriptionSession(projectName, topicName, subId, shardIds) if err != nil { fmt.Println("open session failed") fmt.Println(err) } fmt.Println("open session successful") fmt.Println(oss) offset := oss.Offsets["0"] // set offset message offset.Sequence = 900 offset.Timestamp = 1565593166690 offsetMap := map[string]datahub.SubscriptionOffset{ "0": offset, } if _, err := dh.CommitSubscriptionOffset(projectName, topicName, subId, offsetMap); err != nil { if _, ok := err.(*datahub.SubscriptionOfflineError); ok { fmt.Println("the subscription has offline") } else if _, ok := err.(*datahub.SubscriptionSessionInvalidError); ok { fmt.Println("the subscription is open elsewhere") } else if _, ok := err.(*datahub.SubscriptionOffsetResetError); ok { fmt.Println("the subscription is reset elsewhere") } else { fmt.Println(err) } fmt.Println("update offset failed") return } fmt.Println("update offset successful") } func resetOffset() { offset := datahub.SubscriptionOffset{ Timestamp: 1565593166690, } offsetMap := map[string]datahub.SubscriptionOffset{ "1": offset, } if _, err := dh.ResetSubscriptionOffset(projectName, topicName, subId, offsetMap); err != nil { fmt.Println("reset offset failed") fmt.Println(err) return } fmt.Println("reset offset successful") }
// These are examples of manipulating binary values. package binary
package core import ( "database/sql" "database/sql/driver" ) // Scan implements the sql.Scanner interface. func (this *Int) Scan(value interface{}) error { if value == nil { this.int, this.Valid = 0, false return nil } var ns sql.NullInt64 err := ns.Scan(value) if err != nil { this.int = int(ns.Int64) this.Valid = false return err } this.Valid = true this.int = int(ns.Int64) return nil } // Value implements the driver.Valuer interface. func (this Int) Value() (driver.Value, error) { if !this.Valid { return nil, nil } return this.int, nil }
package helm import ( "crypto/subtle" "net/http" "strings" "time" "github.com/rancher/fleet/integrationtests/cli" ) const ( username = "user" password = "pass" ) type repository struct { server *http.Server port string } // starts a helm repository on localhost:3000. It contains all repositories that are located in the assets/helmrepository folder. // basic auth is enabled is authEnabled is true. func (r *repository) startRepository(authEnabled bool) { r.server = &http.Server{Addr: r.port, ReadHeaderTimeout: 1 * time.Second} r.server.Handler = getHandler(authEnabled) go func() { const maxAttempts = 10 currentAttempt := 0 for { err := r.server.ListenAndServe() // It is possible that the previous repository is still closing as it takes a few extra milliseconds to fully close // retry after 100 milliseconds if "address already in use" error is returned if err != nil && strings.Contains(err.Error(), "address already in use") { if currentAttempt == maxAttempts { panic("Max number of attempts reached: error creating helm repository: " + err.Error()) } currentAttempt++ time.Sleep(100 * time.Millisecond) continue } if err != nil && err != http.ErrServerClosed { panic("error creating helm repository: " + err.Error()) } break } }() } func getHandler(authEnabled bool) http.Handler { fs := http.FileServer(http.Dir(cli.AssetsPath + "helmrepository")) if !authEnabled { return fs } return &authHandler{fs: fs} } func (r *repository) stopRepository() error { return r.server.Close() } // handler with basic authentication enabled type authHandler struct { fs http.Handler } func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || subtle.ConstantTimeCompare([]byte(strings.TrimSpace(user)), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(strings.TrimSpace(pass)), []byte(password)) != 1 { w.WriteHeader(401) _, err := w.Write([]byte("Unauthorised.")) if err != nil { return } return } h.fs.ServeHTTP(w, r) }
package tiltfile import ( "context" "fmt" "path/filepath" "strings" "time" "github.com/looplab/tarjan" "github.com/pkg/errors" "go.starlark.net/starlark" "go.starlark.net/syntax" "golang.org/x/mod/semver" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/tilt-dev/tilt/internal/controllers/apis/cmdimage" "github.com/tilt-dev/tilt/internal/controllers/apis/dockerimage" "github.com/tilt-dev/tilt/internal/controllers/apis/liveupdate" "github.com/tilt-dev/tilt/internal/controllers/apiset" "github.com/tilt-dev/tilt/internal/localexec" "github.com/tilt-dev/tilt/internal/tiltfile/cisettings" "github.com/tilt-dev/tilt/internal/tiltfile/hasher" "github.com/tilt-dev/tilt/internal/tiltfile/links" "github.com/tilt-dev/tilt/internal/tiltfile/print" "github.com/tilt-dev/tilt/internal/tiltfile/probe" "github.com/tilt-dev/tilt/internal/tiltfile/sys" "github.com/tilt-dev/tilt/internal/tiltfile/tiltextension" "github.com/tilt-dev/tilt/pkg/apis" "github.com/tilt-dev/tilt/internal/container" "github.com/tilt-dev/tilt/internal/dockercompose" "github.com/tilt-dev/tilt/internal/feature" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/ospath" "github.com/tilt-dev/tilt/internal/sliceutils" "github.com/tilt-dev/tilt/internal/tiltfile/analytics" "github.com/tilt-dev/tilt/internal/tiltfile/config" "github.com/tilt-dev/tilt/internal/tiltfile/dockerprune" "github.com/tilt-dev/tilt/internal/tiltfile/encoding" "github.com/tilt-dev/tilt/internal/tiltfile/git" "github.com/tilt-dev/tilt/internal/tiltfile/include" "github.com/tilt-dev/tilt/internal/tiltfile/io" tiltfile_k8s "github.com/tilt-dev/tilt/internal/tiltfile/k8s" "github.com/tilt-dev/tilt/internal/tiltfile/k8scontext" "github.com/tilt-dev/tilt/internal/tiltfile/loaddynamic" "github.com/tilt-dev/tilt/internal/tiltfile/metrics" "github.com/tilt-dev/tilt/internal/tiltfile/os" "github.com/tilt-dev/tilt/internal/tiltfile/secretsettings" "github.com/tilt-dev/tilt/internal/tiltfile/shlex" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" "github.com/tilt-dev/tilt/internal/tiltfile/starlarkstruct" "github.com/tilt-dev/tilt/internal/tiltfile/telemetry" "github.com/tilt-dev/tilt/internal/tiltfile/updatesettings" tfv1alpha1 "github.com/tilt-dev/tilt/internal/tiltfile/v1alpha1" "github.com/tilt-dev/tilt/internal/tiltfile/version" "github.com/tilt-dev/tilt/internal/tiltfile/watch" fwatch "github.com/tilt-dev/tilt/internal/watch" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" "github.com/tilt-dev/tilt/pkg/logger" "github.com/tilt-dev/tilt/pkg/model" ) var unmatchedImageNoConfigsWarning = "We could not find any deployment instructions, e.g. `k8s_yaml` or `docker_compose`.\n" + "Skipping all image builds until we know how to deploy them." var unmatchedImageAllUnresourcedWarning = "No Kubernetes configs with images found.\n" + "If you are using CRDs, add k8s_kind() to tell Tilt how to find images.\n" + "https://docs.tilt.dev/api.html#api.k8s_kind" var pkgInitTime = time.Now() type resourceSet struct { dc []*dcResourceSet k8s []*k8sResource } type tiltfileState struct { // set at creation ctx context.Context dcCli dockercompose.DockerComposeClient webHost model.WebHost execer localexec.Execer k8sContextPlugin k8scontext.Plugin versionPlugin version.Plugin configPlugin *config.Plugin extensionPlugin *tiltextension.Plugin ciSettingsPlugin cisettings.Plugin features feature.FeatureSet // added to during execution buildIndex *buildIndex k8sObjectIndex *tiltfile_k8s.State // The mutation semantics of these 3 things are a bit fuzzy // Objects are moved back and forth between them in different // phases of tiltfile execution and post-execution assembly. // // TODO(nick): Move these into a unified k8sObjectIndex that // maintains consistent internal state. Right now the state // is duplicated. k8s []*k8sResource k8sByName map[string]*k8sResource k8sUnresourced []k8s.K8sEntity dc dcResourceMap k8sResourceOptions []k8sResourceOptions localResources []*localResource localByName map[string]*localResource // ensure that any images are pushed to/pulled from this registry, rewriting names if needed defaultReg *v1alpha1.RegistryHosting k8sKinds map[k8s.ObjectSelector]*tiltfile_k8s.KindInfo workloadToResourceFunction workloadToResourceFunction // for assembly usedImages map[string]bool // count how many times each builtin is called, for analytics builtinCallCounts map[string]int // how many times each arg is used on each builtin builtinArgCounts map[string]map[string]int // any LiveUpdate steps that have been created but not used by a LiveUpdate will cause an error, to ensure // that users aren't accidentally using step-creating functions incorrectly // stored as a map of string(declarationPosition) -> step // it'd be appealing to store this as a map[liveUpdateStep]bool, but then things get weird if we have two steps // with the same hashcode (like, all restartcontainer steps) unconsumedLiveUpdateSteps map[string]liveUpdateStep // global trigger mode -- will be the default for all manifests (tho user can still explicitly set // triggerMode for a specific manifest) triggerMode triggerMode // for error reporting in case it's called twice triggerModeCallPosition syntax.Position teamID string secretSettings model.SecretSettings apiObjects apiset.ObjectSet logger logger.Logger // postExecReadFiles is generally a mistake -- it means that if tiltfile execution fails, // these will never be read. Remove these when you can!!! postExecReadFiles []string // Temporary directory for storing generated artifacts during the lifetime of the tiltfile context. // The directory is recursively deleted when the context is done. scratchDir *fwatch.TempDir } func newTiltfileState( ctx context.Context, dcCli dockercompose.DockerComposeClient, webHost model.WebHost, execer localexec.Execer, k8sContextPlugin k8scontext.Plugin, versionPlugin version.Plugin, configPlugin *config.Plugin, extensionPlugin *tiltextension.Plugin, ciSettingsPlugin cisettings.Plugin, features feature.FeatureSet) *tiltfileState { return &tiltfileState{ ctx: ctx, dcCli: dcCli, webHost: webHost, execer: execer, k8sContextPlugin: k8sContextPlugin, versionPlugin: versionPlugin, configPlugin: configPlugin, extensionPlugin: extensionPlugin, ciSettingsPlugin: ciSettingsPlugin, buildIndex: newBuildIndex(), k8sObjectIndex: tiltfile_k8s.NewState(), k8sByName: make(map[string]*k8sResource), dc: make(map[string]*dcResourceSet), localByName: make(map[string]*localResource), usedImages: make(map[string]bool), logger: logger.Get(ctx), builtinCallCounts: make(map[string]int), builtinArgCounts: make(map[string]map[string]int), unconsumedLiveUpdateSteps: make(map[string]liveUpdateStep), localResources: []*localResource{}, triggerMode: TriggerModeAuto, features: features, secretSettings: model.DefaultSecretSettings(), apiObjects: apiset.ObjectSet{}, k8sKinds: tiltfile_k8s.InitialKinds(), } } // print() for fulfilling the starlark thread callback func (s *tiltfileState) print(_ *starlark.Thread, msg string) { s.logger.Infof("%s", msg) } // Load loads the Tiltfile in `filename`, and returns the manifests matching `matching`. // // This often returns a starkit.Model even on error, because the starkit.Model // has a record of what happened during the execution (what files were read, etc). // // TODO(nick): Eventually this will just return a starkit.Model, which will contain // all the mutable state collected by execution. func (s *tiltfileState) loadManifests(tf *v1alpha1.Tiltfile) ([]model.Manifest, starkit.Model, error) { s.logger.Infof("Loading Tiltfile at: %s", tf.Spec.Path) result, err := starkit.ExecFile(tf, s, include.IncludeFn{}, git.NewPlugin(), os.NewPlugin(), sys.NewPlugin(), io.NewPlugin(), s.k8sContextPlugin, dockerprune.NewPlugin(), analytics.NewPlugin(), s.versionPlugin, s.configPlugin, starlarkstruct.NewPlugin(), telemetry.NewPlugin(), metrics.NewPlugin(), updatesettings.NewPlugin(), s.ciSettingsPlugin, secretsettings.NewPlugin(), encoding.NewPlugin(), shlex.NewPlugin(), watch.NewPlugin(), loaddynamic.NewPlugin(), s.extensionPlugin, links.NewPlugin(), print.NewPlugin(), probe.NewPlugin(), tfv1alpha1.NewPlugin(), hasher.NewPlugin(), ) if err != nil { return nil, result, starkit.UnpackBacktrace(err) } resources, unresourced, err := s.assemble() if err != nil { return nil, result, err } us, err := updatesettings.GetState(result) if err != nil { return nil, result, err } err = s.assertAllImagesMatched(us) if err != nil { s.logger.Warnf("%s", err.Error()) } manifests := []model.Manifest{} k8sContextState, err := k8scontext.GetState(result) if err != nil { return nil, result, err } if len(resources.k8s) > 0 || len(unresourced) > 0 { ms, err := s.translateK8s(resources.k8s, us) if err != nil { return nil, result, err } manifests = append(manifests, ms...) isAllowed := k8sContextState.IsAllowed(tf) if !isAllowed { kubeContext := k8sContextState.KubeContext() return nil, result, fmt.Errorf(`Stop! %s might be production. If you're sure you want to deploy there, add: allow_k8s_contexts('%s') to your Tiltfile. Otherwise, switch k8s contexts and restart Tilt.`, kubeContext, kubeContext) } } if len(resources.dc) > 0 { if err := s.validateDockerComposeVersion(); err != nil { return nil, result, err } for _, dc := range resources.dc { ms, err := s.translateDC(dc) if err != nil { return nil, result, err } manifests = append(manifests, ms...) } } err = s.validateLiveUpdatesForManifests(manifests) if err != nil { return nil, result, err } err = s.checkForUnconsumedLiveUpdateSteps() if err != nil { return nil, result, err } localManifests, err := s.translateLocal() if err != nil { return nil, result, err } manifests = append(manifests, localManifests...) if len(unresourced) > 0 { mn := model.UnresourcedYAMLManifestName r := &k8sResource{ name: mn.String(), entities: unresourced, podReadinessMode: model.PodReadinessIgnore, } kt, err := s.k8sDeployTarget(mn.TargetName(), r, nil, us) if err != nil { return nil, starkit.Model{}, err } yamlManifest := model.Manifest{Name: mn}.WithDeployTarget(kt) manifests = append(manifests, yamlManifest) } err = s.sanitizeDependencies(manifests) if err != nil { return nil, starkit.Model{}, err } for i := range manifests { // ensure all manifests have a label indicating they're owned // by the Tiltfile - some reconcilers have special handling l := manifests[i].Labels if l == nil { l = make(map[string]string) } manifests[i] = manifests[i].WithLabels(l) err := manifests[i].Validate() if err != nil { // Even on manifest validation errors, we may be able // to use other kinds of models (e.g., watched files) return manifests, result, err } } return manifests, result, nil } // Builtin functions const ( // build functions dockerBuildN = "docker_build" customBuildN = "custom_build" defaultRegistryN = "default_registry" // docker compose functions dockerComposeN = "docker_compose" dcResourceN = "dc_resource" // k8s functions k8sYamlN = "k8s_yaml" filterYamlN = "filter_yaml" k8sResourceN = "k8s_resource" portForwardN = "port_forward" k8sKindN = "k8s_kind" k8sImageJSONPathN = "k8s_image_json_path" workloadToResourceFunctionN = "workload_to_resource_function" k8sCustomDeployN = "k8s_custom_deploy" // local resource functions localResourceN = "local_resource" testN = "test" // a deprecated fork of local resource // file functions localN = "local" kustomizeN = "kustomize" helmN = "helm" // live update functions fallBackOnN = "fall_back_on" syncN = "sync" runN = "run" restartContainerN = "restart_container" // trigger mode triggerModeN = "trigger_mode" triggerModeAutoN = "TRIGGER_MODE_AUTO" triggerModeManualN = "TRIGGER_MODE_MANUAL" // feature flags enableFeatureN = "enable_feature" disableFeatureN = "disable_feature" disableSnapshotsN = "disable_snapshots" // other functions setTeamN = "set_team" ) type triggerMode int func (m triggerMode) String() string { switch m { case TriggerModeAuto: return triggerModeAutoN case TriggerModeManual: return triggerModeManualN default: return fmt.Sprintf("unknown trigger mode with value %d", m) } } func (t triggerMode) Type() string { return "TriggerMode" } func (t triggerMode) Freeze() { // noop } func (t triggerMode) Truth() starlark.Bool { return starlark.MakeInt(int(t)).Truth() } func (t triggerMode) Hash() (uint32, error) { return starlark.MakeInt(int(t)).Hash() } var _ starlark.Value = triggerMode(0) const ( TriggerModeUnset triggerMode = iota TriggerModeAuto triggerMode = iota TriggerModeManual triggerMode = iota ) func (s *tiltfileState) triggerModeForResource(resourceTriggerMode triggerMode) triggerMode { if resourceTriggerMode != TriggerModeUnset { return resourceTriggerMode } else { return s.triggerMode } } func starlarkTriggerModeToModel(triggerMode triggerMode, autoInit bool) (model.TriggerMode, error) { switch triggerMode { case TriggerModeAuto: if !autoInit { return model.TriggerModeAutoWithManualInit, nil } return model.TriggerModeAuto, nil case TriggerModeManual: if autoInit { return model.TriggerModeManualWithAutoInit, nil } else { return model.TriggerModeManual, nil } default: return 0, fmt.Errorf("unknown triggerMode %v", triggerMode) } } // count how many times each Builtin is called, for analytics func (s *tiltfileState) OnBuiltinCall(name string, fn *starlark.Builtin) { s.builtinCallCounts[name]++ } func (s *tiltfileState) OnExec(t *starlark.Thread, tiltfilePath string, contents []byte) error { return nil } // wrap a builtin such that it's only allowed to run when we have a known safe k8s context // (none (e.g., docker-compose), local, or specified by `allow_k8s_contexts`) func (s *tiltfileState) potentiallyK8sUnsafeBuiltin(f starkit.Function) starkit.Function { return func(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { tf, err := starkit.StartTiltfileFromThread(thread) if err != nil { return nil, err } model, err := starkit.ModelFromThread(thread) if err != nil { return nil, err } k8sContextState, err := k8scontext.GetState(model) if err != nil { return nil, err } isAllowed := k8sContextState.IsAllowed(tf) if !isAllowed { kubeContext := k8sContextState.KubeContext() return nil, fmt.Errorf(`Refusing to run '%s' because %s might be a production kube context. If you're sure you want to continue add: allow_k8s_contexts('%s') before this function call in your Tiltfile. Otherwise, switch k8s contexts and restart Tilt.`, fn.Name(), kubeContext, kubeContext) } return f(thread, fn, args, kwargs) } } func (s *tiltfileState) unpackArgs(fnname string, args starlark.Tuple, kwargs []starlark.Tuple, pairs ...interface{}) error { err := starlark.UnpackArgs(fnname, args, kwargs, pairs...) if err == nil { var paramNames []string for i, o := range pairs { if i%2 == 0 { name := strings.TrimSuffix(o.(string), "?") paramNames = append(paramNames, name) } } usedParamNames := paramNames[:args.Len()] for _, p := range kwargs { name := strings.TrimSuffix(string(p[0].(starlark.String)), "?") usedParamNames = append(usedParamNames, name) } _, ok := s.builtinArgCounts[fnname] if !ok { s.builtinArgCounts[fnname] = make(map[string]int) } for _, paramName := range usedParamNames { s.builtinArgCounts[fnname][paramName]++ } } return err } // TODO(nick): Split these into separate plugins func (s *tiltfileState) OnStart(e *starkit.Environment) error { e.SetArgUnpacker(s.unpackArgs) e.SetPrint(s.print) e.SetContext(s.ctx) for _, b := range []struct { name string builtin starkit.Function }{ {localN, s.potentiallyK8sUnsafeBuiltin(s.local)}, {dockerBuildN, s.dockerBuild}, {customBuildN, s.customBuild}, {defaultRegistryN, s.defaultRegistry}, {dockerComposeN, s.dockerCompose}, {dcResourceN, s.dcResource}, {k8sYamlN, s.k8sYaml}, {filterYamlN, s.filterYaml}, {k8sResourceN, s.k8sResource}, {k8sCustomDeployN, s.k8sCustomDeploy}, {localResourceN, s.localResource}, {testN, s.localResource}, {portForwardN, s.portForward}, {k8sKindN, s.k8sKind}, {k8sImageJSONPathN, s.k8sImageJsonPath}, {workloadToResourceFunctionN, s.workloadToResourceFunctionFn}, {kustomizeN, s.kustomize}, {helmN, s.helm}, {triggerModeN, s.triggerModeFn}, {fallBackOnN, s.liveUpdateFallBackOn}, {syncN, s.liveUpdateSync}, {runN, s.liveUpdateRun}, {restartContainerN, s.liveUpdateRestartContainer}, {enableFeatureN, s.enableFeature}, {disableFeatureN, s.disableFeature}, {disableSnapshotsN, s.disableSnapshots}, {setTeamN, s.setTeam}, } { err := e.AddBuiltin(b.name, b.builtin) if err != nil { return err } } for _, v := range []struct { name string value starlark.Value }{ {triggerModeAutoN, TriggerModeAuto}, {triggerModeManualN, TriggerModeManual}, } { err := e.AddValue(v.name, v.value) if err != nil { return err } } return nil } func (s *tiltfileState) assemble() (resourceSet, []k8s.K8sEntity, error) { err := s.assembleImages() if err != nil { return resourceSet{}, nil, err } err = s.assembleK8s() if err != nil { return resourceSet{}, nil, err } err = s.assembleDC() if err != nil { return resourceSet{}, nil, err } dcRes := []*dcResourceSet{} for _, resSet := range s.dc { dcRes = append(dcRes, resSet) } return resourceSet{ dc: dcRes, k8s: s.k8s, }, s.k8sUnresourced, nil } // Emit an error if there are unmatches images. // // There are 4 mistakes people commonly make if they // have unmatched images: // 1. They didn't include any Kubernetes or Docker Compose configs at all. // 2. They included Kubernetes configs, but they're custom resources // and Tilt can't infer the image. // 3. They typo'd the image name, and need help finding the right name. // 4. The tooling they're using to generating the k8s resources // isn't generating what they expect. // // This function intends to help with cases (1)-(3). // Long-term, we want to have better tooling to help with (4), // like being able to see k8s resources as they move thru // the build system. func (s *tiltfileState) assertAllImagesMatched(us model.UpdateSettings) error { unmatchedImages := s.buildIndex.unmatchedImages() unmatchedImages = filterUnmatchedImages(us, unmatchedImages) if len(unmatchedImages) == 0 { return nil } dcSvcCount := s.dc.ServiceCount() if dcSvcCount == 0 && len(s.k8s) == 0 && len(s.k8sUnresourced) == 0 { return fmt.Errorf(unmatchedImageNoConfigsWarning) } if len(s.k8s) == 0 && len(s.k8sUnresourced) != 0 { return fmt.Errorf(unmatchedImageAllUnresourcedWarning) } configType := "Kubernetes" if dcSvcCount > 0 { configType = "Docker Compose" } return s.buildIndex.unmatchedImageWarning(unmatchedImages[0], configType) } func (s *tiltfileState) assembleImages() error { for _, imageBuilder := range s.buildIndex.images { if imageBuilder.dbDockerfile != "" { depImages, err := imageBuilder.dbDockerfile.FindImages(imageBuilder.dbBuildArgs) if err != nil { return err } for _, depImage := range depImages { depBuilder := s.buildIndex.findBuilderForConsumedImage(depImage) if depBuilder == nil { // Images in the Dockerfile that don't have docker_build // instructions are OK. We'll pull them as prebuilt images. continue } imageBuilder.imageMapDeps = append(imageBuilder.imageMapDeps, depBuilder.ImageMapName()) } } for _, depImage := range imageBuilder.customImgDeps { depBuilder := s.buildIndex.findBuilderForConsumedImage(depImage) if depBuilder == nil { // If the user specifically said to depend on this image, there // must be a build instruction for it. return fmt.Errorf("image %q: image dep %q not found", imageBuilder.configurationRef.RefFamiliarString(), container.FamiliarString(depImage)) } imageBuilder.imageMapDeps = append(imageBuilder.imageMapDeps, depBuilder.ImageMapName()) } } return nil } func (s *tiltfileState) assembleDC() error { if s.dc.ServiceCount() > 0 && !container.IsEmptyRegistry(s.defaultReg) { return errors.New("default_registry is not supported with docker compose") } for _, resSet := range s.dc { for _, svcName := range resSet.serviceNames { svc := resSet.services[svcName] builder := s.buildIndex.findBuilderForConsumedImage(svc.ImageRef()) if builder != nil { // there's a Tilt-managed builder (e.g. docker_build or custom_build) for this image reference, so use that svc.ImageMapDeps = append(svc.ImageMapDeps, builder.ImageMapName()) } else { // create a DockerComposeBuild image target and consume it if this service has a build section in YAML err := s.maybeAddDockerComposeImageBuilder(svc) if err != nil { return err } } } } return nil } func (s *tiltfileState) maybeAddDockerComposeImageBuilder(svc *dcService) error { build := svc.ServiceConfig.Build if build == nil || build.Context == "" { // this Docker Compose service has no build info - it relies purely on // a pre-existing image (e.g. from a registry) return nil } buildContext := build.Context dfPath := build.Dockerfile if dfPath == "" { // Per Compose spec, the default is "Dockerfile" (in the context dir) dfPath = "Dockerfile" } // Only populate dbBuildPath if it's an absolute path, not if it's a git url. dbBuildPath := "" if filepath.IsAbs(buildContext) { dbBuildPath = buildContext } if !filepath.IsAbs(dfPath) && dbBuildPath != "" { dfPath = filepath.Join(dbBuildPath, dfPath) } imageRef := svc.ImageRef() err := s.buildIndex.addImage( &dockerImage{ buildType: DockerComposeBuild, configurationRef: container.NewRefSelector(imageRef), dockerComposeService: svc.ServiceName, dockerComposeLocalVolumePaths: svc.MountedLocalDirs, dbBuildPath: dbBuildPath, dbDockerfilePath: dfPath, }) if err != nil { return err } b := s.buildIndex.findBuilderForConsumedImage(imageRef) svc.ImageMapDeps = append(svc.ImageMapDeps, b.ImageMapName()) return nil } func (s *tiltfileState) assembleK8s() error { err := s.assembleK8sByWorkload() if err != nil { return err } err = s.assembleK8sUnresourced() if err != nil { return err } resourcedEntities := []k8s.K8sEntity{} for _, r := range s.k8sByName { resourcedEntities = append(resourcedEntities, r.entities...) } allEntities := append(resourcedEntities, s.k8sUnresourced...) fragmentsToEntities := k8s.FragmentsToEntities(allEntities) fullNames := make([]string, len(allEntities)) for i, e := range allEntities { fullNames[i] = fullNameFromK8sEntity(e) } for _, opts := range s.k8sResourceOptions { if opts.manuallyGrouped { r, err := s.makeK8sResource(opts.newName) if err != nil { return err } r.manuallyGrouped = true s.k8sByName[opts.newName] = r } if r, ok := s.k8sByName[opts.workload]; ok { // Options are added, so aggregate options from previous resource calls. r.extraPodSelectors = append(r.extraPodSelectors, opts.extraPodSelectors...) if opts.podReadinessMode != model.PodReadinessNone { r.podReadinessMode = opts.podReadinessMode } if opts.discoveryStrategy != "" { r.discoveryStrategy = opts.discoveryStrategy } r.portForwards = append(r.portForwards, opts.portForwards...) if opts.triggerMode != TriggerModeUnset { r.triggerMode = opts.triggerMode } if opts.autoInit.IsSet { r.autoInit = bool(opts.autoInit.Value) } r.resourceDeps = append(r.resourceDeps, opts.resourceDeps...) r.links = append(r.links, opts.links...) for k, v := range opts.labels { r.labels[k] = v } if opts.newName != "" && opts.newName != r.name { err := s.checkResourceConflict(opts.newName) if err != nil { return fmt.Errorf("%s: k8s_resource specified to rename %q to %q: %v", opts.tiltfilePosition.String(), r.name, opts.newName, err) } delete(s.k8sByName, r.name) r.name = opts.newName s.k8sByName[r.name] = r } selectors := make([]k8s.ObjectSelector, len(opts.objects)) for i, o := range opts.objects { s, err := k8s.SelectorFromString(o) if err != nil { return errors.Wrapf(err, "Error making selector from string %q", o) } selectors[i] = s } for i, o := range opts.objects { entities, ok := fragmentsToEntities[strings.ToLower(o)] if !ok || len(entities) == 0 { return fmt.Errorf("No object identified by the fragment %q could be found. Possible objects are: %s", o, sliceutils.QuotedStringList(fullNames)) } if len(entities) > 1 { matchingObjects := make([]string, len(entities)) for i, e := range entities { matchingObjects[i] = fullNameFromK8sEntity(e) } return fmt.Errorf("%q is not a unique fragment. Objects that match %q are %s", o, o, sliceutils.QuotedStringList(matchingObjects)) } entitiesToRemove := filterEntitiesBySelector(s.k8sUnresourced, selectors[i]) if len(entitiesToRemove) == 0 { // we've already taken these entities out of unresourced remainingUnresourced := make([]string, len(s.k8sUnresourced)) for i, entity := range s.k8sUnresourced { remainingUnresourced[i] = fullNameFromK8sEntity(entity) } return fmt.Errorf("No object identified by the fragment %q could be found in remaining YAML. Valid remaining fragments are: %s", o, sliceutils.QuotedStringList(remainingUnresourced)) } if len(entitiesToRemove) > 1 { panic(fmt.Sprintf("Fragment %q matches %d resources. Each object fragment must match exactly 1 resource. This should NOT be possible at this point in the code, we should have already checked that this fragment was unique", o, len(entitiesToRemove))) } s.addEntityToResourceAndRemoveFromUnresourced(entitiesToRemove[0], r) } } else { var knownResources []string for name := range s.k8sByName { knownResources = append(knownResources, name) } return fmt.Errorf("%s: k8s_resource specified unknown resource %q. known k8s resources: %s", opts.tiltfilePosition.String(), opts.workload, strings.Join(knownResources, ", ")) } } for _, r := range s.k8s { if err := s.validateK8s(r); err != nil { return err } } return nil } // NOTE(dmiller): This isn't _technically_ a fullname since it is missing "group" (core, apps, data, etc) // A true full name would look like "foo:secret:mynamespace:core" // However because we // a) couldn't think of a concrete case where you would need to specify group // b) being able to do so would make things more complicated, like in the case where you want to specify the group of // // a cluster scoped object but are unable to specify the namespace (e.g. foo:clusterrole::rbac.authorization.k8s.io) // // we decided to leave it off for now. When we encounter a concrete use case for specifying group it shouldn't be too // hard to add it here and in the docs. func fullNameFromK8sEntity(e k8s.K8sEntity) string { return k8s.SelectorStringFromParts([]string{e.Name(), e.GVK().Kind, e.Namespace().String()}) } func filterEntitiesBySelector(entities []k8s.K8sEntity, sel k8s.ObjectSelector) []k8s.K8sEntity { ret := []k8s.K8sEntity{} for _, e := range entities { if sel.Matches(e) { ret = append(ret, e) } } return ret } func (s *tiltfileState) addEntityToResourceAndRemoveFromUnresourced(e k8s.K8sEntity, r *k8sResource) { r.entities = append(r.entities, e) for i, ur := range s.k8sUnresourced { if ur == e { // delete from unresourced s.k8sUnresourced = append(s.k8sUnresourced[:i], s.k8sUnresourced[i+1:]...) return } } panic("Unable to find entity in unresourced YAML after checking that it was there. This should never happen") } func (s *tiltfileState) assembleK8sByWorkload() error { locators := s.k8sImageLocatorsList() var workloads, rest []k8s.K8sEntity for _, e := range s.k8sUnresourced { isWorkload, err := s.isWorkload(e, locators) if err != nil { return err } if isWorkload { workloads = append(workloads, e) } else { rest = append(rest, e) } } s.k8sUnresourced = rest resourceNames, err := s.calculateResourceNames(workloads) if err != nil { return err } for i, resourceName := range resourceNames { workload := workloads[i] res, err := s.makeK8sResource(resourceName) if err != nil { return errors.Wrapf(err, "error making resource for workload %s", newK8sObjectID(workload)) } err = res.addEntities([]k8s.K8sEntity{workload}, locators, s.envVarImages()) if err != nil { return err } // find any other entities that match the workload's labels (e.g., services), // and move them from unresourced to this resource match, rest, err := k8s.FilterByMatchesPodTemplateSpec(workload, s.k8sUnresourced) if err != nil { return err } err = res.addEntities(match, locators, s.envVarImages()) if err != nil { return err } s.k8sUnresourced = rest } return nil } func (s *tiltfileState) envVarImages() []container.RefSelector { var r []container.RefSelector // explicitly don't care about order for _, img := range s.buildIndex.images { if !img.matchInEnvVars { continue } r = append(r, img.configurationRef) } return r } func (s *tiltfileState) isWorkload(e k8s.K8sEntity, locators []k8s.ImageLocator) (bool, error) { for sel := range s.k8sKinds { if sel.Matches(e) { return true, nil } } images, err := e.FindImages(locators, s.envVarImages()) if err != nil { return false, errors.Wrapf(err, "finding images in %s", e.Name()) } else { return len(images) > 0, nil } } // assembleK8sUnresourced makes k8sResources for all k8s entities that: // a. are not already attached to a Tilt resource, and // b. will result in pods, // and stores the resulting resource(s) on the tiltfileState. // (We smartly grouping pod-creating entities with some kinds of // corresponding entities, e.g. services), func (s *tiltfileState) assembleK8sUnresourced() error { withPodSpec, allRest, err := k8s.FilterByHasPodTemplateSpec(s.k8sUnresourced) if err != nil { return nil } for _, e := range withPodSpec { target, err := s.k8sResourceForName(e.Name()) if err != nil { return err } target.entities = append(target.entities, e) match, rest, err := k8s.FilterByMatchesPodTemplateSpec(e, allRest) if err != nil { return err } target.entities = append(target.entities, match...) allRest = rest } s.k8sUnresourced = allRest return nil } func (s *tiltfileState) validateK8s(r *k8sResource) error { if len(r.entities) == 0 && r.customDeploy == nil { return fmt.Errorf("resource %q: could not associate any k8s_yaml() or k8s_custom_deploy() with this resource", r.name) } for _, ref := range r.imageRefs { builder := s.buildIndex.findBuilderForConsumedImage(ref) if builder != nil { r.imageMapDeps = append(r.imageMapDeps, builder.ImageMapName()) continue } metadata, ok := r.imageDepsMetadata[ref.String()] if ok && metadata.required { return fmt.Errorf("resource %q: image build %q not found", r.name, container.FamiliarString(ref)) } } return nil } // k8sResourceForName returns the k8sResource with which this name is associated // (either an existing resource or a new one). func (s *tiltfileState) k8sResourceForName(name string) (*k8sResource, error) { if r, ok := s.k8sByName[name]; ok { return r, nil } // otherwise, create a new resource return s.makeK8sResource(name) } // Auto-infer the readiness mode // // CONVO: // jazzdan: This still feels overloaded to me // nicks: i think whenever we define a new CRD, we need to know: // how to find the images in it // how to find any pods it deploys (if they can't be found by owner references) // if it should not expect pods at all (e.g., PostgresVersion) // if it should wait for the pods to be ready before building the next resource (e.g., servers) // if it should wait for the pods to be complete before building the next resource (e.g., jobs) // and it's complicated a bit by the fact that there are both normal CRDs where the image shows up in the same place each time, and more meta CRDs (like HelmRelease) where it might appear in different places // // feels like we're still doing this very ad-hoc rather than holistically func (s *tiltfileState) inferPodReadinessMode(r *k8sResource) model.PodReadinessMode { // The mode set directly on the resource has highest priority. if r.podReadinessMode != model.PodReadinessNone { return r.podReadinessMode } // Next, check if any of the k8s kinds have a mode. hasMode := make(map[model.PodReadinessMode]bool) for _, e := range r.entities { for sel, info := range s.k8sKinds { if sel.Matches(e) { hasMode[info.PodReadinessMode] = true } } } modes := []model.PodReadinessMode{model.PodReadinessWait, model.PodReadinessIgnore, model.PodReadinessSucceeded} for _, m := range modes { if hasMode[m] { return m } } // Auto-infer based on context // // If the resource was // 1) manually grouped (i.e., we didn't find any images in it) // 2) doesn't have pod selectors, and // 3) doesn't depend on images // assume that it will never create pods. if r.manuallyGrouped && len(r.extraPodSelectors) == 0 && len(r.imageMapDeps) == 0 { return model.PodReadinessIgnore } return model.PodReadinessWait } func (s *tiltfileState) translateK8s(resources []*k8sResource, updateSettings model.UpdateSettings) ([]model.Manifest, error) { var result []model.Manifest for _, r := range resources { mn := model.ManifestName(r.name) tm, err := starlarkTriggerModeToModel(s.triggerModeForResource(r.triggerMode), r.autoInit) if err != nil { return nil, errors.Wrapf(err, "error in resource %s options", mn) } var mds []model.ManifestName for _, md := range r.resourceDeps { mds = append(mds, model.ManifestName(md)) } m := model.Manifest{ Name: mn, TriggerMode: tm, ResourceDependencies: mds, } m = m.WithLabels(r.labels) iTargets, err := s.imgTargetsForDeps(mn, r.imageMapDeps) if err != nil { return nil, errors.Wrapf(err, "getting image build info for %s", r.name) } for i, iTarget := range iTargets { if liveupdate.IsEmptySpec(iTarget.LiveUpdateSpec) { continue } iTarget.LiveUpdateReconciler = true iTargets[i] = iTarget } m = m.WithImageTargets(iTargets) k8sTarget, err := s.k8sDeployTarget(mn.TargetName(), r, iTargets, updateSettings) if err != nil { return nil, errors.Wrapf(err, "creating K8s deploy target for %s", r.name) } m = m.WithDeployTarget(k8sTarget) result = append(result, m) } err := maybeRestartContainerDeprecationError(result) if err != nil { return nil, err } return result, nil } func (s *tiltfileState) k8sDeployTarget(targetName model.TargetName, r *k8sResource, imageTargets []model.ImageTarget, updateSettings model.UpdateSettings) (model.K8sTarget, error) { var kdTemplateSpec *v1alpha1.KubernetesDiscoveryTemplateSpec if len(r.extraPodSelectors) != 0 { kdTemplateSpec = &v1alpha1.KubernetesDiscoveryTemplateSpec{ ExtraSelectors: k8s.SetsAsLabelSelectors(r.extraPodSelectors), } } sinceTime := apis.NewTime(pkgInitTime) applySpec := v1alpha1.KubernetesApplySpec{ Cluster: v1alpha1.ClusterNameDefault, Timeout: metav1.Duration{Duration: updateSettings.K8sUpsertTimeout()}, PortForwardTemplateSpec: k8s.PortForwardTemplateSpec(s.defaultedPortForwards(r.portForwards)), DiscoveryStrategy: r.discoveryStrategy, KubernetesDiscoveryTemplateSpec: kdTemplateSpec, PodLogStreamTemplateSpec: &v1alpha1.PodLogStreamTemplateSpec{ SinceTime: &sinceTime, IgnoreContainers: []string{ string(container.IstioInitContainerName), string(container.IstioSidecarContainerName), string(container.LinkerdSidecarContainerName), string(container.LinkerdInitContainerName), }, }, } var deps []string var ignores []v1alpha1.IgnoreDef if r.customDeploy != nil { deps = r.customDeploy.deps ignores = append(ignores, model.DockerignoresToIgnores(r.customDeploy.ignores)...) applySpec.ApplyCmd = toKubernetesApplyCmd(r.customDeploy.applyCmd) applySpec.DeleteCmd = toKubernetesApplyCmd(r.customDeploy.deleteCmd) applySpec.RestartOn = &v1alpha1.RestartOnSpec{ FileWatches: []string{apis.SanitizeName(fmt.Sprintf("%s:apply", targetName.String()))}, } } else { entities := k8s.SortedEntities(r.entities) var err error applySpec.YAML, err = k8s.SerializeSpecYAML(entities) if err != nil { return model.K8sTarget{}, err } for _, locator := range s.k8sImageLocatorsList() { if k8s.LocatorMatchesOne(locator, entities) { applySpec.ImageLocators = append(applySpec.ImageLocators, locator.ToSpec()) } } } ignores = append(ignores, repoIgnoresForPaths(deps)...) t, err := k8s.NewTarget(targetName, applySpec, s.inferPodReadinessMode(r), r.links) if err != nil { return model.K8sTarget{}, err } t = t.WithImageDependencies(model.FilterLiveUpdateOnly(r.imageMapDeps, imageTargets)). WithRefInjectCounts(r.imageRefInjectCounts()). WithPathDependencies(deps). WithIgnores(ignores) return t, nil } // Fill in default values in port-forwarding. // // In Kubernetes, "defaulted" is used as a verb to say "if a YAML value of a specification // was left blank, the API server should fill in the value with a default". See: // // https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/#default-field-values // // In Tilt, we typically do this in the Tiltfile loader post-execution. // Here, we default the port-forward Host to the WebHost. // // TODO(nick): I think the "right" way to do this is to give the starkit plugin system // a "default"-ing hook that runs post-execution. func (s *tiltfileState) defaultedPortForwards(pfs []model.PortForward) []model.PortForward { result := make([]model.PortForward, 0, len(pfs)) for _, pf := range pfs { if pf.Host == "" { pf.Host = string(s.webHost) } result = append(result, pf) } return result } func (s *tiltfileState) validateLiveUpdatesForManifests(manifests []model.Manifest) error { for _, m := range manifests { err := s.validateLiveUpdatesForManifest(m) if err != nil { return err } } return nil } // validateLiveUpdatesForManifest checks any image targets on the // given manifest the contain any illegal LiveUpdates func (s *tiltfileState) validateLiveUpdatesForManifest(m model.Manifest) error { g, err := model.NewTargetGraph(m.TargetSpecs()) if err != nil { return err } for _, iTarg := range m.ImageTargets { isDeployed := m.IsImageDeployed(iTarg) // This check only applies to images with live updates. if liveupdate.IsEmptySpec(iTarg.LiveUpdateSpec) { continue } // TODO(nick): If an undeployed base image has a live-update component, we // should probably emit a different kind of warning. if !isDeployed { continue } err = s.validateLiveUpdate(iTarg, g) if err != nil { return err } } return nil } func (s *tiltfileState) validateLiveUpdate(iTarget model.ImageTarget, g model.TargetGraph) error { luSpec := iTarget.LiveUpdateSpec if liveupdate.IsEmptySpec(luSpec) { return nil } var watchedPaths []string err := g.VisitTree(iTarget, func(t model.TargetSpec) error { current, ok := t.(model.ImageTarget) if !ok { return nil } watchedPaths = append(watchedPaths, current.Dependencies()...) return nil }) if err != nil { return err } // Verify that all a) sync step src's and b) fall_back_on files are children of a watched paths. // (If not, we'll never even get "file changed" events for them--they're nonsensical input, throw an error.) for _, sync := range liveupdate.SyncSteps(luSpec) { if !ospath.IsChildOfOne(watchedPaths, sync.LocalPath) { return fmt.Errorf("sync step source '%s' is not a child of any watched filepaths (%v)", sync.LocalPath, watchedPaths) } } pathSet := liveupdate.FallBackOnFiles(luSpec) for _, path := range pathSet.Paths { resolved := path if !filepath.IsAbs(resolved) { resolved = filepath.Join(pathSet.BaseDirectory, path) } if !ospath.IsChildOfOne(watchedPaths, resolved) { return fmt.Errorf("fall_back_on paths '%s' is not a child of any watched filepaths (%v)", resolved, watchedPaths) } } return nil } func (s *tiltfileState) validateDockerComposeVersion() error { const minimumDockerComposeVersion = "v1.28.3" dcVersion, _, err := s.dcCli.Version(s.ctx) if err != nil { logger.Get(s.ctx).Debugf("Failed to determine Docker Compose version: %v", err) } else if semver.Compare(dcVersion, minimumDockerComposeVersion) == -1 { return fmt.Errorf( "Tilt requires Docker Compose %s+ (you have %s). Please upgrade and re-launch Tilt.", minimumDockerComposeVersion, dcVersion) } else if semver.Major(dcVersion) == "v2" && semver.Compare(dcVersion, "v2.2") < 0 { logger.Get(s.ctx).Warnf("Using Docker Compose %s (version < 2.2) may result in errors or broken functionality.\n"+ "For best results, we recommend upgrading to Docker Compose >= v2.2.0.", dcVersion) } return nil } func maybeRestartContainerDeprecationError(manifests []model.Manifest) error { var needsError []model.ManifestName for _, m := range manifests { if needsRestartContainerDeprecationError(m) { needsError = append(needsError, m.Name) } } if len(needsError) > 0 { return fmt.Errorf("%s", restartContainerDeprecationError(needsError)) } return nil } func needsRestartContainerDeprecationError(m model.Manifest) bool { // 7/2/20: we've deprecated restart_container() in favor of the restart_process plugin. // If this is a k8s resource with a restart_container step, throw a deprecation error. // (restart_container is still allowed for Docker Compose resources) if !m.IsK8s() { return false } for _, iTarg := range m.ImageTargets { if liveupdate.ShouldRestart(iTarg.LiveUpdateSpec) { return true } } return false } // Grabs all image targets for the given references, // as well as any of their transitive dependencies. func (s *tiltfileState) imgTargetsForDeps(mn model.ManifestName, imageMapDeps []string) ([]model.ImageTarget, error) { claimStatus := make(map[string]claim, len(imageMapDeps)) return s.imgTargetsForDepsHelper(mn, imageMapDeps, claimStatus) } func (s *tiltfileState) imgTargetsForDepsHelper(mn model.ManifestName, imageMapDeps []string, claimStatus map[string]claim) ([]model.ImageTarget, error) { iTargets := make([]model.ImageTarget, 0, len(imageMapDeps)) for _, imName := range imageMapDeps { image := s.buildIndex.findBuilderByImageMapName(imName) if image == nil { return nil, fmt.Errorf("Internal error: no image builder found for id %s", imName) } claim := claimStatus[imName] if claim == claimFinished { // Skip this target, an earlier call has already built it continue } else if claim == claimPending { return nil, fmt.Errorf("Image dependency cycle: %s", image.configurationRef) } claimStatus[imName] = claimPending var overrideCommand *v1alpha1.ImageMapOverrideCommand if !image.entrypoint.Empty() { overrideCommand = &v1alpha1.ImageMapOverrideCommand{ Command: image.entrypoint.Argv, } } iTarget := model.ImageTarget{ ImageMapSpec: v1alpha1.ImageMapSpec{ Selector: image.configurationRef.RefFamiliarString(), MatchInEnvVars: image.matchInEnvVars, MatchExact: image.configurationRef.MatchExact(), OverrideCommand: overrideCommand, OverrideArgs: image.overrideArgs, }, LiveUpdateSpec: image.liveUpdate, } if !liveupdate.IsEmptySpec(image.liveUpdate) { iTarget.LiveUpdateName = liveupdate.GetName(mn, iTarget.ID()) } contextIgnores, fileWatchIgnores, err := s.ignoresForImage(image) if err != nil { return nil, err } switch image.Type() { case DockerBuild: iTarget.DockerImageName = dockerimage.GetName(mn, iTarget.ID()) spec := v1alpha1.DockerImageSpec{ DockerfileContents: image.dbDockerfile.String(), Context: image.dbBuildPath, Args: image.dbBuildArgs, Target: image.targetStage, SSHAgentConfigs: image.sshSpecs, Secrets: image.secretSpecs, Network: image.network, CacheFrom: image.cacheFrom, Pull: image.pullParent, Platform: image.platform, ExtraTags: image.extraTags, ContextIgnores: contextIgnores, ExtraHosts: image.extraHosts, } iTarget = iTarget.WithBuildDetails(model.DockerBuild{DockerImageSpec: spec}) case CustomBuild: iTarget.CmdImageName = cmdimage.GetName(mn, iTarget.ID()) spec := v1alpha1.CmdImageSpec{ Args: image.customCommand.Argv, Dir: image.workDir, OutputTag: image.customTag, OutputsImageRefTo: image.outputsImageRefTo, } if image.skipsLocalDocker { spec.OutputMode = v1alpha1.CmdImageOutputRemote } else if image.disablePush { spec.OutputMode = v1alpha1.CmdImageOutputLocalDockerAndRemote } else { spec.OutputMode = v1alpha1.CmdImageOutputLocalDocker } r := model.CustomBuild{ CmdImageSpec: spec, Deps: image.customDeps, } iTarget = iTarget.WithBuildDetails(r) case DockerComposeBuild: bd := model.DockerComposeBuild{ Service: image.dockerComposeService, Context: image.dbBuildPath, } iTarget = iTarget.WithBuildDetails(bd) case UnknownBuild: return nil, fmt.Errorf("no build info for image %s", image.configurationRef.RefFamiliarString()) } iTarget = iTarget.WithImageMapDeps(image.imageMapDeps). WithFileWatchIgnores(fileWatchIgnores) depTargets, err := s.imgTargetsForDepsHelper(mn, image.imageMapDeps, claimStatus) if err != nil { return nil, err } iTargets = append(iTargets, depTargets...) iTargets = append(iTargets, iTarget) claimStatus[imName] = claimFinished } return iTargets, nil } func (s *tiltfileState) translateDC(dc *dcResourceSet) ([]model.Manifest, error) { var result []model.Manifest for _, name := range dc.serviceNames { svc := dc.services[name] iTargets, err := s.imgTargetsForDeps(model.ManifestName(svc.Name), svc.ImageMapDeps) if err != nil { return nil, errors.Wrapf(err, "getting image build info for %s", svc.Name) } for _, iTarg := range iTargets { if iTarg.OverrideCommand != nil { return nil, fmt.Errorf("docker_build/custom_build.entrypoint not supported for Docker Compose resources") } } m, err := s.dcServiceToManifest(svc, dc, iTargets) if err != nil { return nil, err } result = append(result, m) } return result, nil } type claim int const ( claimNone claim = iota claimPending claimFinished ) var _ claim = claimNone func (s *tiltfileState) triggerModeFn(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var triggerMode triggerMode err := s.unpackArgs(fn.Name(), args, kwargs, "trigger_mode", &triggerMode) if err != nil { return nil, err } if s.triggerModeCallPosition.IsValid() { return starlark.None, fmt.Errorf("%s can only be called once. It was already called at %s", fn.Name(), s.triggerModeCallPosition.String()) } s.triggerMode = triggerMode s.triggerModeCallPosition = thread.CallFrame(1).Pos return starlark.None, nil } func (s *tiltfileState) setTeam(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var teamID string err := s.unpackArgs(fn.Name(), args, kwargs, "team_id", &teamID) if err != nil { return nil, err } if len(teamID) == 0 { return nil, errors.New("team_id cannot be empty") } if s.teamID != "" { return nil, fmt.Errorf("team_id set multiple times (to '%s' and '%s')", s.teamID, teamID) } s.teamID = teamID return starlark.None, nil } func (s *tiltfileState) translateLocal() ([]model.Manifest, error) { var result []model.Manifest for _, r := range s.localResources { mn := model.ManifestName(r.name) tm, err := starlarkTriggerModeToModel(s.triggerModeForResource(r.triggerMode), r.autoInit) if err != nil { return nil, errors.Wrapf(err, "error in resource %s options", mn) } paths := append([]string{}, r.deps...) paths = append(paths, r.threadDir) ignores := repoIgnoresForPaths(paths) if len(r.ignores) != 0 { ignores = append(ignores, v1alpha1.IgnoreDef{ BasePath: r.threadDir, Patterns: r.ignores, }) } lt := model.NewLocalTarget(model.TargetName(r.name), r.updateCmd, r.serveCmd, r.deps). WithAllowParallel(r.allowParallel || r.updateCmd.Empty()). WithLinks(r.links). WithReadinessProbe(r.readinessProbe) lt.FileWatchIgnores = ignores var mds []model.ManifestName for _, md := range r.resourceDeps { mds = append(mds, model.ManifestName(md)) } m := model.Manifest{ Name: mn, TriggerMode: tm, ResourceDependencies: mds, }.WithDeployTarget(lt) m = m.WithLabels(r.labels) result = append(result, m) } return result, nil } func (s *tiltfileState) tempDir() (*fwatch.TempDir, error) { if s.scratchDir == nil { dir, err := fwatch.NewDir("tiltfile") if err != nil { return dir, err } s.scratchDir = dir go func() { <-s.ctx.Done() _ = s.scratchDir.TearDown() }() } return s.scratchDir, nil } func (s *tiltfileState) sanitizeDependencies(ms []model.Manifest) error { // warn + delete resource deps that don't exist // error if resource deps are not a DAG knownResources := make(map[model.ManifestName]bool) for _, m := range ms { knownResources[m.Name] = true } // construct the graph and make sure all edges are valid edges := make(map[interface{}][]interface{}) for i, m := range ms { var sanitizedDeps []model.ManifestName for _, b := range m.ResourceDependencies { if m.Name == b { return fmt.Errorf("resource %s specified a dependency on itself", m.Name) } if _, ok := knownResources[b]; !ok { logger.Get(s.ctx).Warnf("resource %s specified a dependency on unknown resource %s - dependency ignored", m.Name, b) continue } edges[m.Name] = append(edges[m.Name], b) sanitizedDeps = append(sanitizedDeps, b) } m.ResourceDependencies = sanitizedDeps ms[i] = m } // check for cycles connections := tarjan.Connections(edges) for _, g := range connections { if len(g) > 1 { var nodes []string for i := range g { nodes = append(nodes, string(g[len(g)-i-1].(model.ManifestName))) } nodes = append(nodes, string(g[len(g)-1].(model.ManifestName))) return fmt.Errorf("cycle detected in resource dependency graph: %s", strings.Join(nodes, " -> ")) } } return nil } func toKubernetesApplyCmd(cmd model.Cmd) *v1alpha1.KubernetesApplyCmd { if cmd.Empty() { return nil } return &v1alpha1.KubernetesApplyCmd{ Args: cmd.Argv, Dir: cmd.Dir, Env: cmd.Env, } } func (s *tiltfileState) ignoresForImage(image *dockerImage) (contextIgnores []v1alpha1.IgnoreDef, fileWatchIgnores []v1alpha1.IgnoreDef, err error) { dockerignores, err := s.dockerignoresForImage(image) if err != nil { return nil, nil, fmt.Errorf("reading dockerignore for %s: %v", image.configurationRef.RefFamiliarString(), err) } if image.tiltfilePath != "" { contextIgnores = append(contextIgnores, v1alpha1.IgnoreDef{BasePath: image.tiltfilePath}) } contextIgnores = append(contextIgnores, s.repoIgnoresForImage(image)...) contextIgnores = append(contextIgnores, model.DockerignoresToIgnores(dockerignores)...) for i := range contextIgnores { fileWatchIgnores = append(fileWatchIgnores, *contextIgnores[i].DeepCopy()) } if image.dbDockerfilePath != "" { // while this might seem unusual, we actually do NOT want the // ImageTarget to watch the Dockerfile itself because the image // builder does not actually use the Dockerfile on-disk! instead, // the Tiltfile watches the Dockerfile and always reads it in as // part of execution, storing the full contents in the ImageTarget // so that we can rewrite it in memory to inject image references // and more // as a result, if BOTH the Tiltfile and the ImageTarget watch the // Dockerfile, it'll result in a race condition, as the ImageTarget // build might see the change first and re-execute _before_ the // Tiltfile, meaning it's running with a stale version of the // Dockerfile fileWatchIgnores = append(fileWatchIgnores, v1alpha1.IgnoreDef{BasePath: image.dbDockerfilePath}) } if image.Type() == DockerComposeBuild { // Docker Compose local volumes are mounted into the running container, // so we don't want to watch these paths, as that'd trigger rebuilds // instead of the desired Live Update-ish behavior // note that they ARE eligible for usage within the Docker context, as // it's a common pattern to include some files (e.g. config) in the // image but then mount a local volume on top of it for local dev for _, p := range image.dockerComposeLocalVolumePaths { fileWatchIgnores = append(fileWatchIgnores, v1alpha1.IgnoreDef{BasePath: p}) } } return } var _ starkit.Plugin = &tiltfileState{} var _ starkit.OnExecPlugin = &tiltfileState{} var _ starkit.OnBuiltinCallPlugin = &tiltfileState{}
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "chromiumos/tast/common/fixture" "chromiumos/tast/common/pci" "chromiumos/tast/common/policy" "chromiumos/tast/common/policy/fakedms" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/faillog" "chromiumos/tast/local/chrome/uiauto/nodewith" "chromiumos/tast/local/chrome/uiauto/role" "chromiumos/tast/local/policyutil" "chromiumos/tast/testing" "chromiumos/tast/testing/hwdep" ) func init() { testing.AddTest(&testing.Test{ Func: ScreenBrightnessPercent, LacrosStatus: testing.LacrosVariantUnneeded, Desc: "Test behavior of ScreenBrightnessPercent policy: check if the screen brightness matches the value of the policy", Contacts: []string{ "alexanderhartl@google.com", // Test author }, HardwareDeps: hwdep.D(hwdep.InternalDisplay()), // no_qemu: VMs don't support brightness control. SoftwareDeps: []string{"chrome", "no_qemu"}, Attr: []string{"group:mainline"}, Fixture: fixture.ChromePolicyLoggedIn, SearchFlags: []*testing.StringPair{ pci.SearchFlag(&policy.ScreenBrightnessPercent{}, pci.VerifiedFunctionalityUI), }, }) } func ScreenBrightnessPercent(ctx context.Context, s *testing.State) { cr := s.FixtValue().(chrome.HasChrome).Chrome() fdms := s.FixtValue().(fakedms.HasFakeDMS).FakeDMS() // Connect to Test API to use it with the UI library. tconn, err := cr.TestAPIConn(ctx) if err != nil { s.Fatal("Failed to create Test API connection: ", err) } for _, param := range []struct { name string wantBrightness string // wantBrightness is the expected brightness value. policy *policy.ScreenBrightnessPercent // policy is the policy we test. }{ { name: "brightness_1", wantBrightness: "83%", policy: &policy.ScreenBrightnessPercent{ Val: &policy.ScreenBrightnessPercentValue{ BrightnessAC: 83, BrightnessBattery: 83, }, }, }, { name: "brightness_2", wantBrightness: "47%", policy: &policy.ScreenBrightnessPercent{ Val: &policy.ScreenBrightnessPercentValue{ BrightnessAC: 47, BrightnessBattery: 47, }, }, }, { name: "unset", wantBrightness: "47%", // In the unset case the last set brightness is expected. policy: &policy.ScreenBrightnessPercent{Stat: policy.StatusUnset}, }, } { s.Run(ctx, param.name, func(ctx context.Context, s *testing.State) { defer faillog.DumpUITreeWithScreenshotOnError(ctx, s.OutDir(), s.HasError, cr, "ui_tree_"+param.name) // Perform cleanup. if err := policyutil.ResetChrome(ctx, fdms, cr); err != nil { s.Fatal("Failed to clean up: ", err) } // Update policies. if err := policyutil.ServeAndVerify(ctx, fdms, cr, []policy.Policy{param.policy}); err != nil { s.Fatal("Failed to update policies: ", err) } ui := uiauto.New(tconn) // Find the Status unifided system tray node and click to open it. statusTray := nodewith.ClassName("UnifiedSystemTray") if err := uiauto.Combine("find and click the status area unified system tray", ui.WaitUntilExists(statusTray), ui.LeftClick(statusTray), )(ctx); err != nil { s.Fatal("Failed to find and click the status area unified system tray: ", err) } defer func() { // Close the Status tray again, otherwise the next subtest won't find it. if err := ui.LeftClick(statusTray)(ctx); err != nil { s.Fatal("Failed to close Status tray: ", err) } }() // Get the NodeInfo of the Brightness slider. brightnessSlider := nodewith.Name("Brightness").Role(role.Slider) sliderInfo, err := ui.Info(ctx, brightnessSlider) if err != nil { s.Fatal("Failed to find Brightness slider: ", err) } if sliderInfo.Value != param.wantBrightness { s.Errorf("Unexpected brightness set: got %s; want %s", sliderInfo.Value, param.wantBrightness) } }) } }
package enum_generator import ( "github.com/morlay/gin-swagger/codegen" "github.com/morlay/gin-swagger/program" "github.com/morlay/gin-swagger/swagger" "go/types" "path/filepath" "strings" ) func NewEnumGenerator(packagePath string) *EnumGenerator { prog := program.NewProgram(packagePath) return &EnumGenerator{ PackagePath: packagePath, Program: prog, } } type Option struct { Value string Label string } type Enum struct { Name string Type string Pathname string PackageName string Values []Option } type EnumGenerator struct { PackagePath string Program *program.Program Enums []Enum } func (g *EnumGenerator) addEnum(name string, tpe string, pkg *types.Package, enumOptions []program.Option) { if g.Enums == nil { g.Enums = []Enum{} } options := []Option{} for _, option := range enumOptions { switch option.Value.(type) { case string: options = append(options, Option{ Value: option.Value.(string), Label: option.Label, }) } } if len(options) > 0 { g.Enums = append(g.Enums, Enum{ Name: name, Type: tpe, Pathname: pkg.Path(), PackageName: pkg.Name(), Values: options, }) } } func (g *EnumGenerator) Scan() { for _, pkgInfo := range g.Program.AllPackages { if program.IsSubPackageOf(g.PackagePath, pkgInfo.Pkg.Path()) { for id, def := range pkgInfo.Defs { doc := program.GetTextFromCommentGroup(g.Program.CommentGroupFor(id)) _, hasEnum := swagger.ParseEnum(doc) if hasEnum { options := g.Program.GetEnumOptionsByType(id) g.addEnum( def.Name(), def.Type().Underlying().String(), def.Pkg(), options, ) } } } } } func (g *EnumGenerator) Output() { g.Scan() for _, enum := range g.Enums { relPath, _ := filepath.Rel(g.PackagePath, enum.Pathname) name := strings.Replace(codegen.ToLowerSnakeCase(enum.Name), "_", " ", -1) blocks := []string{ codegen.DeclPackage(enum.PackageName), codegen.DeclImports("errors", "strings"), codegen.DeclVar("Invalid"+enum.Name, `errors.New("invalid `+name+`")`), ParseEnumStringify(enum), ParseEnumParser(enum), ParseEnumJSONMarshal(enum), } codegen.WriteGoFile( codegen.JoinWithSlash(relPath, codegen.ToLowerSnakeCase("generated_"+enum.Name)+".go"), strings.Join(blocks, "\n\n"), ) } } func ParseEnumParser(enum Enum) string { firstLine := codegen.TemplateRender(`func Parse{{ .Name }}FromString(s string) ({{ .Name }}, error) { switch s {`)(enum) var lines = []string{ firstLine, } prefix := codegen.ToUpperSnakeCase(enum.Name) lines = append(lines, codegen.DeclCase(codegen.WithQuotes(""))) lines = append(lines, codegen.DeclReturn(codegen.JoinWithComma(prefix+"_UNKNOWN", "nil"))) for _, option := range enum.Values { lines = append(lines, codegen.DeclCase(codegen.WithQuotes(option.Value))) lines = append(lines, codegen.DeclReturn(codegen.JoinWithComma(prefix+"__"+option.Value, "nil"))) } lines = append(lines, "}") lines = append(lines, codegen.DeclReturn(codegen.JoinWithComma(prefix+"_UNKNOWN", codegen.TemplateRender(`Invalid{{ .Name }}`)(enum)))) lines = append(lines, "}") return strings.Join(lines, "\n") } func ParseEnumStringify(enum Enum) string { firstLine := codegen.TemplateRender(`func (v {{ .Name }}) String() string { switch v {`)(enum) var lines = []string{ firstLine, } prefix := codegen.ToUpperSnakeCase(enum.Name) lines = append(lines, codegen.DeclCase(prefix+"_UNKNOWN")) lines = append(lines, codegen.DeclReturn(codegen.WithQuotes(""))) for _, option := range enum.Values { lines = append(lines, codegen.DeclCase(prefix+"__"+option.Value)) lines = append(lines, codegen.DeclReturn(codegen.WithQuotes(option.Value))) } lines = append(lines, `} return "UNKNOWN" }`) return strings.Join(lines, "\n") } func ParseEnumJSONMarshal(enum Enum) string { return codegen.TemplateRender(` func (v {{ .Name }}) MarshalJSON() ([]byte, error) { str := v.String() if str == "UNKNOWN" { return nil, Invalid{{ .Name }} } return []byte("\"" + str + "\""), nil } func (v *{{ .Name }}) UnmarshalJSON(data []byte) (err error) { s := strings.Trim(strings.ToUpper(string(data)), "\"") *v, err = Parse{{ .Name }}FromString(s) return }`)(enum) }
package infrastructure import ( "flag" "github.com/spf13/viper" "log" "path" "strings" ) type httpListen struct { Ip string Port int } type logs struct { PathToLogFile string Level string // it can be (error/warn/info/debug) } type db struct { Host string Port int Dbname string PoolMaxConns int Password string User string } type Configuration struct { HttpListen httpListen Logs logs DB db } func InitConfig() Configuration { var pathToConfigFile = flag.String("config", "", "path to configuration file") flag.Parse() if *pathToConfigFile != "" { dir := path.Dir(*pathToConfigFile) ext := path.Ext(*pathToConfigFile) base := strings.Replace(path.Base(*pathToConfigFile), ext, "", 1) viper.SetConfigName(base) viper.AddConfigPath(dir) viper.SetConfigType(ext[1:]) if err := viper.ReadInConfig(); err != nil { log.Fatalf("Error reading config file, %s", err) } } else { viper.SetDefault("HttpListen.Ip", "0.0.0.0") viper.SetDefault("HttpListen.Port", "8080") viper.SetDefault("Logs.PathToLogFile", "all.log") viper.SetDefault("Logs.Level", "debug") } var configuration Configuration if err := viper.Unmarshal(&configuration); err != nil { log.Fatalf("unable to decode into struct, %v", err) } return configuration }
package removeelement func removeElement(nums []int, val int) int { var count int // 重复 val 个数 for i := 0; i < len(nums); { if nums[i] == val { count++ if i == len(nums)-1 { // 最后一个元素也等于 val nums = append(nums[:i-count+1]) } } else { if count != 0 { nums = append(nums[:i-count], nums[i:]...) i = i - count // 更新 i count = 0 continue } } i++ } return len(nums) }
/* Sudoku Solver Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. */ package main // 位图检测+回溯法 func solveSudoku(board [][]byte) { if len(board) != 9 || len(board[0]) != 9 { return } col := make([]uint16,9) row := make([]uint16,9) square := make([]uint16,9) empty := make([]uint16,9) // 初始化冲突位图 for i,v := range board { for j,val := range v { if val == '.' { empty[i] |= 1 << uint(j) continue } idx := uint16(1 << (val - '0')) if col[j] & idx != uint16(0) || row[i] & idx != uint16(0) || square[i / 3 * 3 + j / 3] & idx != uint16(0) { return } col[j] |= idx row[i] |= idx square[i / 3 * 3 + j / 3] |= idx } } solve(board,empty,col,row,square,0) } // 回溯法递归解决数独问题 func solve(board [][]byte, empty, col, row, square []uint16, cur int) bool { for i := cur;i < 81;i ++ { r,c := i / 9,i % 9 if empty[r] & (1 << uint(c)) == uint16(0) { continue } s := r / 3 * 3 + c / 3 for v := 1;v <= 9;v++ { idx := uint16(1 << uint(v)) if col[c] & idx == uint16(0) && row[r] & idx == uint16(0) && square[s] & idx == uint16(0) { col[c] |= idx row[r] |= idx square[s] |= idx board[r][c] = byte('0' + v) if solve(board, empty, col, row, square, i+1) { return true } col[c] ^= idx row[r] ^= idx square[s] ^= idx } } return false } return true } func sudokuPrint(x [][]byte) { for i,v := range x { if i % 3 == 0 { fmt.Println(" -----------------") } for j, val := range v { if j % 3 == 0 { fmt.Print("|") } else { fmt.Print(" ") } fmt.Print(string(val)) } fmt.Println("|") } fmt.Println(" -----------------") }
package editors type ( // Taskfile wraps task list output for use in editor integrations (e.g. VSCode, etc) Taskfile struct { Tasks []Task `json:"tasks"` Location string `json:"location"` } // Task describes a single task Task struct { Name string `json:"name"` Desc string `json:"desc"` Summary string `json:"summary"` UpToDate bool `json:"up_to_date"` Location *Location `json:"location"` } // Location describes a task's location in a taskfile Location struct { Line int `json:"line"` Column int `json:"column"` Taskfile string `json:"taskfile"` } )
package main import "testing" func TestParse(t *testing.T) { values := loadData("test_input.txt") _, root := parseData(values, 0) if len(root.children) != 2 { t.Errorf("Root should have 2 children, found %v.", len(root.children)) } if len(root.metadata) != 3 { t.Errorf("Root should have 3 metadata, found %v.", len(root.metadata)) } if len(root.children[0].children) != 0 { t.Errorf("First child of root should have 0 children, found %v.", len(root.children[0].children)) } if len(root.children[0].metadata) != 3 { t.Errorf("First child of root should have 3 metadata, found %v.", len(root.children[0].metadata)) } if len(root.children[1].children) != 1 { t.Errorf("Second child of root should have 1 children, found %v.", len(root.children[1].children)) } if len(root.children[1].metadata) != 1 { t.Errorf("Second child of root should have 1 metadata, found %v.", len(root.children[1].children)) } if len(root.children[1].children[0].children) != 0 { t.Errorf("Child of second child of root should have 0 children, found %v.", len(root.children[1].children[0].children)) } if len(root.children[1].children[0].metadata) != 1 { t.Errorf("Child of second child of root should have 1 metadata, found %v.", len(root.children[1].children[0].metadata)) } if root.MetadataSum() != 138 { t.Errorf("Metadata sum %v is not equal to 138.", root.MetadataSum()) } } func TestPart2(t *testing.T) { values := loadData("test_input.txt") _, root := parseData(values, 0) if root.Value() != 66 { t.Errorf("Root value should be 66, got %v.", root.Value()) } }
package main import ( "strconv" "fmt" ) func convertFormat(input string) string { sh := input[0:2] part := input[8:10] hour, _ := strconv.Atoi(sh) if part == "PM" && hour != 12 { hour += 12 } else if part == "AM" && hour == 12 { hour = 0 } return fmt.Sprintf("%02d%s", hour, input[2:8]) } func main() { var s string fmt.Scan(&s) fmt.Println(convertFormat(s)) }
package main import "github.com/sadasant/scripts/go/euler/euler" func solution(n int) int { var s int for i := 0; i < n; i++ { if i%3*i%5 == 0 { s += i } } return s } func main() { euler.Init(1, "Find the sum of all the multiples of 3 or 5 below 1000.") euler.PrintTime("Result: %v, Nanoseconds: %d\n", solution, 1000) }
../src0/base_1529__tcpBufMachine__irun.go
package client import ( "context" "fmt" "log" "github.com/piotrkira/microservices-calc/muldiv/endpoints" "google.golang.org/grpc" ) type Client struct { cli endpoints.MulDivClient } func New(serverAddres string) *Client { client := Client{} connection, err := grpc.Dial(fmt.Sprintf("%s:7777", serverAddres), grpc.WithInsecure()) if err != nil { log.Fatal(err) } client.cli = endpoints.NewMulDivClient(connection) return &client } func (c *Client) Mul(a, b int64) (string, error) { res, err := c.cli.Mul(context.Background(), &endpoints.Numbers{A: a, B: b}) if err != nil { log.Println(err) return "", err } return res.Content, nil } func (c *Client) Div(a, b int64) (string, error) { res, err := c.cli.Div(context.Background(), &endpoints.Numbers{A: a, B: b}) if err != nil { log.Println(err) return "", err } return res.Content, nil }
package log import ( "fmt" "github.com/project-flogo/core/activity" "github.com/project-flogo/core/data/coerce" ) func init() { _ = activity.Register(&Activity{}) } type Input struct { Message string `md:"message"` // The message to log AddDetails bool `md:"addDetails"` // Append contextual execution information to the log message UsePrint bool `md:"usePrint"` } func (i *Input) ToMap() map[string]interface{} { return map[string]interface{}{ "message": i.Message, "addDetails": i.AddDetails, "usePrint": i.UsePrint, } } func (i *Input) FromMap(values map[string]interface{}) error { var err error i.Message, err = coerce.ToString(values["message"]) if err != nil { return err } i.AddDetails, err = coerce.ToBool(values["addDetails"]) if err != nil { return err } i.UsePrint, err = coerce.ToBool(values["usePrint"]) if err != nil { return err } return nil } var activityMd = activity.ToMetadata(&Input{}) // Activity is an Activity that is used to log a message to the console // inputs : {message, flowInfo} // outputs: none type Activity struct { } // Metadata returns the activity's metadata func (a *Activity) Metadata() *activity.Metadata { return activityMd } // Eval implements api.Activity.Eval - Logs the Message func (a *Activity) Eval(ctx activity.Context) (done bool, err error) { input := &Input{} ctx.GetInputObject(input) msg := input.Message if input.AddDetails { msg = fmt.Sprintf("'%s' - HostID [%s], HostName [%s], Activity [%s]", msg, ctx.ActivityHost().ID(), ctx.ActivityHost().Name(), ctx.Name()) } if input.UsePrint { fmt.Println(msg) } else { ctx.Logger().Info(msg) } return true, nil }
package dockercomposeservice import ( "context" "testing" "time" dtypes "github.com/docker/docker/api/types" "github.com/jonboulle/clockwork" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/tilt-dev/tilt/internal/controllers/apicmp" "github.com/tilt-dev/tilt/internal/controllers/fake" "github.com/tilt-dev/tilt/internal/docker" "github.com/tilt-dev/tilt/internal/dockercompose" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/internal/store/dockercomposeservices" "github.com/tilt-dev/tilt/internal/testutils/manifestbuilder" "github.com/tilt-dev/tilt/internal/testutils/tempdir" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" ) func TestImageIndexing(t *testing.T) { f := newFixture(t) obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "a", }, Spec: v1alpha1.DockerComposeServiceSpec{ ImageMaps: []string{"image-a", "image-c"}, }, } f.Create(&obj) // Verify we can index one image map. reqs := f.r.indexer.Enqueue(context.Background(), &v1alpha1.ImageMap{ObjectMeta: metav1.ObjectMeta{Name: "image-a"}}) assert.ElementsMatch(t, []reconcile.Request{ {NamespacedName: types.NamespacedName{Name: "a"}}, }, reqs) } func TestForceApply(t *testing.T) { f := newFixture(t) nn := types.NamespacedName{Name: "fe"} obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "fe", Annotations: map[string]string{ v1alpha1.AnnotationManagedBy: "buildcontrol", }, }, Spec: v1alpha1.DockerComposeServiceSpec{ Service: "fe", Project: v1alpha1.DockerComposeProject{ YAML: "fake-yaml", }, }, } f.Create(&obj) f.MustReconcile(nn) f.MustGet(nn, &obj) assert.True(t, obj.Status.LastApplyStartTime.IsZero()) status := f.r.ForceApply(f.Context(), nn, obj.Spec, nil, false) assert.False(t, status.LastApplyStartTime.IsZero()) assert.Equal(t, "", status.ApplyError) assert.Equal(t, true, status.ContainerState.Running) f.MustReconcile(nn) f.MustGet(nn, &obj) assert.True(t, apicmp.DeepEqual(status, obj.Status)) f.assertSteadyState(&obj) } func TestAutoApply(t *testing.T) { f := newFixture(t) nn := types.NamespacedName{Name: "fe"} obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "fe", }, Spec: v1alpha1.DockerComposeServiceSpec{ Service: "fe", Project: v1alpha1.DockerComposeProject{ YAML: "fake-yaml", }, }, } f.Create(&obj) f.MustReconcile(nn) f.MustGet(nn, &obj) assert.False(t, obj.Status.LastApplyStartTime.IsZero()) assert.Equal(t, "", obj.Status.ApplyError) assert.Equal(t, true, obj.Status.ContainerState.Running) f.assertSteadyState(&obj) } func TestLogObject(t *testing.T) { f := newFixture(t) nn := types.NamespacedName{Name: "fe"} obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "fe", }, Spec: v1alpha1.DockerComposeServiceSpec{ Service: "fe", Project: v1alpha1.DockerComposeProject{ YAML: "fake-yaml", }, }, } f.Create(&obj) f.MustReconcile(nn) f.MustGet(nn, &obj) var log v1alpha1.DockerComposeLogStream f.MustGet(nn, &log) assert.False(t, obj.Status.LastApplyStartTime.IsZero()) assert.Equal(t, "fe", log.Spec.Service) assert.Equal(t, "fake-yaml", log.Spec.Project.YAML) _, _ = f.Delete(&obj) assert.False(t, f.Get(nn, &log)) } func TestContainerEvent(t *testing.T) { f := newFixture(t) nn := types.NamespacedName{Name: "fe"} obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "fe", Annotations: map[string]string{ v1alpha1.AnnotationManifest: "fe", }, }, Spec: v1alpha1.DockerComposeServiceSpec{ Service: "fe", Project: v1alpha1.DockerComposeProject{ YAML: "fake-yaml", }, }, } f.Create(&obj) status := f.r.ForceApply(f.Context(), nn, obj.Spec, nil, false) assert.Equal(t, "", status.ApplyError) assert.Equal(t, true, status.ContainerState.Running) container := dtypes.ContainerState{ Status: "exited", Running: false, ExitCode: 0, StartedAt: "2021-09-08T19:58:01.483005100Z", FinishedAt: "2021-09-08T19:58:01.483005100Z", } containerID := "my-container-id" f.dc.Containers[containerID] = container event := dockercompose.Event{Type: dockercompose.TypeContainer, ID: containerID, Service: "fe"} f.dcc.SendEvent(event) require.Eventually(t, func() bool { f.MustReconcile(nn) f.MustGet(nn, &obj) return obj.Status.ContainerState.Status == "exited" }, time.Second, 10*time.Millisecond, "container exited") assert.Equal(t, containerID, obj.Status.ContainerID) f.MustReconcile(nn) tmpf := tempdir.NewTempDirFixture(t) s := store.NewState() m := manifestbuilder.New(tmpf, "fe").WithDockerCompose().Build() s.UpsertManifestTarget(store.NewManifestTarget(m)) for _, action := range f.Store.Actions() { switch action := action.(type) { case dockercomposeservices.DockerComposeServiceUpsertAction: dockercomposeservices.HandleDockerComposeServiceUpsertAction(s, action) } } assert.Equal(t, "exited", s.ManifestTargets["fe"].State.DCRuntimeState().ContainerState.Status) } func TestForceDelete(t *testing.T) { f := newFixture(t) nn := types.NamespacedName{Name: "fe"} obj := v1alpha1.DockerComposeService{ ObjectMeta: metav1.ObjectMeta{ Name: "fe", Annotations: map[string]string{ v1alpha1.AnnotationManifest: "fe", }, }, Spec: v1alpha1.DockerComposeServiceSpec{ Service: "fe", Project: v1alpha1.DockerComposeProject{ YAML: "fake-yaml", }, }, } f.Create(&obj) err := f.r.ForceDelete(f.Context(), nn, obj.Spec, "testing") assert.Nil(f.T(), err) assert.Equal(f.T(), f.dcc.RmCalls()[0].Specs[0].Service, "fe") } type fixture struct { *fake.ControllerFixture r *Reconciler dc *docker.FakeClient dcc *dockercompose.FakeDCClient } func newFixture(t *testing.T) *fixture { cfb := fake.NewControllerFixtureBuilder(t) dcCli := dockercompose.NewFakeDockerComposeClient(t, cfb.Context()) dcCli.ContainerIDDefault = "fake-cid" dCli := docker.NewFakeClient() clock := clockwork.NewFakeClock() watcher := NewDisableSubscriber(cfb.Context(), dcCli, clock) r := NewReconciler(cfb.Client, dcCli, dCli, cfb.Store, v1alpha1.NewScheme(), watcher) return &fixture{ ControllerFixture: cfb.Build(r), r: r, dc: dCli, dcc: dcCli, } } func (f *fixture) assertSteadyState(s *v1alpha1.DockerComposeService) { f.T().Helper() f.MustReconcile(types.NamespacedName{Name: s.Name}) var s2 v1alpha1.DockerComposeService f.MustGet(types.NamespacedName{Name: s.Name}, &s2) assert.Equal(f.T(), s.ResourceVersion, s2.ResourceVersion) }
package majiangserver import ( //cmn "common" //"fmt" //"debug" "logger" "math" "sort" "time" ) const ( ESuccess = iota ECardNull ETypeAmountMuch ECardFullSame ) //胡牌类型 const ( DanDiaoHu = iota //单调胡 ShunZiHu //顺子胡 DuiChuHu //对处胡 ) //模式类型 const ( NormalPattern = iota //普通模式 DaDuiZiPattern //大对子 XiaoQiDuiPattern //小七对 ) type HuController struct { patternGroups []*MaJiangPatternGroup originCards []*MaJiangCard cards []*MaJiangCard rmCardsAmountInfo *CardAmountStatistics //替换模式下的卡牌数量 player *MaJiangPlayer } func NewHuController(p *MaJiangPlayer) *HuController { huC := &HuController{player: p} return huC } //初始化函数 ,调用完次函数后,就可以直接获取成员数据了 func (self *HuController) UpdateData(cards []*MaJiangCard) { //1.check input param if !self.CheckHandCardsAmount(cards) { //logger.Error("手牌数量有问题, 当前的手牌数量为:%d", len(cards)) return } player := self.player if player == nil { logger.Error("HuController.player is nil.") return } //2.need check hu logger.Info("更新胡:") if eReason := self.needUpdate(cards); eReason != ESuccess { logger.Info("不需要更新:", eReason) //当以前是能够胡牌的,但是摸了一张不同花色的牌导致现在有不能胡了要把以前的胡的模式组给清除掉 if eReason == ETypeAmountMuch { self.patternGroups = make([]*MaJiangPatternGroup, 0) self.originCards = make([]*MaJiangCard, len(cards)) copy(self.originCards, cards) } PrintPatternGroupsS("在进行胡控制器更新时,坚持到不需要更新,此时以前可以胡的模式组如下:", self.patternGroups, false) return } logger.Info("开始计算胡数") //3.cache card self.originCards = make([]*MaJiangCard, len(cards)) copy(self.originCards, cards) self.patternGroups = make([]*MaJiangPatternGroup, 0) //4.克隆一副手牌 clonedCards := CloneMaJiangCards(cards) //5.拆分出本牌和红中 normalCards, hongZhongCards := SplitCards(clonedCards) //6.根据手牌数量,生成素胡,打对子和小七对 self.GeneratePatternGroup(normalCards, len(hongZhongCards)) //7.打印最终的结果 PrintPatternGroupsS("最终结果:", self.patternGroups, true) } //检查是否需要重新算胡牌,牌没变化就用算了 func (self *HuController) needUpdate(cards []*MaJiangCard) int32 { //1. check input param if cards == nil { logger.Error("needUpdate:cards is nil.") return ECardNull } //2. check type amount if self.player != nil { fixedTypeList := self.player.GetTypeInfoInShowPattern() amountInfo := NewCardAmountStatisticsByCards(cards, false) typeAmount := amountInfo.GetTypeAmount(false, fixedTypeList) if typeAmount > int32(2-len(fixedTypeList)) { return ETypeAmountMuch } } //3. check card amount is same if len(self.originCards) != 0 && len(self.originCards) != len(cards) { return ESuccess } //4. check is same tempCards := make([]*MaJiangCard, len(cards)) copy(tempCards, cards) for _, v := range self.originCards { cType, cVal := v.CurValue() removedSuccess := true removedSuccess, tempCards = RemoveCardByType(tempCards, cType, cVal) if !removedSuccess { return ESuccess } } isSame := len(tempCards) <= 0 if isSame { return ECardFullSame } return ESuccess } //检查手牌数量是否正确 func (self *HuController) CheckHandCardsAmount(cards []*MaJiangCard) bool { if cards == nil { return false } cardAmount := len(cards) return !(cardAmount != 13 && cardAmount != 10 && cardAmount != 7 && cardAmount != 4 && cardAmount != 1) } //产生模式组 func (self *HuController) GeneratePatternGroup(normalCards []*MaJiangCard, hzAmount int) { cardAmount := len(normalCards) if self.IsOnlyGenerateDaDuiZi(int32(cardAmount), int32(hzAmount)) { self.GenerateDaDuiZiPatternGroup(normalCards, hzAmount) } else if self.IsOnlyGenerateXiaoQiDui(int32(cardAmount), int32(hzAmount)) { self.GenerateXiaoQiDuiPatternGroup(normalCards, hzAmount) } else { //1.产生普通的模式组 self.GenerateNormalPatternGroup(normalCards, hzAmount) //2.产生大对子的模式组 self.GenerateDaDuiZiPatternGroup(normalCards, hzAmount) //3.产生小七对的模式组 self.GenerateXiaoQiDuiPatternGroup(normalCards, hzAmount) } //4.打印所有胡的模式组 //PrintPatternGroupsS("所有能胡的模式组:", self.patternGroups, true) } //产生素(普通)的模式组 func (self *HuController) GenerateNormalPatternGroup(normalCards []*MaJiangCard, hzAmount int) { logger.Info("开始计算普通胡") //根据胡牌方式进行枚举 curTime := time.Now() //单调胡 logger.Info("=====================普通胡牌下的单调胡=====================") self.GenerateNormalPatternGroupByHuType(DanDiaoHu, normalCards, hzAmount) //顺子胡 logger.Info("=====================普通胡牌下的顺子胡=====================") self.GenerateNormalPatternGroupByHuType(ShunZiHu, normalCards, hzAmount) //对处胡 logger.Info("=====================普通胡牌下的对处胡=====================") self.GenerateNormalPatternGroupByHuType(DuiChuHu, normalCards, hzAmount) logger.Info("产生普通模式组用时:", time.Now().Sub(curTime)) } //产生素(普通)的单调胡模式组 func (self *HuController) GenerateNormalPatternGroupByHuType(huType int32, normalCards []*MaJiangCard, hzAmount int) { //1.检查输入参数 if normalCards == nil || len(normalCards) <= 0 { logger.Error("本牌的数量是nil或0") return } //2.产生单调胡的模式列表,并计算最终的红中替换后的胡牌模式组 totalCardAmount := len(normalCards) + hzAmount minCardAmount := 4 if huType == DuiChuHu { minCardAmount = 7 } if totalCardAmount < minCardAmount { return } maxKanAmount := (totalCardAmount - minCardAmount) / 3 //计算每种组合 PrintCardsS("========+++++++++普通胡牌,开始统计坎前,剩余的牌:", normalCards) AAAPatterns, remainAAANormalCards := GetAAAPatterns(normalCards, hzAmount) PrintPatternsS("========+++++++++普通胡牌,所有坎模式的列表:", AAAPatterns) PrintCardsS("========+++++++++普通胡牌,所有坎模式的列表时,剩余本牌:", remainAAANormalCards) for needKanAmount := maxKanAmount; needKanAmount >= 0; needKanAmount-- { //坎 validAAAPatterns, validAAARNCCards, remainAAAHZAmounts := GetValidAAAPatterns(needKanAmount, AAAPatterns, remainAAANormalCards, hzAmount) if len(validAAAPatterns) != len(validAAARNCCards) || len(validAAAPatterns) != len(remainAAAHZAmounts) { logger.Error("三个的数量必须相同!") continue } //dump info logger.Info("普通胡牌,统计(%d)个坎时,所有组合:", needKanAmount) for kanCIndex, kanPatternC := range validAAAPatterns { PrintPatternsS("组合的坎:", kanPatternC) PrintCardsS("组合的坎后=====剩余的本牌:", validAAARNCCards[kanCIndex]) logger.Info("剩余的红中数量:%d", remainAAAHZAmounts[kanCIndex]) } for kanCIndex, kanPatternC := range validAAAPatterns { //顺子 needSZAmount := maxKanAmount - needKanAmount + 1 if huType == ShunZiHu { needSZAmount = maxKanAmount - needKanAmount } //计算顺子的时候,剩余的牌 // remainKanCards := GetCardsOfPatternList(validAAARNCCards[kanCIndex]) // remainKanNormalCards, remainKanHZCards := SplitCards(remainKanCards) // remainKanNormalCards = append(remainKanNormalCards, remainNormalCards...) remainKanNormalCards := validAAARNCCards[kanCIndex] remainKanHZAmount := remainAAAHZAmounts[kanCIndex] PrintCardsS("普通胡牌,开始顺子统计前,剩余的牌:", remainKanNormalCards) ABCPatterns := GetABCPatterns(remainKanNormalCards, remainKanHZAmount) if len(ABCPatterns) < needSZAmount { continue } PrintPatternsS("普通胡牌,统计的顺子:", ABCPatterns) validABCPatterns, validABCRNCCards, remainABCHZAmounts := GetValidABCPatterns(needSZAmount, ABCPatterns, remainKanNormalCards, remainKanHZAmount) if len(validABCPatterns) != len(validABCRNCCards) || len(validABCPatterns) != len(remainABCHZAmounts) { logger.Error("三个的数量必须相同!") continue } logger.Info("普通胡牌,统计(%d)个顺子时,所有组合:", needSZAmount) for szCIndex, szPatternC := range validABCPatterns { PrintPatternsS("组合的顺子:", szPatternC) PrintCardsS("组合的顺子后=====剩余的本牌:", validABCRNCCards[szCIndex]) logger.Info("剩余的红中数量:%d", remainABCHZAmounts[szCIndex]) } //生成红中替换后的最终模式组 for szCIndex, szPatternC := range validABCPatterns { //计算生成最终模式前,剩余的牌 // remainABCCards := GetCardsOfPatternList(otherSZPatternsC[szCIndex]) // remainABCNormalCards, remainABCHZCards := SplitCards(remainABCCards) // remainABCNormalCards = append(remainABCNormalCards, ABCRemainCards...) // tempABCRemainHZAmount := ABCRemainHZAmount + len(remainABCHZCards) remainABCNormalCards := validABCRNCCards[szCIndex] remainABCHZAmount := remainABCHZAmounts[szCIndex] PrintCardsS("普通胡牌,顺子统计完后,剩余的牌:", remainABCNormalCards) if huType == ShunZiHu { needDuiZiAmount := 1 if len(remainABCNormalCards)+remainABCHZAmount != 4 { logger.Error("到这一步时,必须是4张牌!") return } AAPatterns, remainAANormalCards := GetAAPatterns(remainABCNormalCards, remainABCHZAmount) if len(AAPatterns) < needDuiZiAmount { continue } validAAPatterns, validAARNCCards, remainAAHZAmounts := GetValidAAPatterns(needDuiZiAmount, AAPatterns, remainAANormalCards, remainABCHZAmount) if len(validAAPatterns) != len(validAARNCCards) || len(validAAPatterns) != len(remainAAHZAmounts) { logger.Error("三个的数量必须相同!") continue } for aaCIndex, aaPatternC := range validAAPatterns { //计算剩余的牌 remainAANormalCards := validAARNCCards[aaCIndex] remainAAHZAmount := remainAAHZAmounts[aaCIndex] // singlRemainCards := []*MaJiangCard{} // singlRemainCards = append(singlRemainCards, singleCards...) for i := 0; i < remainAAHZAmount; i++ { remainAANormalCards = append(remainAANormalCards, NewHongZhong()) } patterns := []*MaJiangPattern{} patterns = append(patterns, kanPatternC...) patterns = append(patterns, szPatternC...) patterns = append(patterns, aaPatternC[:needDuiZiAmount]...) self.GenerateFinalPatternGroups(NormalPattern, patterns, remainAANormalCards, hzAmount) } } else { for i := 0; i < remainABCHZAmount; i++ { remainABCNormalCards = append(remainABCNormalCards, NewHongZhong()) } patterns := []*MaJiangPattern{} patterns = append(patterns, kanPatternC...) patterns = append(patterns, szPatternC...) self.GenerateFinalPatternGroups(NormalPattern, patterns, remainABCNormalCards, hzAmount) } } } } PrintCardsS("GenerateNormalPatternGroupByHuType函数退出后,normalCards的情况:", normalCards) } //产生大对子模式组 func (self *HuController) GenerateDaDuiZiPatternGroup(normalCards []*MaJiangCard, hzAmount int) { //根据胡牌方式进行枚举 curTime := time.Now() //单调胡 logger.Info("=====================大对子胡牌下的单调胡=====================") self.GenerateDaDuiZiPatternGroupByHuType(DanDiaoHu, normalCards, hzAmount) //对处胡 logger.Info("=====================大对子胡牌下的对处胡=====================") self.GenerateDaDuiZiPatternGroupByHuType(DuiChuHu, normalCards, hzAmount) logger.Info("产生大对子模式组用时:", time.Now().Sub(curTime)) } func (self *HuController) GenerateDaDuiZiPatternGroupByHuType(huType int32, normalCards []*MaJiangCard, hzAmount int) { //1.检查输入参数 if normalCards == nil || len(normalCards) <= 0 { logger.Error("本牌的数量是nil或0") return } //2.产生单调胡的模式列表,并计算最终的红中替换后的胡牌模式组 totalCardAmount := len(normalCards) + hzAmount minCardAmount := 1 if huType == DuiChuHu { minCardAmount = 4 } if totalCardAmount < minCardAmount { return } needKanAmount := (totalCardAmount - minCardAmount) / 3 //坎 AAAPatterns, remainAAANormalCards := GetAAAPatterns(normalCards, hzAmount) if len(AAAPatterns) < needKanAmount { return } PrintPatternsS("大对子胡牌,统计的坎:", AAAPatterns) PrintCardsS("大对子胡牌,统计坎时,剩余本牌:", remainAAANormalCards) //坎 validAAAPatterns, validAAARNCCards, remainAAAHZAmounts := GetValidAAAPatterns(needKanAmount, AAAPatterns, remainAAANormalCards, hzAmount) if len(validAAAPatterns) != len(validAAARNCCards) || len(validAAAPatterns) != len(remainAAAHZAmounts) { logger.Error("三个的数量必须相同!") return } //dump info logger.Info("大对子胡牌,统计(%d)个坎时,所有组合:", needKanAmount) for kanCIndex, kanPatternC := range validAAAPatterns { PrintPatternsS("组合的坎:", kanPatternC) PrintCardsS("组合的坎后=====剩余的本牌:", validAAARNCCards[kanCIndex]) logger.Info("剩余的红中数量:%d", remainAAAHZAmounts[kanCIndex]) } for kanCIndex, kanPatternC := range validAAAPatterns { // remainKanCards := GetCardsOfPatternList(otherKanPatternsC[kanCIndex]) // remainKanNormalCards, remainKanHZCards := SplitCards(remainKanCards) // remainKanNormalCards = append(remainKanNormalCards, remainNormalCards...) //tempRemainHZAmount := remainHZAmount + len(remainKanHZCards) remainKanNormalCards := validAAARNCCards[kanCIndex] remainKanHZAmount := remainAAAHZAmounts[kanCIndex] for i := 0; i < remainKanHZAmount; i++ { remainKanNormalCards = append(remainKanNormalCards, NewHongZhong()) } PrintCardsS("大对子胡牌,坎统计完后,剩余的牌:", remainKanNormalCards) patterns := []*MaJiangPattern{} patterns = append(patterns, kanPatternC...) self.GenerateFinalPatternGroups(DaDuiZiPattern, patterns, remainKanNormalCards, hzAmount) } } //产生小七对模式组 func (self *HuController) GenerateXiaoQiDuiPatternGroup(normalCards []*MaJiangCard, hzAmount int) { //1.检查输入参数 if normalCards == nil || len(normalCards) <= 0 { logger.Error("本牌的数量是nil或0") return } curTime := time.Now() totalCardAmount := len(normalCards) + hzAmount if totalCardAmount != 13 { return } logger.Info("=====================小七对胡牌下的单调胡=====================") PrintCardsS("小七对胡牌,开始统计坎时,剩余的牌:", normalCards) needDuiZiAmount := (totalCardAmount - 1) / 2 normalAAPatterns, normalSingleCards := SplitToAA_A(normalCards) needDuiZiAmount -= len(normalAAPatterns) AAPatterns, remainSingleCards := GetAAPatterns(normalSingleCards, hzAmount) if len(AAPatterns) < needDuiZiAmount { return } validAAPatterns, validAARNCCards, remainAAHZAmounts := GetValidAAPatterns(needDuiZiAmount, AAPatterns, remainSingleCards, hzAmount) if len(validAAPatterns) != len(validAARNCCards) || len(validAAPatterns) != len(remainAAHZAmounts) { logger.Error("三个的数量必须相同!") return } //dump info logger.Info("大对子胡牌,统计(%d)个坎时,所有组合:", needDuiZiAmount) for aaCIndex, aaPatternC := range validAAPatterns { PrintPatternsS("组合的坎:", aaPatternC) PrintCardsS("组合的坎后=====剩余的本牌:", validAARNCCards[aaCIndex]) logger.Info("剩余的红中数量:%d", remainAAHZAmounts[aaCIndex]) } for aaCIndex, aaPatternC := range validAAPatterns { // remainKanCards := GetCardsOfPatternList(otherKanPatternsC[kanCIndex]) // remainKanNormalCards, remainKanHZCards := SplitCards(remainKanCards) // remainKanNormalCards = append(remainKanNormalCards, remainNormalCards...) //tempRemainHZAmount := remainHZAmount + len(remainKanHZCards) remainAANormalCards := validAARNCCards[aaCIndex] remainAAHZAmount := remainAAHZAmounts[aaCIndex] logger.Info("小七对胡牌,统计坎后,红中的数量:", remainAAHZAmount) PrintPatternsS("小七对胡牌,统计的对:", aaPatternC) PrintCardsS("小七对胡牌,统计对时,剩余本牌:", remainAANormalCards) //计算剩余的牌 // singlRemainCards := GetCardsOfPatternList(AAPatterns[needDuiZiAmount:]) // singlRemainCards = append(singlRemainCards, remainSingleCards...) for i := 0; i < remainAAHZAmount; i++ { remainAANormalCards = append(remainAANormalCards, NewHongZhong()) } PrintCardsS("小七对胡牌,对子统计完后,剩余的牌:", remainAANormalCards) patterns := []*MaJiangPattern{} patterns = append(patterns, normalAAPatterns...) patterns = append(patterns, AAPatterns...) self.GenerateFinalPatternGroups(XiaoQiDuiPattern, patterns, remainAANormalCards, hzAmount) } logger.Info("产生小七对模式组,用时:", time.Now().Sub(curTime)) } //获取模式列表里的牌 func GetCardsOfPatternList(patterns []*MaJiangPattern) []*MaJiangCard { result := make([]*MaJiangCard, 0) if len(patterns) <= 0 { return result } for _, p := range patterns { result = append(result, p.cards...) } return result } //获取AAA的所有模式(包括红中的替代的模式) func GetAAAPatterns(normalCards []*MaJiangCard, hzAmount int) (patterns []*MaJiangPattern, remainNormalCards []*MaJiangCard) { //初始话返回参数 patterns = []*MaJiangPattern{} remainNormalCards = []*MaJiangCard{} if len(normalCards) <= 0 { return } //拆分本牌 AAAPatterns, AAPatterns, AAASingleCards := SplitToAAA_AA_A(normalCards) patterns = append(patterns, AAAPatterns...) //根据红中的数量来组合AAA的模式 if hzAmount <= 0 { remainNormalCards = append(remainNormalCards, GetCardsOfPatternList(AAPatterns)...) remainNormalCards = append(remainNormalCards, AAASingleCards...) return } if hzAmount >= 1 { for _, aaP := range AAPatterns { temp := make([]*MaJiangCard, 0, 3) temp = append(temp, aaP.cards...) temp = append(temp, NewCard(0, HongZhong, 0)) patterns = append(patterns, NewPattern(PTKan, temp, false)) } } if hzAmount >= 2 { for _, c := range AAASingleCards { temp := make([]*MaJiangCard, 0, 3) temp = append(temp, c) temp = append(temp, NewCard(0, HongZhong, 0)) temp = append(temp, NewCard(0, HongZhong, 0)) patterns = append(patterns, NewPattern(PTKan, temp, false)) } } else { remainNormalCards = append(remainNormalCards, AAASingleCards...) } return } //获取有效的AAA func GetValidAAAPatterns(needKanAmount int, patterns []*MaJiangPattern, normalCards []*MaJiangCard, hzAmount int) ( result [][]*MaJiangPattern, remainNormalCards [][]*MaJiangCard, remainHZAmounts []int) { //初始化返回值 result = [][]*MaJiangPattern{} remainNormalCards = [][]*MaJiangCard{} remainHZAmounts = []int{} //检查参数的合法性 if needKanAmount > len(patterns) { return } kanPCs, otherKanPCs := GetAllPatternsCombination(needKanAmount, patterns, true) if len(kanPCs) != len(otherKanPCs) { logger.Error("两个的数量必须相同!") return } for kanPCIndex, kanPC := range kanPCs { sucess, remainHZAmount := VerifyPatterns(kanPC, hzAmount) if !sucess { continue } otherKanPCCards := GetCardsOfPatternList(otherKanPCs[kanPCIndex]) nCards, _ := SplitCards(otherKanPCCards) result = append(result, kanPC) tempCards := []*MaJiangCard{} tempCards = append(tempCards, nCards...) if normalCards != nil { tempCards = append(tempCards, normalCards...) } remainNormalCards = append(remainNormalCards, tempCards) remainHZAmounts = append(remainHZAmounts, remainHZAmount) } return } //是否是有效的组 func VerifyPatterns(patterns []*MaJiangPattern, hzAmount int) (isValid bool, remainHZAmount int) { isValid = true remainHZAmount = hzAmount if len(patterns) <= 0 { return } for _, p := range patterns { for _, c := range p.cards { if c.IsHongZhong() { remainHZAmount-- if remainHZAmount < 0 { isValid = false return } } } } return } //获取AA的所有模式(包括红中的替代的模式) func GetAAPatterns(normalCards []*MaJiangCard, hzAmount int) (patterns []*MaJiangPattern, remainNormalCards []*MaJiangCard) { //初始话返回参数 patterns = []*MaJiangPattern{} remainNormalCards = []*MaJiangCard{} if len(normalCards) <= 0 { return } //拆分本牌 AAPatterns, ABCSingleCards := SplitToAA_A(normalCards) patterns = append(patterns, AAPatterns...) //根据红中的数量来组合AAA的模式 if hzAmount <= 0 { remainNormalCards = append(remainNormalCards, ABCSingleCards...) return } if hzAmount >= 1 { for _, c := range ABCSingleCards { temp := []*MaJiangCard{c, NewHongZhong()} patterns = append(patterns, NewPattern(PTPair, temp, false)) } } return } //获取有效的AA func GetValidAAPatterns(needPairAmount int, patterns []*MaJiangPattern, normalCards []*MaJiangCard, hzAmount int) ( result [][]*MaJiangPattern, remainNormalCards [][]*MaJiangCard, remainHZAmounts []int) { //初始化返回值 result = [][]*MaJiangPattern{} remainNormalCards = [][]*MaJiangCard{} remainHZAmounts = []int{} //检查参数的合法性 if needPairAmount > len(patterns) { return } pairPCs, otherPairPCs := GetAllPatternsCombination(needPairAmount, patterns, true) if len(pairPCs) != len(otherPairPCs) { logger.Error("两个的数量必须相同!") return } for pairPCIndex, pairPC := range pairPCs { sucess, remainHZAmount := VerifyPatterns(pairPC, hzAmount) if !sucess { continue } otherPairPCCards := GetCardsOfPatternList(otherPairPCs[pairPCIndex]) nCards, _ := SplitCards(otherPairPCCards) result = append(result, pairPC) tempCards := []*MaJiangCard{} tempCards = append(tempCards, nCards...) if normalCards != nil { tempCards = append(tempCards, normalCards...) } remainNormalCards = append(remainNormalCards, tempCards) remainHZAmounts = append(remainHZAmounts, remainHZAmount) } return } //获取AAA的所有模式(包括红中的替代的模式) func GetABCPatterns(normalCards []*MaJiangCard, hzAmount int) (patterns []*MaJiangPattern) { //1.初始话返回参数 patterns = []*MaJiangPattern{} if len(normalCards) <= 0 { return } //2.组合可能的顺子 //2.1组合3个本牌的顺子 tempPatterns := []*MaJiangPattern{} for _, c := range normalCards { findCard1 := FindCard(normalCards, c.cType, c.value-1) if findCard1 != nil { findCard2 := FindCard(normalCards, c.cType, c.value-2) if findCard2 != nil { cards := []*MaJiangCard{c, findCard1, findCard2} tempPatterns = append(tempPatterns, NewPattern(PTSZ, cards, false)) } } } //2.2组合2个本牌的顺子 //2.2.1组合2个本牌连着的顺子 if hzAmount >= 1 { for _, c := range normalCards { findCard1 := FindCard(normalCards, c.cType, c.value-1) if findCard1 != nil { cards := []*MaJiangCard{c, findCard1, NewHongZhong()} tempPatterns = append(tempPatterns, NewPattern(PTSZ, cards, false)) } } } //2.2.2组合2个本牌间隔的顺子 if hzAmount >= 1 { for _, c := range normalCards { findCard1 := FindCard(normalCards, c.cType, c.value-2) if findCard1 != nil { cards := []*MaJiangCard{c, findCard1, NewHongZhong()} tempPatterns = append(tempPatterns, NewPattern(PTSZ, cards, false)) } } } //2.3组合1个本牌的顺子 if hzAmount >= 2 { for _, c := range normalCards { cards := []*MaJiangCard{c, NewHongZhong(), NewHongZhong()} tempPatterns = append(tempPatterns, NewPattern(PTSZ, cards, false)) } } //2.4组合全红中的顺子 hzSZAmount := hzAmount / 3 for i := 0; i < hzSZAmount; i++ { cards := []*MaJiangCard{NewHongZhong(), NewHongZhong(), NewHongZhong()} tempPatterns = append(tempPatterns, NewPattern(PTSZ, cards, false)) } //3.踢出多余的顺子 //3.1拆分相同的模式 //PrintPatternsS("统计后的所有模式:", tempPatterns) tempMap := SplitPatternsToSameList(tempPatterns) //3.2计算相同的顺子需要保留几个 for _, ps := range tempMap { //PrintPatternsS("统计后的每一组模式:", ps) if len(ps) <= 0 { continue } if ps[0].IsAllHZ() { patterns = append(patterns, ps...) } else { curPsAmount := len(ps) maxPsAmount := CalcMaxPatternsAmount(normalCards, ps[0]) reservePsAmount := int32(math.Min(float64(curPsAmount), float64(maxPsAmount))) //移除多余的 patterns = append(patterns, ps[:reservePsAmount]...) } } //PrintPatternsS("统计后的最终模式组:", patterns) return } //拆分相同的模式组 func SplitPatternsToSameList(patterns []*MaJiangPattern) (result [][]*MaJiangPattern) { result = [][]*MaJiangPattern{} if len(patterns) <= 0 { return } for _, p := range patterns { find := false for i, rp := range result { if len(rp) <= 0 { continue } if rp[0].IsEqual(p) { result[i] = append(result[i], p) find = true break } } if !find { result = append(result, []*MaJiangPattern{p}) } } return } //获取能够通过本牌组成的最大数量的模式 func CalcMaxPatternsAmount(normalCards []*MaJiangCard, pattern *MaJiangPattern) (result int) { if len(normalCards) <= 0 || pattern == nil { return 0 } result = 999999 for _, c := range pattern.cards { if c.IsHongZhong() { continue } findCards := FindCards(normalCards, c.cType, c.value) findCardsAmount := len(findCards) if findCardsAmount < result { result = findCardsAmount } } return } //获取有效的ABC func GetValidABCPatterns(needSZAmount int, patterns []*MaJiangPattern, normalCards []*MaJiangCard, hzAmount int) ( result [][]*MaJiangPattern, remainNormalCards [][]*MaJiangCard, remainHZAmounts []int) { //初始化返回值 result = [][]*MaJiangPattern{} remainNormalCards = [][]*MaJiangCard{} remainHZAmounts = []int{} //检查参数的合法性 if needSZAmount > len(patterns) { return } szPatterns := GetSZPatternsCombination(needSZAmount, patterns) for _, szPtns := range szPatterns { sucess, vfyRemainNormalCards, remainHZAmount := GetRemainNormalCardsAndHZAmountAndVerify(szPtns, normalCards, hzAmount) if !sucess { continue } result = append(result, szPtns) remainNormalCards = append(remainNormalCards, vfyRemainNormalCards) remainHZAmounts = append(remainHZAmounts, remainHZAmount) } return } //获取顺子组合的模式组后剩余的本牌和红中数量 func GetRemainNormalCardsAndHZAmountAndVerify(patterns []*MaJiangPattern, normalCards []*MaJiangCard, hzAmount int) ( success bool, remainNormalCards []*MaJiangCard, remainHZAmount int) { //1.设置返回的初始化值 remainNormalCards = make([]*MaJiangCard, len(normalCards)) copy(remainNormalCards, normalCards) remainHZAmount = hzAmount success = true if len(patterns) <= 0 { return } //2.获取剩余的本牌和红中数量 for _, p := range patterns { for _, c := range p.cards { if c.IsHongZhong() { if remainHZAmount <= 0 { success = false break } remainHZAmount-- } else { if len(remainNormalCards) <= 0 { success = false break } removedSuccess := true removedSuccess, remainNormalCards = RemoveCardByType(remainNormalCards, c.cType, c.value) if !removedSuccess { success = false break } } } if !success { break } } return } //将牌拆分成AAA, AA或A模式 func SplitToAAA_AA_A(cards []*MaJiangCard) (AAAPatterns, AAPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { AAAPatterns = []*MaJiangPattern{} AAPatterns = []*MaJiangPattern{} singleCards = []*MaJiangCard{} isFirst := true var firstCard *MaJiangCard var ptnCards []*MaJiangCard tempCards := make([]*MaJiangCard, len(cards)) copy(tempCards, cards) for len(tempCards) > 0 { if isFirst { firstCard = tempCards[0] ptnCards = []*MaJiangCard{} ptnCards = append(ptnCards, firstCard) tempCards = tempCards[1:] isFirst = false } isEndInnerLoop := len(tempCards) <= 0 for i, c := range tempCards { isEndInnerLoop = i+1 >= len(tempCards) if firstCard.IsFullEqual(c) { ptnCards = append(ptnCards, c) tempCards = append(tempCards[:i], tempCards[i+1:]...) break } } ptnAmount := len(ptnCards) if isEndInnerLoop || ptnAmount >= 3 { isFirst = true switch ptnAmount { case 3: AAAPatterns = append(AAAPatterns, NewPattern(PTKan, ptnCards, false)) case 2: AAPatterns = append(AAPatterns, NewPattern(PTPair, ptnCards, false)) case 1: singleCards = append(singleCards, ptnCards...) default: logger.Error("不能超过3个!") } } } return } ////将牌拆分成AA或A模式 func SplitToAA_A(cards []*MaJiangCard) (AAPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { AAPatterns = []*MaJiangPattern{} singleCards = []*MaJiangCard{} isFirst := true var firstCard *MaJiangCard var ptnCards []*MaJiangCard tempCards := make([]*MaJiangCard, len(cards)) copy(tempCards, cards) for len(tempCards) > 0 { if isFirst { firstCard = tempCards[0] ptnCards = []*MaJiangCard{} ptnCards = append(ptnCards, firstCard) tempCards = tempCards[1:] isFirst = false } isEndInnerLoop := len(tempCards) <= 0 for i, c := range tempCards { isEndInnerLoop = i+1 >= len(tempCards) if firstCard.IsFullEqual(c) { ptnCards = append(ptnCards, c) tempCards = append(tempCards[:i], tempCards[i+1:]...) break } } ptnAmount := len(ptnCards) if isEndInnerLoop || ptnAmount >= 2 { isFirst = true switch ptnAmount { case 2: AAPatterns = append(AAPatterns, NewPattern(PTPair, ptnCards, false)) case 1: singleCards = append(singleCards, ptnCards...) default: logger.Error("不能超过2个!") } } } return } //组合指定数量的顺子 func SplitToABC_AB_A(cards []*MaJiangCard) (ABCPatterns, ABPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { //1.检查输入参数 if cards == nil || len(cards) <= 0 { logger.Error("cards is null.") return } tempCards := make([]*MaJiangCard, len(cards)) copy(tempCards, cards) //2.排序 sort.Sort(CardList(tempCards)) //3.统计3张牌的顺子 ABCPatterns = make([]*MaJiangPattern, 0) tagIndex := 0 for tagIndex <= len(tempCards)-3 { tagCard := tempCards[tagIndex] ptnCards := []*MaJiangCard{tagCard} if tempCards[tagIndex+1].IsFullEqualByTypeAndValue(tagCard.cType, tagCard.value+1, tagCard.rcType) { ptnCards = append(ptnCards, tempCards[tagIndex+1]) } if tempCards[tagIndex+2].IsFullEqualByTypeAndValue(tagCard.cType, tagCard.value+2, tagCard.rcType) { ptnCards = append(ptnCards, tempCards[tagIndex+2]) } if len(ptnCards) >= 3 { ABCPatterns = append(ABCPatterns, NewPattern(PTSZ, ptnCards, false)) tempCards = append(tempCards[:tagIndex], tempCards[tagIndex+3:]...) } else { tagIndex++ } } //4.统计2张牌的间隔模式 ABPatterns = make([]*MaJiangPattern, 0) tagIndex = 0 for tagIndex <= len(tempCards)-2 { tagCard := tempCards[tagIndex] ptnCards := []*MaJiangCard{tagCard} if tempCards[tagIndex+1].IsFullEqualByTypeAndValue(tagCard.cType, tagCard.value+2, tagCard.rcType) { ptnCards = append(ptnCards, tempCards[tagIndex+1]) ABPatterns = append(ABPatterns, NewPattern(PTSZ, ptnCards, false)) tempCards = append(tempCards[:tagIndex], tempCards[tagIndex+2:]...) } else { tagIndex++ } } //5.统计2张牌的相邻模式 tagIndex = 0 for tagIndex <= len(tempCards)-2 { tagCard := tempCards[tagIndex] ptnCards := []*MaJiangCard{tagCard} if tempCards[tagIndex+1].IsFullEqualByTypeAndValue(tagCard.cType, tagCard.value+1, tagCard.rcType) { ptnCards = append(ptnCards, tempCards[tagIndex+1]) ABPatterns = append(ABPatterns, NewPattern(PTSZ, ptnCards, false)) tempCards = append(tempCards[:tagIndex], tempCards[tagIndex+2:]...) } else { tagIndex++ } } //6.统计剩余的单牌 singleCards = make([]*MaJiangCard, 0) singleCards = append(singleCards, tempCards...) return } //牌排序 type CardList []*MaJiangCard func (self CardList) Len() int { return len(self) } func (self CardList) Less(i, j int) bool { iCurType, iCurValue := self[i].CurValue() jCurType, jCurValue := self[j].CurValue() if iCurType == jCurType { return iCurValue < jCurValue } return iCurType < jCurType } func (self CardList) Swap(i, j int) { self[i], self[j] = self[j], self[i] } //计算胡和红中替换 func (self *HuController) GenerateFinalPatternGroups(pType int32, patterns []*MaJiangPattern, remainCards []*MaJiangCard, hzAmount int) (result []*MaJiangPatternGroup) { result = make([]*MaJiangPatternGroup, 0) //debug info switch pType { case NormalPattern: PrintPatternsS("GenerateFinalPatternGroups=====普通胡牌时生成的模式:", patterns) PrintCardsS("GenerateFinalPatternGroups=====剩余的单牌是:", remainCards) case DaDuiZiPattern: PrintPatternsS("GenerateFinalPatternGroups=====大对子胡牌时生成的模式:", patterns) PrintCardsS("GenerateFinalPatternGroups=====剩余的单牌是:", remainCards) case XiaoQiDuiPattern: PrintPatternsS("GenerateFinalPatternGroups=====小七对胡牌时生成的模式:", patterns) PrintCardsS("GenerateFinalPatternGroups=====剩余的单牌是:", remainCards) } logger.Info("GenerateFinalPatternGroups: enter!") //1.检查剩余的牌有没得机会可以胡 if !CanHu(remainCards) { PrintCardsS("不能胡牌,因为剩余的单牌:", remainCards) return } rpTypess := self.player.GetCanReplaceType() logger.Info("可以替换的类型是:", rpTypess) if hzAmount > 0 { logger.Info("GenerateFinalPatternGroups: 分割输入模式组(非全红中/全红中)!") //2.分割固定替换(有本牌的替换)和任意替换(没有本牌的替换) notAllHZPatterns, allHZPatterns := SplitPatterns(patterns) PrintPatternsS("分割产生最终的模式列表:非全红中", notAllHZPatterns) PrintPatternsS("分割产生最终的模式列表:全红中", allHZPatterns) //3.计算模式列表的红中固定替换列表 logger.Info("非全红中时==============") notAllHZRPPatterns := self.GenerateNotAllHZ(notAllHZPatterns) PrintPatternsS("非全红中时,", notAllHZPatterns) //4.根据替换类型,产生每一组替换类型对应的替换模式列表 for _, rpTypes := range rpTypess { allHZRPPatterns := self.GenerateAllHZ(rpTypes, allHZPatterns) for _, pnts := range allHZRPPatterns { PrintPatternsS("全红中时,", pnts) } outAllRPList := make([][]*MaJiangPattern, 0) tempResult := make([]*MaJiangPattern, 0) self.GenerateCandidatePattern(0, append(notAllHZRPPatterns, allHZRPPatterns[:]...), &tempResult, &outAllRPList) for _, pnts := range outAllRPList { logger.Info("===========================rpTypes:", rpTypes) PrintPatternsS("所有的后备模式,", pnts) } for _, rp := range outAllRPList { self.GenerateOneFinalPatternGroups(rpTypes, rp, remainCards) } } } else { self.GenerateOneFinalPatternGroups(rpTypess[0], patterns, remainCards) } logger.Info("完成一次最终模式组的生成-GenerateFinalPatternGroups!") PrintPatternGroupsS("完成一次最终模式组的生成:", self.patternGroups, true) return result } //产生所有非全红中的模式的替换列表 func (self *HuController) GenerateNotAllHZ(notAllHZPatterns []*MaJiangPattern) (notAllHZRPPatterns [][]*MaJiangPattern) { notAllHZRPPatterns = make([][]*MaJiangPattern, len(notAllHZPatterns)) if len(notAllHZPatterns) <= 0 { return } for i, hzp := range notAllHZPatterns { normalCards, hongZhongCards := SplitCards(hzp.cards) switch hzp.ptype { case PTKan: fallthrough case PTPair: notAllHZRPPatterns[i] = ComposeKanAnDZPatternsForNotAllHZ(normalCards, hongZhongCards, hzp.ptype) case PTSZ: notAllHZRPPatterns[i] = ComposeSZPatternsForNotAllHZ(normalCards, hongZhongCards) default: logger.Error("不能有其他类型的模式,只能是坎,顺子,对子。") } } return } //组合坎和对子模式通过本牌和红中牌 func ComposeKanAnDZPatternsForNotAllHZ(normalCards, hongZhongCards []*MaJiangCard, ptype int32) (result []*MaJiangPattern) { result = make([]*MaJiangPattern, 0) if len(normalCards) <= 0 { logger.Error("非所有红中,那么应该至少有一个是本派!") return } PrintCardsS("组合坎和对子模式通过本牌和红中牌时,本牌有:", normalCards) tempCards := []*MaJiangCard{} tempCards = append(tempCards, normalCards...) for _, hzc := range hongZhongCards { tempHZC := *hzc //copy tempHZC.SetHZReplaceValue(normalCards[0].cType, normalCards[0].value) tempCards = append(tempCards, &tempHZC) } result = append(result, NewPattern(ptype, tempCards, false)) return } //组合顺子模式通过本牌和红中牌 func ComposeSZPatternsForNotAllHZ(normalCards, hongZhongCards []*MaJiangCard) (result []*MaJiangPattern) { result = make([]*MaJiangPattern, 0) ncAmount := len(normalCards) hzAmount := len(hongZhongCards) if ncAmount+hzAmount != 3 { logger.Error("顺子模式必须是3张牌!") return } //PrintCardsS("ComposeSZPatternsForNotAllHZ:普通牌:", normalCards) switch ncAmount { case 3: result = append(result, NewPattern(PTSZ, normalCards, false)) case 2: firstCard := normalCards[0] secondCard := normalCards[1] valOffset := firstCard.value - secondCard.value if valOffset == 2 || valOffset == -2 { tempHZCard := *hongZhongCards[0] tempHZCard.SetHZReplaceValue(firstCard.cType, (firstCard.value+secondCard.value)/2) result = append(result, NewPattern(PTSZ, append(normalCards, &tempHZCard), false)) } if valOffset == -1 { if firstCard.value-1 > 0 { tempHZCard := *hongZhongCards[0] tempHZCard.SetHZReplaceValue(firstCard.cType, firstCard.value-1) result = append(result, NewPattern(PTSZ, append(normalCards, &tempHZCard), false)) } if secondCard.value+1 <= 9 { tempHZCard := *hongZhongCards[0] tempHZCard.SetHZReplaceValue(secondCard.cType, secondCard.value+1) result = append(result, NewPattern(PTSZ, append(normalCards, &tempHZCard), false)) } } if valOffset == 1 { if secondCard.value-1 > 0 { tempHZCard := *hongZhongCards[0] tempHZCard.SetHZReplaceValue(secondCard.cType, secondCard.value-1) result = append(result, NewPattern(PTSZ, append(normalCards, &tempHZCard), false)) } if firstCard.value+1 <= 9 { tempHZCard := *hongZhongCards[0] tempHZCard.SetHZReplaceValue(firstCard.cType, firstCard.value+1) result = append(result, NewPattern(PTSZ, append(normalCards, &tempHZCard), false)) } } case 1: firstCard := normalCards[0] if firstCard.value-2 > 0 { tempHZCard1 := *hongZhongCards[0] tempHZCard1.SetHZReplaceValue(firstCard.cType, firstCard.value-1) tempHZCard2 := *hongZhongCards[1] tempHZCard2.SetHZReplaceValue(firstCard.cType, firstCard.value-2) result = append(result, NewPattern(PTSZ, append(append(normalCards, &tempHZCard1), &tempHZCard2), false)) } if firstCard.value-1 > 0 && firstCard.value+1 <= 9 { tempHZCard1 := *hongZhongCards[0] tempHZCard1.SetHZReplaceValue(firstCard.cType, firstCard.value-1) tempHZCard2 := *hongZhongCards[1] tempHZCard2.SetHZReplaceValue(firstCard.cType, firstCard.value+1) result = append(result, NewPattern(PTSZ, append(append(normalCards, &tempHZCard1), &tempHZCard2), false)) } if firstCard.value+2 <= 9 { tempHZCard1 := *hongZhongCards[0] tempHZCard1.SetHZReplaceValue(firstCard.cType, firstCard.value+1) tempHZCard2 := *hongZhongCards[1] tempHZCard2.SetHZReplaceValue(firstCard.cType, firstCard.value+2) result = append(result, NewPattern(PTSZ, append(append(normalCards, &tempHZCard1), &tempHZCard2), false)) } default: logger.Error("本牌不能是其他数量!") } return } //产生所有全红中的模式下的指定替换类型下的的替换列表 func (self *HuController) GenerateAllHZ(rpTypes []int32, allHZPatterns []*MaJiangPattern) (allHZRPPatterns [][]*MaJiangPattern) { allHZRPPatterns = make([][]*MaJiangPattern, len(allHZPatterns)) if len(allHZRPPatterns) <= 0 { return } for i, hzp := range allHZPatterns { hongZhongCards := hzp.cards switch hzp.ptype { case PTKan: fallthrough case PTPair: allHZRPPatterns[i] = ComposeKanAndDZPatternsForAllHZ(rpTypes, hongZhongCards, hzp.ptype) case PTSZ: allHZRPPatterns[i] = ComposeSZPatternsForAllHZ(rpTypes, hongZhongCards) default: logger.Error("不能有其他类型的模式,只能是坎,顺子,对子。") } } return } //组合坎和对子模式通过红中牌 func ComposeKanAndDZPatternsForAllHZ(rpTypes []int32, hongZhongCards []*MaJiangCard, ptype int32) (result []*MaJiangPattern) { result = make([]*MaJiangPattern, 0) if len(hongZhongCards) <= 0 { logger.Error("所有红中,红中的数量不应该小于等于0!") return } for _, rpType := range rpTypes { for i := 1; i <= 9; i++ { tempCards := []*MaJiangCard{} for _, hzc := range hongZhongCards { tempHZC := *hzc //copy tempHZC.SetHZReplaceValue(rpType, int32(i)) tempCards = append(tempCards, &tempHZC) } result = append(result, NewPattern(ptype, tempCards, false)) } } return } //组合顺子模式通过红中牌 func ComposeSZPatternsForAllHZ(rpTypes []int32, hongZhongCards []*MaJiangCard) (result []*MaJiangPattern) { result = make([]*MaJiangPattern, 0) if len(hongZhongCards) != 3 { logger.Error("顺子模式必须是3张牌!") return } for _, rpType := range rpTypes { for i := 1; i <= 7; i++ { tempCards := []*MaJiangCard{} for hi, hzc := range hongZhongCards { tempHZC := *hzc //copy tempHZC.SetHZReplaceValue(rpType, int32(i+hi)) tempCards = append(tempCards, &tempHZC) } result = append(result, NewPattern(PTSZ, tempCards, false)) } } return } //排列生成用于生成最终模式的模式的后备模式列表 func (self *HuController) GenerateCandidatePattern(curIndex int, hzRPPatterns [][]*MaJiangPattern, tempResult *[]*MaJiangPattern, outAllRPList *[][]*MaJiangPattern) { //1. 检查参数 if outAllRPList == nil || tempResult == nil { logger.Error("参数错误!", outAllRPList, tempResult) return } if curIndex >= len(hzRPPatterns) { PrintPatternsS("生成所有后备队列时的其中一组:", *tempResult) temp := make([]*MaJiangPattern, len(*tempResult)) copy(temp, *tempResult) *outAllRPList = append(*outAllRPList, temp) return } loopList := hzRPPatterns[curIndex] curIndex++ for _, p := range loopList { *tempResult = append(*tempResult, p) self.GenerateCandidatePattern(curIndex, hzRPPatterns, tempResult, outAllRPList) oldTempResult := *tempResult *tempResult = oldTempResult[:len(oldTempResult)-1] } } //产生一组最终的模式 func (self *HuController) GenerateOneFinalPatternGroups(rpTypes []int32, hzRPPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { if IsAllHongZhong(singleCards) { self.GenerateOneFinalPatternGroupsForKaoAllHZ(rpTypes, hzRPPatterns, singleCards) } else { self.GenerateOneFinalPatternGroupsForKaoNotAllHZ(rpTypes, hzRPPatterns, singleCards) } } //产生一组最终的模式,对于靠牌全是红中的情况 func (self *HuController) GenerateOneFinalPatternGroupsForKaoAllHZ(rpTypes []int32, hzRPPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { //1.检查输入参数 if len(rpTypes) <= 0 || len(singleCards) <= 0 { logger.Error("替换类型为空。") return } switch len(singleCards) { //单调 case 1: for _, rpType := range rpTypes { for i := 1; i <= 9; i++ { tempHZC := *singleCards[0] //copy tempHZC.SetHZReplaceValue(rpType, int32(i)) kaoCards := []*MaJiangCard{&tempHZC} pg := NewPatternGroup(hzRPPatterns) pg.kaoCards = kaoCards huCards := []*MaJiangCard{NewCard(0, rpType, int32(i))} pg.huCards = huCards self.AddOnePatternGroup(pg) } } //顺子 case 2: //连续的 for _, rpType := range rpTypes { for i := 2; i <= 7; i++ { tempHZC1 := *singleCards[0] //copy tempHZC1.SetHZReplaceValue(rpType, int32(i)) tempHZC2 := *singleCards[1] //copy tempHZC2.SetHZReplaceValue(rpType, int32(i+1)) kaoCards := []*MaJiangCard{&tempHZC1, &tempHZC2} pg := NewPatternGroup(hzRPPatterns) pg.kaoCards = kaoCards huCards := []*MaJiangCard{NewCard(0, rpType, int32(i-1)), NewCard(0, rpType, int32(i+2))} pg.huCards = huCards self.AddOnePatternGroup(pg) } } //间隔的 for _, rpType := range rpTypes { for i := 1; i <= 7; i++ { tempHZC1 := *singleCards[0] //copy tempHZC1.SetHZReplaceValue(rpType, int32(i)) tempHZC2 := *singleCards[1] //copy tempHZC2.SetHZReplaceValue(rpType, int32(i+2)) kaoCards := []*MaJiangCard{&tempHZC1, &tempHZC2} pg := NewPatternGroup(hzRPPatterns) pg.kaoCards = kaoCards huCards := []*MaJiangCard{NewCard(0, rpType, int32(i+1))} pg.huCards = huCards self.AddOnePatternGroup(pg) } } //对处 case 4: rpTypeAmount := len(rpTypes) for i := 1; i <= 9*rpTypeAmount; i++ { iRPType := rpTypes[i/10] iRPValue := int32(((i - 1) % 9) + 1) for j := 1; j <= 9*rpTypeAmount; j++ { tempHZC1 := *singleCards[0] //copy tempHZC1.SetHZReplaceValue(iRPType, iRPValue) tempHZC2 := *singleCards[1] //copy tempHZC2.SetHZReplaceValue(iRPType, iRPValue) jRPType := rpTypes[j/10] jRPValue := int32(((j - 1) % 9) + 1) tempHZC3 := *singleCards[2] //copy tempHZC3.SetHZReplaceValue(jRPType, jRPValue) tempHZC4 := *singleCards[3] //copy tempHZC4.SetHZReplaceValue(jRPType, jRPValue) kaoCards := []*MaJiangCard{&tempHZC1, &tempHZC2, &tempHZC3, &tempHZC4} pg := NewPatternGroup(hzRPPatterns) pg.kaoCards = kaoCards huCards := []*MaJiangCard{NewCard(0, iRPType, iRPValue), NewCard(0, jRPValue, jRPValue)} pg.huCards = huCards self.AddOnePatternGroup(pg) } } default: logger.Error("剩余的单牌数量只能是:1, 2, 4") } } //产生一组最终的模式,对于靠牌非全红中的情况 func (self *HuController) GenerateOneFinalPatternGroupsForKaoNotAllHZ(rpTypes []int32, hzRPPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { //1.检查输入参数 if len(rpTypes) <= 0 || len(singleCards) <= 0 { logger.Error("替换类型为空。") return } logger.Info("产生一个最终的模式组(靠牌非全红中):替换类型:", rpTypes) PrintPatternsS("产生一个最终的模式组(靠牌非全红中):模式列表:", hzRPPatterns) PrintCardsS("产生一个最终的模式组(靠牌非全红中):单牌:", singleCards) switch len(singleCards) { //单调 case 1: fallthrough //顺子 case 2: self.GenerateOneFinalPatternGroupsForKaoNotAllHZ_DD_SZ(rpTypes, hzRPPatterns, singleCards) //对处 case 4: self.GenerateOneFinalPatternGroupsForKaoNotAllHZ_DC(rpTypes, hzRPPatterns, singleCards) default: logger.Error("剩余的单牌数量只能是:1, 2, 4") } } //产生一组最终的模式,对于靠牌非全红中的情况下的单调 func (self *HuController) GenerateOneFinalPatternGroupsForKaoNotAllHZ_DD_SZ(rpTypes []int32, hzRPPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { //1.检查输入参数 if len(rpTypes) <= 0 || len(singleCards) <= 0 { logger.Error("替换类型为空。") return } //排序单牌 sort.Sort(CardList(singleCards)) normalCards, hongZhongCards := SplitCards(singleCards) if len(normalCards) <= 0 { logger.Error("在非所有红中的模式下,不可能没有本牌") return } // szPatterns, otherSZPatterns := GetSZPatternsByType(hzRPPatterns, normalCards[0].cType) // szPatternsC, otherSZPatternsC := GetAllPatternsCombination(2, szPatterns, false) // if len(szPatternsC) != len(otherSZPatternsC) { // logger.Error("获取所有模式的组合情况不正确!") // for _, szP := range szPatternsC { // PrintPatternsS("szPatternsC:", szP) // } // for _, szP := range otherSZPatternsC { // PrintPatternsS("otherSZPatternsC:", szP) // } // return // } //PrintPatternsS("本牌靠牌对应的顺子:", szPatterns) // for i, szP := range szPatternsC { // PrintPatternsS("本牌靠牌对应的顺子可能组合情况:", szP) // PrintPatternsS("本牌靠牌对应的顺子可能组合情况_剩余的模式组:", otherSZPatternsC[i]) // } switch len(singleCards) { //在非全红中的情况下,如果只有一个牌的话,那么这个牌一定不是红中,所以不用考虑singleCards的替换情况 case 1: // if len(szPatternsC) > 0 { // for i, szC := range szPatternsC { // fixedPatterns := append(otherSZPatterns, otherSZPatternsC[i]...) // addType, sortedPatterns := self.CalcAddPosForSZ(szC, singleCards) // logger.Info("顺子的替换未知(前,中,后等)AddType:%d", addType) // PrintPatternsS("本牌靠牌对应的顺子可能组合情况:", sortedPatterns) // if addType != UnknowAdd { // self.CalcAddForSZ(addType, sortedPatterns, singleCards, fixedPatterns) // } else { // pg := NewPatternGroup(append(fixedPatterns, ClonePatterns(szC)...)) // tempCard := *singleCards[0] // pg.kaoCards = []*MaJiangCard{&tempCard} // curCType, curValue := tempCard.CurValue() // pg.huCards = []*MaJiangCard{NewCard(0, curCType, curValue)} // self.AddOnePatternGroup(pg) // } // } // } else { pg := NewPatternGroup(hzRPPatterns) tempCard := *singleCards[0] pg.kaoCards = []*MaJiangCard{&tempCard} curCType, curValue := tempCard.CurValue() pg.huCards = []*MaJiangCard{NewCard(0, curCType, curValue)} self.AddOnePatternGroup(pg) //} case 2: //计算可以替换顺子的列表 rpCardsList := make([][]*MaJiangCard, 0) if len(hongZhongCards) == 1 { rpType := normalCards[0].cType nVal := normalCards[0].value if nVal-1 > 0 { clonedCard := *hongZhongCards[0] clonedCard.SetHZReplaceValue(rpType, nVal-1) rpCardsList = append(rpCardsList, []*MaJiangCard{&clonedCard, normalCards[0]}) } if nVal+1 <= 9 { clonedCard := *hongZhongCards[0] clonedCard.SetHZReplaceValue(rpType, nVal+1) rpCardsList = append(rpCardsList, []*MaJiangCard{normalCards[0], &clonedCard}) } } else { rpCardsList = append(rpCardsList, normalCards) } //生成模式组 for _, rpSingleCards := range rpCardsList { //for i, szC := range szPatternsC { // fixedPatterns := append(otherSZPatterns, otherSZPatternsC[i]...) // addType, sortedPatterns := self.CalcAddPosForSZ(szC, rpSingleCards) // if addType != UnknowAdd { // self.CalcAddForSZ(addType, sortedPatterns, rpSingleCards, fixedPatterns) // } else { pg := NewPatternGroup(hzRPPatterns) firstCard := *rpSingleCards[0] secondCard := *rpSingleCards[1] pg.kaoCards = []*MaJiangCard{&firstCard, &secondCard} pg.huCards = []*MaJiangCard{} valOffset := firstCard.value - secondCard.value switch valOffset { case -2, 2: pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, (firstCard.value+secondCard.value)/2)) case -1: if firstCard.value-1 > 0 { pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, firstCard.value-1)) } if secondCard.value+1 <= 9 { pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, secondCard.value+1)) } case 1: if secondCard.value-1 > 0 { pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, secondCard.value-1)) } if firstCard.value+1 <= 9 { pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, firstCard.value+1)) } default: logger.Error("值有问题!first:%d, second:%d", firstCard.value, secondCard.value) } self.AddOnePatternGroup(pg) //} //} } default: logger.Error("只能1或2单牌") } } //产生一组最终的模式,对于靠牌非全红中的情况下的对处 func (self *HuController) GenerateOneFinalPatternGroupsForKaoNotAllHZ_DC(rpTypes []int32, hzRPPatterns []*MaJiangPattern, singleCards []*MaJiangCard) { if len(singleCards) != 4 { logger.Error("对处的单牌必须是4张!") return } normalCards, hongZhongCards := SplitCards(singleCards) if len(normalCards) <= 0 { logger.Error("必须要有个本牌!") return } AAPatterns, tempSingleCards := SplitToAA_A(normalCards) switch len(hongZhongCards) { case 0: if len(AAPatterns) != 2 { logger.Error("必须是两个对子模式!") break } pg := NewPatternGroup(hzRPPatterns) pg.kaoCards = CloneMaJiangCards(singleCards) pg.huCards = []*MaJiangCard{ NewCard(0, AAPatterns[0].cards[0].cType, AAPatterns[0].cards[0].value), NewCard(0, AAPatterns[1].cards[0].cType, AAPatterns[1].cards[0].value)} self.AddOnePatternGroup(pg) case 1: if len(AAPatterns) != 1 { logger.Error("必须有一个本牌的对子模式!") break } pg := NewPatternGroup(hzRPPatterns) tempHongZhong := *hongZhongCards[0] curCType, curValue := tempSingleCards[0].CurValue() tempHongZhong.SetHZReplaceValue(curCType, curValue) pg.kaoCards = append(normalCards, &tempHongZhong) pg.huCards = []*MaJiangCard{NewCard(0, AAPatterns[0].cards[0].cType, AAPatterns[0].cards[0].value), NewCard(0, curCType, curValue)} self.AddOnePatternGroup(pg) case 2: if len(AAPatterns) == 1 { for _, rpType := range rpTypes { for i := 1; i <= 9; i++ { pg := NewPatternGroup(hzRPPatterns) tempHongZhong1 := *hongZhongCards[0] tempHongZhong2 := *hongZhongCards[1] tempHongZhong1.SetHZReplaceValue(rpType, int32(i)) tempHongZhong2.SetHZReplaceValue(rpType, int32(i)) pg.kaoCards = append(normalCards, &tempHongZhong1) pg.kaoCards = append(pg.kaoCards, &tempHongZhong2) pg.huCards = []*MaJiangCard{NewCard(0, AAPatterns[0].cards[0].cType, AAPatterns[0].cards[0].value)} pg.huCards = append(pg.huCards, NewCard(0, rpType, int32(i))) self.AddOnePatternGroup(pg) } } } else { pg := NewPatternGroup(hzRPPatterns) tempHongZhong1 := *hongZhongCards[0] tempHongZhong2 := *hongZhongCards[1] tempHongZhong1.SetHZReplaceValue(normalCards[0].cType, normalCards[0].value) tempHongZhong2.SetHZReplaceValue(normalCards[1].cType, normalCards[1].value) pg.kaoCards = append(normalCards, &tempHongZhong1) pg.kaoCards = append(pg.kaoCards, &tempHongZhong2) pg.huCards = []*MaJiangCard{ NewCard(0, normalCards[0].cType, normalCards[0].value), NewCard(0, normalCards[1].cType, normalCards[1].value)} self.AddOnePatternGroup(pg) } case 3: for _, rpType := range rpTypes { for i := 1; i <= 9; i++ { pg := NewPatternGroup(hzRPPatterns) tempHongZhong1 := *hongZhongCards[0] tempHongZhong2 := *hongZhongCards[1] tempHongZhong1.SetHZReplaceValue(rpType, int32(i)) tempHongZhong2.SetHZReplaceValue(rpType, int32(i)) tempHongZhong3 := *hongZhongCards[2] tempHongZhong3.SetHZReplaceValue(normalCards[0].cType, normalCards[0].value) pg.kaoCards = append(normalCards, &tempHongZhong1) pg.kaoCards = append(pg.kaoCards, &tempHongZhong2) pg.kaoCards = append(pg.kaoCards, &tempHongZhong3) pg.huCards = []*MaJiangCard{NewCard(0, rpType, int32(i))} pg.huCards = append(pg.huCards, NewCard(0, normalCards[0].cType, normalCards[0].value)) self.AddOnePatternGroup(pg) } } default: logger.Error("红只可能是0, 1, 2和3个的情况!") } } //叠加情况 const ( UnknowAdd = iota FrontAdd BackAdd MiddleAdd ) //计算叠加位置 func (self *HuController) CalcAddPosForSZ(patterns []*MaJiangPattern, singleCards []*MaJiangCard) (addType int32, sortedPatterns []*MaJiangPattern) { addType = UnknowAdd sortedPatterns = patterns if len(patterns) <= 0 { return } switch len(patterns) { case 1: //确定addType switch len(singleCards) { case 1: if patterns[0].cards[0].value-singleCards[0].value == 1 { addType = FrontAdd } if singleCards[0].value-patterns[0].cards[2].value == 1 { addType = BackAdd } case 2: if singleCards[1].value-singleCards[0].value == 1 { if patterns[0].cards[0].value-singleCards[1].value == 1 { addType = FrontAdd } if singleCards[0].value-patterns[0].cards[2].value == 1 { addType = BackAdd } } default: logger.Error("不能支持超过2个的单牌数量!") } case 2: //对patterns进行排序 firstPattern := patterns[0] secondPattern := patterns[1] if firstPattern.cards[0].value > secondPattern.cards[0].value { firstPattern = patterns[1] secondPattern = patterns[0] } sortedPatterns = []*MaJiangPattern{firstPattern, secondPattern} //确定addType switch len(singleCards) { case 1: patternInterval := secondPattern.cards[0].value - firstPattern.cards[2].value if patternInterval == 1 { if firstPattern.cards[0].value-singleCards[0].value == 1 { addType = FrontAdd } if singleCards[0].value-secondPattern.cards[2].value == 1 { addType = BackAdd } } else if patternInterval == 2 { if singleCards[0].value-firstPattern.cards[2].value == 1 { addType = MiddleAdd } } case 2: patternInterval := secondPattern.cards[0].value - firstPattern.cards[2].value if patternInterval == 1 { if singleCards[1].value-singleCards[0].value == 1 { if firstPattern.cards[0].value-singleCards[1].value == 1 { addType = FrontAdd } if singleCards[0].value-secondPattern.cards[2].value == 1 { addType = BackAdd } } } else if patternInterval == 3 { if singleCards[0].value-firstPattern.cards[2].value == 1 { addType = MiddleAdd } } default: logger.Error("不能支持超过2个的单牌数量!") } default: logger.Error("不支持超过两个的pattern!") PrintPatternsS("不支持超过两个的pattern:", patterns) } return } //计算单牌和已有顺子模式的叠加情况 func (self *HuController) CalcAddForSZ(addType int32, patterns []*MaJiangPattern, singleCards []*MaJiangCard, fixedPatterns []*MaJiangPattern) { //检查输入参数 if len(patterns) <= 0 || len(singleCards) <= 0 { logger.Error("patterns or singleCards is nil:", patterns, singleCards) return } singleAmount := len(singleCards) if !(singleAmount == 1 || singleAmount == 2) { logger.Error("不是顺子的方式") return } tempCards := []*MaJiangCard{} switch addType { case FrontAdd: tempCards = append(tempCards, singleCards...) for _, p := range patterns { tempCards = append(tempCards, p.cards...) } case BackAdd: for _, p := range patterns { tempCards = append(tempCards, p.cards...) } tempCards = append(tempCards, singleCards...) case MiddleAdd: if len(patterns) != 2 { logger.Error("中间添加的话,必须是两个模式,才能被放在中间!") return } firstP := patterns[0] tempCards = append(tempCards, firstP.cards...) tempCards = append(tempCards, singleCards...) secondP := patterns[1] tempCards = append(tempCards, secondP.cards...) default: logger.Error("添加类型错误!") } //检查牌的最低限制 clonedTempCards := CloneMaJiangCards(tempCards) clonedTCAmount := len(clonedTempCards) PrintCardsS("CalcAddForSZ.clonedTempCards:", clonedTempCards) tempSingleCardAmount := clonedTCAmount % 3 switch tempSingleCardAmount { case 1: if clonedTCAmount < 4 { logger.Error("至少是4张牌") return } for i := 0; i < clonedTCAmount; i += 3 { remainPtns := []*MaJiangPattern{} if i == 0 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+1:i+4], false)) if clonedTCAmount >= 7 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+4:i+7], false)) } } else if i == 3 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-3:i], false)) if clonedTCAmount >= 7 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+1:i+4], false)) } } else if i == 6 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-6:i-3], false)) if clonedTCAmount >= 7 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-3:i], false)) } } else { logger.Error("不应该出现其他的情况") } // PrintPatternsS("CalcAddForSZ.fixedPatterns:", fixedPatterns) // PrintPatternsS("CalcAddForSZ.remainPtns:", remainPtns) resultPtns := []*MaJiangPattern{} resultPtns = append(resultPtns, fixedPatterns...) pg := NewPatternGroup(append(resultPtns, remainPtns...)) pg.kaoCards = []*MaJiangCard{clonedTempCards[i]} curCType, curValue := clonedTempCards[i].CurValue() pg.huCards = []*MaJiangCard{NewCard(0, curCType, curValue)} self.AddOnePatternGroup(pg) //PrintPatternGroupsS("CalcAddForSZ.patternGroups", self.patternGroups, true) } case 2: if clonedTCAmount < 5 { logger.Error("至少是5张牌") return } for i := 0; i < clonedTCAmount; i += 3 { remainPtns := []*MaJiangPattern{} if i == 0 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+2:i+5], false)) if clonedTCAmount >= 8 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+5:i+8], false)) } } else if i == 3 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-3:i], false)) if clonedTCAmount >= 8 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i+2:i+5], false)) } } else if i == 6 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-6:i-3], false)) if clonedTCAmount >= 8 { remainPtns = append(remainPtns, NewPattern(PTSZ, clonedTempCards[i-3:i], false)) } } else { logger.Error("不应该出现其他的情况") } resultPtns := []*MaJiangPattern{} resultPtns = append(resultPtns, fixedPatterns...) pg := NewPatternGroup(append(resultPtns, remainPtns...)) pg.kaoCards = []*MaJiangCard{clonedTempCards[i], clonedTempCards[i+1]} prevCType, prevValue := clonedTempCards[i].CurValue() backCType, backValue := clonedTempCards[i+1].CurValue() pg.huCards = []*MaJiangCard{} if prevValue-1 > 0 { pg.huCards = append(pg.huCards, NewCard(0, prevCType, prevValue-1)) } if backValue+1 <= 9 { pg.huCards = append(pg.huCards, NewCard(0, backCType, backValue+1)) } self.AddOnePatternGroup(pg) } default: logger.Error("只能是1或2!") } } //添加一个模式组到最终的模式组里 func (self *HuController) AddOnePatternGroup(pg *MaJiangPatternGroup) { if pg == nil { return } pg.GenerateID() if !IsExistPatternGroup(self.patternGroups, pg) { logger.Info("在添加到最终模式组列表时检查是否重复:ID:", pg.id) self.patternGroups = append(self.patternGroups, pg) } } //仅需要产生大对子胡模式组吗 func (self *HuController) IsOnlyGenerateDaDuiZi(cardAmount, hzCardAmount int32) bool { if cardAmount == 13 { return false } return cardAmount*2 < hzCardAmount } //仅需要产生小七对胡模式组吗 func (self *HuController) IsOnlyGenerateXiaoQiDui(cardAmount, hzCardAmount int32) bool { if cardAmount != 13 { return false } return cardAmount < hzCardAmount } //检查是否存在相同的PatternGroup func IsExistPatternGroup(pgs []*MaJiangPatternGroup, pg *MaJiangPatternGroup) bool { if len(pgs) <= 0 { return false } for _, p := range pgs { if p.IsEqual(pg) { return true } } return false } //检查靠能否胡牌 func CanHu(cards []*MaJiangCard) bool { //检查数量 cardAmount := len(cards) if !(cardAmount == 1 || cardAmount == 2 || cardAmount == 4) { logger.Error("剩余检查胡的牌的数量只能是1, 2, 4") return false } //检查两张牌时 if cardAmount == 2 && GetHongZhongAmount(cards) <= 0 { //检查花色 if !IsSameHuaSe(cards, false) { return false } valOffset := cards[0].value - cards[1].value if valOffset > 2 || valOffset < -2 || valOffset == 0 { return false } } //检查4张牌时 if cardAmount == 4 { normalcards, hongZhongCards := SplitCards(cards) AAPatterns, _ := SplitToAA_A(normalcards) hzAmount := len(hongZhongCards) AAAmount := len(AAPatterns) if AAAmount == 0 && hzAmount <= 1 { return false } if AAAmount == 1 && hzAmount <= 0 { return false } } return true } //分开本牌和红中 func SplitCards(cards []*MaJiangCard) (normalCards, hongZhongCards []*MaJiangCard) { normalCards = make([]*MaJiangCard, 0) hongZhongCards = make([]*MaJiangCard, 0) if len(cards) <= 0 { //logger.Error("cards is empty!") return } for _, c := range cards { if c.IsHongZhong() { hongZhongCards = append(hongZhongCards, c) } else { normalCards = append(normalCards, c) } } return } //分开本牌和红中 func SplitCardsToHuaSe(normalCards []*MaJiangCard) (splitedCards map[int32][]*MaJiangCard) { splitedCards = make(map[int32][]*MaJiangCard, 0) if len(normalCards) <= 0 { return } for _, c := range normalCards { _, exist := splitedCards[c.cType] if !exist { splitedCards[c.cType] = []*MaJiangCard{} } splitedCards[c.cType] = append(splitedCards[c.cType], c) } return } //分割全红中和非全红中的模式 func SplitPatterns(patterns []*MaJiangPattern) (notAllHZPatterns, allHZPatterns []*MaJiangPattern) { notAllHZPatterns = make([]*MaJiangPattern, 0) allHZPatterns = make([]*MaJiangPattern, 0) if len(patterns) <= 0 { return } for _, p := range patterns { if p.IsAllHZ() { allHZPatterns = append(allHZPatterns, p) } else { notAllHZPatterns = append(notAllHZPatterns, p) } } return } //分割不同花色的模式 func SplitHuaSePatterns(patterns []*MaJiangPattern) (result map[int32][]*MaJiangPattern) { result = make(map[int32][]*MaJiangPattern, 0) if len(patterns) <= 0 { return } notAllHZPatterns, allHZPatterns := SplitPatterns(patterns) result[HongZhong] = allHZPatterns result[Tiao] = []*MaJiangPattern{} result[Tong] = []*MaJiangPattern{} result[Wan] = []*MaJiangPattern{} for _, p := range notAllHZPatterns { for _, c := range p.cards { if !c.IsHongZhong() { result[c.cType] = append(result[c.cType], p) break } } } return } //获取指定花色的顺子 func GetSZPatternsByType(patterns []*MaJiangPattern, cType int32) (result, other []*MaJiangPattern) { result = make([]*MaJiangPattern, 0) other = make([]*MaJiangPattern, 0) if len(patterns) <= 0 { return } for _, p := range patterns { isFind := false if p.ptype == PTSZ { for _, c := range p.cards { if cType == c.cType { result = append(result, p) isFind = true break } } } if !isFind { other = append(other, p) } } return } //获取1或2个模式的所有组合情况 func GetAllPatternsCombination(n int, patterns []*MaJiangPattern, isOnlyN bool) (result, other [][]*MaJiangPattern) { result = make([][]*MaJiangPattern, 0) other = make([][]*MaJiangPattern, 0) patternAmount := len(patterns) if patternAmount <= 0 { result = append(result, []*MaJiangPattern{}) other = append(other, []*MaJiangPattern{}) return } if n <= 0 { result = append(result, []*MaJiangPattern{}) temp := make([]*MaJiangPattern, len(patterns)) copy(temp, patterns) other = append(other, temp) return } //生成用于进行排列组合的下标 indexes := make([]int32, patternAmount) for i := 0; i < patternAmount; i++ { indexes[i] = int32(i) } //进行组合 maxCAmount := int(math.Min(float64(patternAmount), float64(n))) i := 1 if isOnlyN { i = maxCAmount } for ; i <= maxCAmount; i++ { cIndexes := C(int32(i), int32(patternAmount)) for _, cIndex := range cIndexes { //没有选择中的添加到列表里 tempOther := []*MaJiangPattern{} remainIndexes := Exclude(indexes, cIndex) for _, ri := range remainIndexes { tempOther = append(tempOther, ClonePattern(patterns[ri])) } other = append(other, tempOther) //把选择中的添加到列表里 temp := []*MaJiangPattern{} for _, index := range cIndex { temp = append(temp, ClonePattern(patterns[index])) } result = append(result, temp) } } return } //获取顺子的组合情况 func GetSZPatternsCombination(n int, patterns []*MaJiangPattern) (result [][]*MaJiangPattern) { patternAmount := len(patterns) cIndexes := C(int32(n), int32(patternAmount)) for _, cIndex := range cIndexes { temp := []*MaJiangPattern{} for _, index := range cIndex { temp = append(temp, patterns[index]) } result = append(result, temp) } return } //克隆Patterns列表 func ClonePatterns(src []*MaJiangPattern) (dst []*MaJiangPattern) { if src == nil { return } dst = make([]*MaJiangPattern, len(src)) for i, v := range src { dst[i] = ClonePattern(v) } return } //克隆一个Pattern func ClonePattern(src *MaJiangPattern) (dst *MaJiangPattern) { if src == nil { return } dst = &MaJiangPattern{} dst.id = src.id dst.ptype = src.ptype dst.cType = src.cType dst.cards = CloneMaJiangCards(src.cards) dst.isShowPattern = src.isShowPattern return } //复制牌 func CloneMaJiangCards(src []*MaJiangCard) (dst []*MaJiangCard) { if src == nil { return nil } dst = make([]*MaJiangCard, len(src)) for i, v := range src { temp := *v dst[i] = &temp } return } //获取除自定数字以外的其他数字 func Exclude(ids []int32, excludeIds []int32) []int32 { if len(ids) <= 0 || len(excludeIds) <= 0 { return ids } result := []int32{} for _, id := range ids { if !Exist(excludeIds, id) { result = append(result, id) } } return result } //生成模式的组合下标 func C(n int32, m int32) (result [][]int32) { if n > m { logger.Error("n must be less than m", n, m) return nil } // fmt.Println("组合数量:", n, m, size) result = make([][]int32, 0) index := make([]int32, m) //fmt.Println(m, index) for i := 0; int32(i) < m; i++ { index[i] = 0 } for i := 0; int32(i) < n; i++ { index[i] = 1 } result = append(result, GetC(index)) for true { for i := 0; int32(i) < m-1; i++ { if index[i] == 1 && index[i+1] == 0 { oneIndex := 0 for j := 0; j < i; j++ { if index[j] == 1 { index[j] = 0 index[oneIndex] = 1 oneIndex++ } } index[i] = 0 index[i+1] = 1 result = append(result, GetC(index)) break } } //check is end isEnd := true for k := m - n; k < m; k++ { if index[k] != 1 { isEnd = false break } } if isEnd { break } } return } func GetC(index []int32) (result []int32) { result = make([]int32, 0) for i := 0; i < len(index); i++ { if index[i] == 1 { result = append(result, int32(i)) } } return } //检查是否是全红中的牌 func IsAllHongZhong(cards []*MaJiangCard) bool { return int32(len(cards)) == GetHongZhongAmount(cards) } //获取红中的数量 func GetHongZhongAmount(cards []*MaJiangCard) (result int32) { result = 0 if len(cards) <= 0 { return result } for _, c := range cards { if c.IsHongZhong() { result++ } } return result } //检查是否是同一种牌类型 func IsSameHuaSe(cards []*MaJiangCard, checkHZ bool) bool { if len(cards) <= 0 { return true } tempCards := make([]*MaJiangCard, len(cards)) copy(tempCards, cards) //移除红中 for !checkHZ { curIndex := 0 for i, c := range tempCards { curIndex = i if c.IsHongZhong() { tempCards = append(tempCards[:i], tempCards[i+1:]...) break } } //全部检查完了 if curIndex+1 >= len(tempCards) { break } } //检查是否花色相同 if len(tempCards) > 0 { firstCard := tempCards[0] for _, c := range tempCards { if firstCard.cType != c.cType { return false } } } return true } //从一个切片中移除指定类型的Card func RemoveCardByType(cards []*MaJiangCard, cType, value int32) (success bool, result []*MaJiangCard) { if cards == nil { logger.Error("RemoveCardByType:cards is nil.") return false, nil } for i, v := range cards { curCType, curVal := v.CurValue() if curVal == value && curCType == cType { cards = append(cards[:i], cards[i+1:]...) return true, cards } } return false, cards } //从一个切片中移除指定类型的多个Card func RemoveCardsByType(cards []*MaJiangCard, cType, value, wantRemovedAmount int32) (result []*MaJiangCard, outRemovedCards []*MaJiangCard) { if cards == nil { logger.Error("RemoveCardsByType:cards is nil.") return } //removedAmount := 0 result = make([]*MaJiangCard, 0) outRemovedCards = make([]*MaJiangCard, 0) for i, v := range cards { if int32(len(outRemovedCards)) >= wantRemovedAmount { result = append(result, cards[i:]...) break } if !v.IsEqualByTypeAndValue(cType, value) { result = append(result, v) } else { outRemovedCards = append(outRemovedCards, v) } } return } //在列表中查找指定的Card– func FindCard(cards []*MaJiangCard, cType, val int32) *MaJiangCard { if cards == nil { logger.Error("FindCard:cards is nil.") return nil } for i, v := range cards { if v.IsEqualByTypeAndValue(cType, val) { return cards[i] } } return nil } //在列表中查找指定的Card func FindCards(cards []*MaJiangCard, cType, val int32) []*MaJiangCard { if cards == nil { logger.Error("FindCards:cards is nil.") return nil } result := []*MaJiangCard{} for i, v := range cards { if v.IsEqualByTypeAndValue(cType, val) { result = append(result, cards[i]) } } return result } // package majiangserver // import ( // cmn "common" // //"fmt" // "logger" // "math" // "time" // ) // const ( // ESuccess = iota // ECardNull // ETypeAmountMuch // ECardFullSame // ) // type HuController struct { // patternGroups []*MaJiangPatternGroup // //allpatternGroups []*MaJiangPatternGroup // originCards []*MaJiangCard // cards []*MaJiangCard // rmCardsAmountInfo *CardAmountStatistics //替换模式下的卡牌数量 // //notrmCardAmountInfo *CardAmountStatistics //非替换模式下的卡牌数量 // player *MaJiangPlayer // } // func NewHuController(p *MaJiangPlayer) *HuController { // huC := &HuController{player: p} // return huC // } // //初始化函数 ,调用完次函数后,就可以直接获取成员数据了 // func (self *HuController) UpdateData(cards []*MaJiangCard) { // //check input param // if cards == nil || len(cards) <= 0 { // logger.Error("UpdateData:cards is nil.") // return // } // //need check hu // logger.Info("更新胡:") // if eReason := self.needUpdate(cards); eReason != ESuccess { // logger.Info("不需要更新:", eReason) // //当以前是能够胡牌的,但是摸了一张不同花色的牌导致现在有不能胡了要把以前的胡的模式组给清除掉 // if eReason == ETypeAmountMuch { // self.patternGroups = make([]*MaJiangPatternGroup, 0) // } // return // } // logger.Info("开始计算胡数") // //cache card && statistics card amount // self.originCards = make([]*MaJiangCard, len(cards)) // copy(self.originCards, cards) // //self.notrmCardAmountInfo = NewCardAmountStatisticsByCards(cards, false) // self.patternGroups = make([]*MaJiangPatternGroup, 0) // //self.allpatternGroups = make([]*MaJiangPatternGroup, 0) // // replace hongzhong value && statistics card amount // player := self.player // if player == nil { // logger.Error("HuController.player is nil.") // return // } // self.cards = CloneMaJiangCards(cards) // hongZhongCards := GetSpecificTypeCardsByCardsList(self.cards, HongZhong, false) // hongZhongAmount := len(hongZhongCards) // hongZhongCardsInReplaceMode := GetSpecificTypeCardsByCardsList(self.cards, HongZhong, true) // //没有红中不需要进行替换,或者红中是已经被替换掉的 // if hongZhongAmount <= 0 || len(hongZhongCardsInReplaceMode) <= 0 { // //统计这一组替换的牌的数量信息 // self.rmCardsAmountInfo = NewCardAmountStatisticsByCards(self.cards, true) // PrintCardsS("这一组替换后的手牌:", cards) // curTime := time.Now() // //生成特殊的胡牌模式组 // self.GenerateSpecificPatternGroup() // //生成可以胡牌的模式组,将结果保存在成员中 // self.GeneratePatternGroup() // logger.Info("一次完整的计算胡用时:", time.Now().Sub(curTime)) // } else { // curTime := time.Now() // canReplaceTypes := player.GetCanReplaceType() // replaceList := GetReplaceList(int32(hongZhongAmount), canReplaceTypes) // logger.Info("红中数量:%d, replaceListLen:%d, 能替换的类型:", hongZhongAmount, len(replaceList), canReplaceTypes, " 计算红中替换列表耗时:", time.Now().Sub(curTime)) // for _, replaceGroup := range replaceList { // if replaceGroup == nil || len(replaceGroup) <= 0 { // continue // } // if len(replaceGroup) != hongZhongAmount { // logger.Error("替代牌的数量和红中的数量不匹配") // continue // } // //将红中的牌复制一份,再进行替换 // tempCards, clonedHongZhong := CloneHongZhong(self.cards) // self.cards = tempCards // //设置一组替换值并计算胡 // for i, replace := range replaceGroup { // hongZhong := clonedHongZhong[i] // if hongZhong == nil { // logger.Error("红中牌竟然是nil.") // continue // } // hongZhong.SetHZReplaceValue(replace.rType, replace.rValue) // } // //统计这一组替换的牌的数量信息 // self.rmCardsAmountInfo = NewCardAmountStatisticsByCards(self.cards, true) // PrintCardsS("这一组替换后的手牌:", cards) // //生成特殊的胡牌模式组 // self.GenerateSpecificPatternGroup() // //生成可以胡牌的模式组,将结果保存在成员中 // self.GeneratePatternGroup() // } // logger.Info("一次完整的计算胡用时:", time.Now().Sub(curTime)) // //打印最终的结果 // PrintPatternGroupsS("最终结果:", self.patternGroups, true) // } // } // //检查是否需要重新算胡牌,牌没变化就用算了 // func (self *HuController) needUpdate(cards []*MaJiangCard) int32 { // //check input param // if cards == nil { // logger.Error("needUpdate:cards is nil.") // return ECardNull // } // //check type amount // if self.player != nil { // fixedTypeList := self.player.GetTypeInfoInShowPattern() // amountInfo := NewCardAmountStatisticsByCards(cards, false) // typeAmount := amountInfo.GetTypeAmount(false, fixedTypeList) // if typeAmount > int32(2-len(fixedTypeList)) { // return ETypeAmountMuch // } // } // //check card amount is same // if len(self.originCards) != 0 && len(self.originCards) != len(cards) { // return ESuccess // } // //is same // tempCards := make([]*MaJiangCard, len(cards)) // copy(tempCards, cards) // for _, v := range self.originCards { // cType, cVal := v.CurValue() // tempCards = RemoveCardByType(tempCards, cType, cVal) // } // isSame := len(tempCards) <= 0 // if isSame { // return ECardFullSame // } // return ESuccess // } // //产生模式组 // func (self *HuController) GeneratePatternGroup() { // curTime := time.Now() // //获取去重后的所有模式 // patterns := self.StatisticsAllPattern() // logger.Info("获取所有的准模式:", len(patterns), "用时:", time.Now().Sub(curTime)) // PrintPatterns(patterns) // //然后对这些模式进行组合,形成模式组(一套可胡牌的模式列表) // curTime = time.Now() // n := math.Min(float64(len(self.cards)/3), float64(len(patterns))) // patternGroups := self.CalcPatternGroup(int(n), patterns) // logger.Info("zuhe:", n, len(patterns)) // PrintPatterns(patterns) // logger.Info("进行模式的组合:", len(patternGroups), "用时:", time.Now().Sub(curTime)) // PrintPatternGroups(patternGroups, false) // //没有模式组可以生成时,检查手牌,是否只剩下1或2张牌了 // if patternGroups == nil || len(patternGroups) <= 0 { // cardCount := len(self.cards) // switch cardCount { // case 0: // fallthrough // case 1: // fallthrough // case 2: // patternGroups = []*MaJiangPatternGroup{NewPatternGroup([]*MaJiangPattern{})} // default: // // self.patternGroups = make([]*MaJiangPatternGroup, 0) // // self.allpatternGroups = make([]*MaJiangPatternGroup, 0) // return // } // } // //计算出每种模式组中的单牌 // curTime = time.Now() // singleCardInpatternGroups := self.GetSingleCardInPatternGroup(patternGroups) // logger.Info("计算每组模式的单牌:", len(singleCardInpatternGroups), "用时:", time.Now().Sub(curTime)) // //最后通过每个模式组中的单牌来计算胡的牌 // curTime = time.Now() // patternGroups = self.CalcHu(singleCardInpatternGroups, patternGroups) // logger.Info("计算每组模式的胡:", "用时:", time.Now().Sub(curTime)) // //剔除不能胡的牌 // curTime = time.Now() // patternGroups = self.StripNoHuPatternGroup(patternGroups) // logger.Info("剔除不能胡的牌:", len(patternGroups), "用时:", time.Now().Sub(curTime)) // //生成模式组的ID // curTime = time.Now() // self.GeneratePatternGroupID(patternGroups) // logger.Info("生成模式组的ID 用时:", time.Now().Sub(curTime)) // //剔除当前的重复模式组 // curTime = time.Now() // patternGroups = self.StripSamePatternGroup(patternGroups) // logger.Info("剔除当前的重复模式组 用时:", time.Now().Sub(curTime)) // PrintPatternGroups(patternGroups, false) // //剔除重复的模式组 // curTime = time.Now() // self.patternGroups = append(self.patternGroups, patternGroups...) // //self.patternGroups = self.StripSamePatternGroup(self.patternGroups) // logger.Info("剔除总的重复的模式组 用时:", time.Now().Sub(curTime)) // PrintPatternGroupsS("剔除总的重复的模式组 用时:", self.patternGroups, false) // } // //产生特殊模式组 // func (self *HuController) GenerateSpecificPatternGroup() { // logger.Info("HuController.GenerateSpecificPatternGroup: 手牌数量:", len(self.cards)) // //小七对 // if len(self.cards) == 13 { // tempCards := make([]*MaJiangCard, len(self.cards)) // copy(tempCards, self.cards) // partternList := make([]*MaJiangPattern, 0) // singleCards := make([]*MaJiangCard, 0) // for len(tempCards) > 0 && len(singleCards) <= 1 { // for _, c := range tempCards { // cType, cVal := c.CurValue() // tempCards = RemoveCardByType(tempCards, cType, cVal) // findCard := FindCard(tempCards, cType, cVal) // //没有此牌的对子,那么此牌为单牌 // if findCard == nil { // singleCards = append(singleCards, c) // } else { // tempCards = RemoveCardByType(tempCards, cType, cVal) // partternList = append(partternList, NewPattern(PTPair, []*MaJiangCard{c, findCard}, false)) // } // break // } // PrintCardsS("HuController.GenerateSpecificPatternGroup:当前的手牌情况", tempCards) // PrintCardsS("HuController.GenerateSpecificPatternGroup:当前的单牌情况", singleCards) // } // PrintCardsS("HuController.GenerateSpecificPatternGroup:最后单牌的情况:", singleCards) // if len(singleCards) == 1 { // patternGroup := NewPatternGroup(partternList) // patternGroup.GenerateID() // cType, cVal := singleCards[0].CurValue() // patternGroup.kaoCards = append(patternGroup.kaoCards, singleCards[0]) // patternGroup.huCards = append(patternGroup.huCards, &MaJiangCard{value: cVal, cType: cType, flag: cmn.CUnknown}) // self.patternGroups = append(self.patternGroups, patternGroup) // } // } // //2个或3个四张的牌 // fourCards := self.rmCardsAmountInfo.GetCardsBySpecificAmount(4, nil) // if len(fourCards) >= 2 { // tempCards := make([]*MaJiangCard, len(self.cards)) // copy(tempCards, self.cards) // partternList := make([]*MaJiangPattern, len(fourCards)) // //统计四个的模式 // for i, c := range fourCards { // cType, cVal := c.CurValue() // var removedCards []*MaJiangCard = nil // tempCards, removedCards = RemoveCardsByType(tempCards, cType, cVal, 4) // partternList[i] = NewPattern(PTGang, removedCards, false) // } // //计算胡 // residueCardAmount := len(tempCards) // if residueCardAmount < 3 && residueCardAmount > 0 { // patternGroup := NewPatternGroup(partternList) // patternGroup.GenerateID() // calcHuPatterGroups := self.CalcHu([][]*MaJiangCard{tempCards}, []*MaJiangPatternGroup{patternGroup}) // calcHuPatterGroups = self.StripNoHuPatternGroup(calcHuPatterGroups) // if calcHuPatterGroups != nil { // self.patternGroups = append(self.patternGroups, calcHuPatterGroups...) // } // } else if residueCardAmount > 3 { // tempHuController := NewHuController(self.player) // tempHuController.UpdateData(tempCards) // for _, p := range tempHuController.patternGroups { // if p == nil { // continue // } // p.patterns = append(p.patterns, partternList...) // p.GenerateID() // } // self.patternGroups = append(self.patternGroups, tempHuController.patternGroups...) // } else { // logger.Error("没有这种胡牌,剩余牌的数量是:", residueCardAmount) // } // } // } // //统计出所有模式 // func (self *HuController) StatisticsAllPattern() (result []*MaJiangPattern) { // result = make([]*MaJiangPattern, 0) // for _, v := range self.cards { // patterns := StatisticsPattern(self.cards, v) // PrintCard(v) // PrintPatterns(patterns) // result = append(result, patterns...) // } // result = self.RemoveUselessPattern(result) // return // } // //统计单张牌的所有模式 // func StatisticsPattern(cards []*MaJiangCard, card *MaJiangCard) []*MaJiangPattern { // if cards == nil { // logger.Error("StatisticsPattern:cards is nil.") // return nil // } // if card == nil { // logger.Error("card is nil.") // return nil // } // result := make([]*MaJiangPattern, 0) // tempCards := make([]*MaJiangCard, 0) // tempCards = append(tempCards, cards...) // cType, cVal := card.CurValue() // tempCards = RemoveCardByType(tempCards, cType, cVal) // pattern := StatisticsAAAA(tempCards, card) // if pattern != nil { // result = append(result, pattern) // } // pattern = StatisticsAAA(tempCards, card) // if pattern != nil { // result = append(result, pattern) // } // pattern = StatisticsAA(tempCards, card) // if pattern != nil { // result = append(result, pattern) // } // pattern = StatisticsSZ(tempCards, card) // if pattern != nil { // result = append(result, pattern) // } // return result // } // //统计AAAA // func StatisticsAAAA(cards []*MaJiangCard, card *MaJiangCard) *MaJiangPattern { // if cards == nil { // logger.Error("StatisticsEQS:cards is nil.") // return nil // } // if card == nil { // logger.Error("card is nil.") // return nil // } // cType, cVal := card.CurValue() // findCards := FindCards(cards, cType, cVal) // if len(findCards) >= 3 { // return NewPattern(PTGang, []*MaJiangCard{findCards[0], findCards[1], findCards[2], card}, false) // } // return nil // } // //统计AAA // func StatisticsAAA(cards []*MaJiangCard, card *MaJiangCard) *MaJiangPattern { // if cards == nil { // logger.Error("StatisticsEQS:cards is nil.") // return nil // } // if card == nil { // logger.Error("card is nil.") // return nil // } // cType, cVal := card.CurValue() // findCards := FindCards(cards, cType, cVal) // if len(findCards) >= 2 { // return NewPattern(PTKan, []*MaJiangCard{findCards[0], findCards[1], card}, false) // } // return nil // } // //统计AA // func StatisticsAA(cards []*MaJiangCard, card *MaJiangCard) *MaJiangPattern { // if cards == nil { // logger.Error("StatisticsAA:cards is nil.") // return nil // } // if card == nil { // logger.Error("card is nil.") // return nil // } // cType, cVal := card.CurValue() // findCard := FindCard(cards, cType, cVal) // if findCard == nil { // return nil // } // return NewPattern(PTPair, []*MaJiangCard{card, findCard}, false) // } // //统计顺子 // func StatisticsSZ(cards []*MaJiangCard, card *MaJiangCard) *MaJiangPattern { // if cards == nil { // logger.Error("StatisticsSZ:cards is nil.") // return nil // } // if card == nil { // logger.Error("card is nil.") // return nil // } // cType, val := card.CurValue() // curNum := val - 1 // if curNum > 0 { // findCard := FindCard(cards, cType, curNum) // curNum-- // if findCard != nil && curNum > 0 { // secondFindCard := FindCard(cards, cType, curNum) // if secondFindCard != nil { // return NewPattern(PTSZ, []*MaJiangCard{card, findCard, secondFindCard}, false) // } // } // } // return nil // } // //移除多余的模式 // func (self *HuController) RemoveUselessPattern(patterns []*MaJiangPattern) (result []*MaJiangPattern) { // result = append(result, patterns...) // patternAmount := StatisticsPatternAmount(patterns) // for _, v := range patternAmount { // minAmount := int32(255) // if v[0].ptype == PTPair { // minAmount = 1 // } else { // for _, card := range v[0].cards { // cType, val := card.CurValue() // curCardAmount := self.rmCardsAmountInfo.GetCardAmount(cType, val) // if minAmount > curCardAmount { // minAmount = curCardAmount // } // } // } // for i := minAmount; i < int32(len(v)); i++ { // for k, r := range result { // if r.id == v[0].id { // result = append(result[:k], result[k+1:]...) // break // } // } // } // } // return // } // //统计相同模式的数量 // func StatisticsPatternAmount(patterns []*MaJiangPattern) (patternAmount map[int32][]*MaJiangPattern) { // if patterns == nil { // logger.Error("pattern is nil.") // return nil // } // patternAmount = make(map[int32][]*MaJiangPattern, 0) // if patterns == nil { // return patternAmount // } // for _, v := range patterns { // if patternAmount[v.id] == nil { // patternAmount[v.id] = make([]*MaJiangPattern, 0) // } // patternAmount[v.id] = append(patternAmount[v.id], v) // } // return // } // //从一个切片中移除指定类型的Card // func RemoveCardByType(cards []*MaJiangCard, cType, value int32) []*MaJiangCard { // if cards == nil { // logger.Error("RemoveCardByType:cards is nil.") // return nil // } // for i, v := range cards { // curCType, curVal := v.CurValue() // if curVal == value && curCType == cType { // cards = append(cards[:i], cards[i+1:]...) // break // } // } // return cards // } // //从一个切片中移除指定类型的多个Card // func RemoveCardsByType(cards []*MaJiangCard, cType, value, wantRemovedAmount int32) (result []*MaJiangCard, outRemovedCards []*MaJiangCard) { // if cards == nil { // logger.Error("RemoveCardsByType:cards is nil.") // return // } // //removedAmount := 0 // result = make([]*MaJiangCard, 0) // outRemovedCards = make([]*MaJiangCard, 0) // for i, v := range cards { // if int32(len(outRemovedCards)) >= wantRemovedAmount { // result = append(result, cards[i:]...) // break // } // if !v.IsEqualByTypeAndValue(cType, value) { // result = append(result, v) // } else { // outRemovedCards = append(outRemovedCards, v) // } // } // return // } // //在列表中查找指定的Card– // func FindCard(cards []*MaJiangCard, cType, val int32) *MaJiangCard { // if cards == nil { // logger.Error("FindCard:cards is nil.") // return nil // } // for i, v := range cards { // if v.IsEqualByTypeAndValue(cType, val) { // return cards[i] // } // } // return nil // } // //在列表中查找指定的Card // func FindCards(cards []*MaJiangCard, cType, val int32) []*MaJiangCard { // if cards == nil { // logger.Error("FindCards:cards is nil.") // return nil // } // result := []*MaJiangCard{} // for i, v := range cards { // if v.IsEqualByTypeAndValue(cType, val) { // result = append(result, cards[i]) // } // } // return result // } // //测试性能统计时间用的 // var cloneCardTime float64 = 0 // var checkTime float64 = 0 // var appendToContainerTime float64 = 0 // var stripSameTime float64 = 0 // var stripSameCompareTime float64 = 0 // //计算所有的模式组 // func (self *HuController) CalcPatternGroup(n int, patterns []*MaJiangPattern) (patternGroups []*MaJiangPatternGroup) { // //patternGroups = make([]*MaJiangPatternGroup, 0) // tempPatternGroups := make([]*MaJiangPatternGroup, 0) // if n <= 0 || len(patterns) <= 0 { // return // } // if n > len(patterns) { // logger.Error("n must be less than patterns's length. N:(%s) Patterns_Length:%s", n, len(patterns)) // PrintCards(self.cards) // return // } // curTime := time.Now() // result := C(n, len(patterns)) // //fmt.Println("生成排列组合数 用时:", time.Now().Sub(curTime).Seconds()) // //fmt.Println("模式组合数:", n, len(patterns), len(result)) // // for k, v := range tempSmallCardCount { // // fmt.Print(k, v) // // fmt.Print(", ") // // } // // fmt.Println("=========") // // for k, v := range tempBigCardCount { // // fmt.Print(k, v) // // fmt.Print(", ") // // } // curCardCountForPatternList := int32(len(self.cards) - 3) // for i := 0; i < len(result); i++ { // curTime = time.Now() // tempCardsCount := self.rmCardsAmountInfo.GetAmountInfo() // cloneCardTime += time.Now().Sub(curTime).Seconds() // // fmt.Println("小:", self.smallCardAmount) // // fmt.Println("大:", self.bigCardAmount) // isFailure := false // tempPatternList := make([]*MaJiangPattern, 0) // for j := 0; j < len(result[i]); j++ { // curTime = time.Now() // index := result[i][j] // pattern := patterns[index] // if pattern.ptype == PTPair { // for k := 0; k < len(tempPatternList); k++ { // if tempPatternList[k].ptype == PTPair { // isFailure = true // break // } // } // } // if isFailure { // break // } // for k := 0; k < len(pattern.cards); k++ { // cType, cVal := pattern.cards[k].CurValue() // if tempCardsCount[cType][cVal] <= 0 { // isFailure = true // break // } // tempCardsCount[cType][cVal]-- // } // if isFailure { // break // } // checkTime += time.Now().Sub(curTime).Seconds() // curTime = time.Now() // tempPatternList = append(tempPatternList, pattern) // if GetCardCountByPatternList(tempPatternList) > curCardCountForPatternList { // break // } // appendToContainerTime += time.Now().Sub(curTime).Seconds() // } // if !isFailure { // //fmt.Println("生成的模式组:") // //PrintPatterns(tempPatternList) // curTime = time.Now() // patternGroup := NewPatternGroup(tempPatternList) // tempPatternGroups = append(tempPatternGroups, patternGroup) // appendToContainerTime += time.Now().Sub(curTime).Seconds() // } // // fmt.Println("生成的模式组:") // // PrintPatternGroups(tempPatternGroups) // curTimeS := time.Now() // //fmt.Println("可行的模式:", len(tempPatternGroups)) // // for i := 0; i < len(tempPatternGroups); i++ { // // isExist := false // // curTime = time.Now() // // for j := 0; j < len(patternGroups); j++ { // // if tempPatternGroups[i].IsEqual(patternGroups[j]) { // // isExist = true // // break // // } // // } // // stripSameCompareTime += time.Now().Sub(curTime).Seconds() // // if !isExist { // // patternGroups = append(patternGroups, tempPatternGroups[i]) // // } // // } // stripSameTime += time.Now().Sub(curTimeS).Seconds() // // fmt.Println("剔除重复后的模式组:") // // PrintPatternGroups(patternGroups) // } // patternGroups = tempPatternGroups // //patternGroups = append(patternGroups, tempPatternGroups...) // // fmt.Println("生成后的模式组:", len(tempPatternGroups)) // // PrintPatternGroups(tempPatternGroups, false) // // fmt.Println("生成后的模式组:==============") // //fmt.Println("克隆的时间:", cloneCardTime) // //fmt.Println("检测的时间:", checkTime) // //fmt.Println("追加的时间:", appendToContainerTime) // //fmt.Println("剔除重复的时间:", stripSameTime) // //fmt.Println("剔除重复的比较的时间:", stripSameCompareTime) // return // } // //生成模式的组合下标 // func C(n int, m int) (result [][]int) { // if n > m { // logger.Error("n must be less than m", n, m) // return nil // } // // size := Factorial(m) / (Factorial(m-n) * Factorial(n)) // // fmt.Println("组合数量:", n, m, size) // result = make([][]int, 0) // index := make([]int, m) // //fmt.Println(m, index) // for i := 0; i < m; i++ { // index[i] = 0 // } // for i := 0; i < n; i++ { // index[i] = 1 // } // result = append(result, GetC(index)) // for true { // for i := 0; i < m-1; i++ { // if index[i] == 1 && index[i+1] == 0 { // oneIndex := 0 // for j := 0; j < i; j++ { // if index[j] == 1 { // index[j] = 0 // index[oneIndex] = 1 // oneIndex++ // } // } // index[i] = 0 // index[i+1] = 1 // result = append(result, GetC(index)) // break // } // } // //check is end // isEnd := true // for k := m - n; k < m; k++ { // if index[k] != 1 { // isEnd = false // break // } // } // if isEnd { // break // } // } // return // } // func GetC(index []int) (result []int) { // result = make([]int, 0) // for i := 0; i < len(index); i++ { // if index[i] == 1 { // result = append(result, i) // } // } // return // } // //获取模式列表卡牌的数量 // func GetCardCountByPatternList(patternList []*MaJiangPattern) (result int32) { // for _, p := range patternList { // if p == nil { // continue // } // result += int32(len(p.cards)) // } // return result // } // //获取每个组模式中的单牌 // func (self *HuController) GetSingleCardInPatternGroup(patternGroup []*MaJiangPatternGroup) (result [][]*MaJiangCard) { // result = make([][]*MaJiangCard, 0) // for _, v := range patternGroup { // tempCards := []*MaJiangCard{} // tempCards = append(tempCards, self.cards...) // for i := 0; i < len(v.patterns); i++ { // for j := 0; j < len(v.patterns[i].cards); j++ { // card := v.patterns[i].cards[j] // cType, cVal := card.CurValue() // tempCards = RemoveCardByType(tempCards, cType, cVal) // } // } // result = append(result, tempCards) // } // return // } // //计算每个组模式中胡的牌 // func (self *HuController) CalcHu(singleCards [][]*MaJiangCard, patternGroups []*MaJiangPatternGroup) []*MaJiangPatternGroup { // for i, v := range singleCards { // singleCardCount := len(v) // pairCards := patternGroups[i].GetPairCard() // pairCount := len(pairCards) // if singleCardCount >= 3 || singleCardCount <= 0 { // continue // } // //logger.Info("当前的模式组:") // //PrintPatternGroup(patternGroups[i], false) // //logger.Info("一个模式组中的单牌数%s, 对子数:%s", singleCardCount, pairCount) // //logger.Info("单张牌:") // //PrintCards(v) // //logger.Info("对子:") // //PrintCards(pairCards) // result := []*MaJiangCard{} // if singleCardCount == 1 { // if pairCount == 0 { // curType, curVal := v[0].CurValue() // result = []*MaJiangCard{&MaJiangCard{value: curVal, cType: curType, flag: cmn.CUnknown}} // } // } else if singleCardCount == 2 { // firstCard := v[0] // secondCard := v[1] // firstCType, _ := firstCard.CurValue() // secondCType, secondVal := secondCard.CurValue() // //AA mode // if firstCard.IsEqualByTypeAndValue(secondCType, secondVal) { // if pairCount == 1 { // curType, curVal := pairCards[0].CurValue() // result = []*MaJiangCard{&MaJiangCard{value: firstCard.value, cType: firstCType, flag: cmn.CUnknown}, // &MaJiangCard{value: curVal, cType: curType, flag: cmn.CUnknown}} // } else if pairCount == 0 { // result = []*MaJiangCard{&MaJiangCard{value: firstCard.value, cType: firstCType, flag: cmn.CUnknown}} // } else { // logger.Error("不可能存在此种情况") // } // //SZ // } else if firstCType == secondCType { // offset := int(secondCard.value) - int(firstCard.value) // switch offset { // case 1: // result = []*MaJiangCard{} // if firstCard.value-1 > 0 { // result = append(result, &MaJiangCard{value: firstCard.value - 1, cType: firstCType, flag: cmn.CUnknown}) // } // if secondCard.value+1 < 10 { // result = append(result, &MaJiangCard{value: secondCard.value + 1, cType: secondCType, flag: cmn.CUnknown}) // } // case -1: // result = []*MaJiangCard{} // if secondCard.value-1 > 0 { // result = append(result, &MaJiangCard{value: secondCard.value - 1, cType: secondCType, flag: cmn.CUnknown}) // } // if firstCard.value+1 < 10 { // result = append(result, &MaJiangCard{value: firstCard.value + 1, cType: firstCType, flag: cmn.CUnknown}) // } // case 2, -2: // result = []*MaJiangCard{&MaJiangCard{value: (firstCard.value + secondCard.value) / 2, cType: firstCType, flag: cmn.CUnknown}} // } // } // } // //检查是否有胡 // if result != nil && len(result) > 0 { // logger.Info("特殊情况下的胡牌:") // PrintCards(result) // patternGroups[i].kaoCards = append(patternGroups[i].kaoCards, singleCards[i]...) // patternGroups[i].huCards = append(patternGroups[i].huCards, result...) // } // } // return patternGroups // } // //剔除不能胡的组模式 // func (self *HuController) StripNoHuPatternGroup(groupPatterns []*MaJiangPatternGroup) (result []*MaJiangPatternGroup) { // //剔除不能胡的牌 // for _, v := range groupPatterns { // if v.CanHu() { // result = append(result, v) // } // } // return result // } // //通过胡数和胡的牌产生唯一ID // func (self *HuController) GeneratePatternGroupID(groupPatterns []*MaJiangPatternGroup) { // for _, v := range groupPatterns { // v.GenerateID() // } // } // //剔除相同的模式组 // func (self *HuController) StripSamePatternGroup(groupPatterns []*MaJiangPatternGroup) (result []*MaJiangPatternGroup) { // result = make([]*MaJiangPatternGroup, 0) // //剔除重复的牌 // isExist := false // for _, v := range groupPatterns { // isExist = false // for _, rv := range result { // if v.id == rv.id { // isExist = true // } // } // if !isExist { // result = append(result, v) // } // } // return // } // //复制牌 // func CloneMaJiangCards(src []*MaJiangCard) (dst []*MaJiangCard) { // if src == nil { // return nil // } // dst = make([]*MaJiangCard, len(src)) // for i, v := range src { // dst[i] = CloneMaJiangCard(v) // } // return // } // //复制红中,防止每次都是替代的同一组红中 // func CloneHongZhong(src []*MaJiangCard) (dst []*MaJiangCard, hongCards []*MaJiangCard) { // dst = make([]*MaJiangCard, len(src)) // hongCards = make([]*MaJiangCard, 0) // if src == nil { // return // } // for i, v := range src { // if v.IsHongZhong() { // temp := CloneMaJiangCard(v) // dst[i] = temp // hongCards = append(hongCards, temp) // } else { // dst[i] = v // } // } // return // } // func CloneMaJiangCard(src *MaJiangCard) (dst *MaJiangCard) { // if src == nil { // return nil // } // dst = &MaJiangCard{} // dst.id = src.id // dst.value = src.value // dst.cType = src.cType // dst.rcType = src.rcType // dst.flag = src.flag // dst.owner = src.owner // return dst // } // //获取指定类型的牌 // func GetSpecificTypeCardsByCardsList(cardsList []*MaJiangCard, cType int32, replaceMode bool) (result []*MaJiangCard) { // result = make([]*MaJiangCard, 0) // if cardsList == nil || len(cardsList) <= 0 { // return // } // if !replaceMode { // for _, card := range cardsList { // if card.cType == cType { // result = append(result, card) // } // } // } else { // for _, card := range cardsList { // tempCType, _ := card.CurValue() // if tempCType == cType { // result = append(result, card) // } // } // } // return result // } // type HongZhongReplaceInfo struct { // id int32 // rType int32 // rValue int32 // } // func GetReplaceList(hongZhongAmount int32, canReplaceTypeList []int32) (result [][]*HongZhongReplaceInfo) { // //可以替换的牌的数量 // canReplaceTypeAmount := len(canReplaceTypeList) // canReplaceAmount := hongZhongAmount * int32(canReplaceTypeAmount) * 9 // //生成可以替换的牌的列表 // hongZhongReplaceList := make([]*HongZhongReplaceInfo, canReplaceAmount) // for h := 0; h < int(hongZhongAmount); h++ { // for typeIndex, rType := range canReplaceTypeList { // for i := 0; i < 9; i++ { // hongZhongReplaceList[h*(canReplaceTypeAmount*9)+typeIndex*9+i] = &HongZhongReplaceInfo{id: rType*10 + int32(i+1), rType: rType, rValue: int32(i + 1)} // } // } // } // //对列表进行组合 // result = make([][]*HongZhongReplaceInfo, 0) // cIndexList := C(int(hongZhongAmount), int(canReplaceAmount)) // logger.Info("替换的组合列表:", cIndexList) // for _, indexGroup := range cIndexList { // tempReplaceGroup := make([]*HongZhongReplaceInfo, len(indexGroup)) // for index, tempReplaceIndex := range indexGroup { // tempReplaceGroup[index] = hongZhongReplaceList[tempReplaceIndex] // } // if !ExistSameReplace(result, tempReplaceGroup) { // result = append(result, tempReplaceGroup) // } // } // return // } // func ExistSameReplace(replaceList [][]*HongZhongReplaceInfo, replaceInfo []*HongZhongReplaceInfo) bool { // for _, replaceGroup := range replaceList { // tempReplaceInfo := make([]*HongZhongReplaceInfo, len(replaceInfo)) // copy(tempReplaceInfo, replaceInfo) // for _, replace := range replaceGroup { // tempReplaceInfo = RemoveReplaceCard(tempReplaceInfo, replace.id) // } // isSame := len(tempReplaceInfo) <= 0 // if isSame { // return true // } // } // return false // } // func RemoveReplaceCard(replaceList []*HongZhongReplaceInfo, id int32) []*HongZhongReplaceInfo { // for i, val := range replaceList { // if val.id == id { // return append(replaceList[:i], replaceList[i+1:]...) // } // } // return replaceList // }
/* * Copyright 2021 American Express * * 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 git import ( "os" "testing" ) var FakeRepo = "https://github.com/carnal0wnage/fake_commited_secrets" func TestReposPerProject(t *testing.T) { if os.Getenv("gituser") == "" && os.Getenv("gitpassword") == "" { t.Skip("Skipping ReposPerProject. Authentication needed. Include ENV vars: gituser, gitpassword") } if gotScanRepos := ReposPerProject("https://github.com/americanexpress", os.Getenv("gituser"), os.Getenv("gitpassword")); len(gotScanRepos) == 0 { t.Errorf("ReposPerProject() = %v, want multiple repository names", gotScanRepos) } } func TestCloneGitRepos(t *testing.T) { if os.Getenv("local") == "" { t.Skip("If test cases not running locally, skip cloning external repositories for CI/CD purposes.") } SearchDir, err := CloneGitRepos([]string{FakeRepo}, "", "", "", true) if err != nil { t.Errorf("Failed to clone repository: %s", FakeRepo) } //Delete temporary cloned repository directory err = os.RemoveAll(SearchDir) if err != nil { t.Errorf("Failed to delete git dir: %s", err) } }
package cmd import ( "fmt" "github.com/infobloxopen/atlas-contacts-app/cmd/setting" "github.com/infobloxopen/atlas-contacts-app/db" ) //const ( // // ServerAddress is the default address for the gRPC server, if no override is specified in the flags // ServerAddress = "0.0.0.0:9090" // // GatewayAddress is the default address for the gateway server, if no override is specified in the flags // GatewayAddress = "0.0.0.0:8080" // // InternalAddress is the default address for the internal http server, if no override is specified in the flags // InternalAddress = "0.0.0.0:8081" // // DatabaseAddress is the default address for the database, if no override is specified in the flags // DBConnectionString = "host=localhost port=5432 user=postgres password=postgres sslmode=disable dbname=atlas_contacts_app" // // SwaggerFile is the file location of the swagger file to serve // SwaggerFile = "./pkg/pb/contacts.swagger.json" // // ApplicationID associates a microservice with an application. The atlas // // contacts application consists of only one service, so we identify both the // // service and the application as "atlas-contacts-app" // ApplicationID = "atlas-contacts-app" //) var ( // ServerAddress is the default address for the gRPC server ServerAddress string // GatewayAddress is the default address for the gateway server GatewayAddress string // InternalAddress is the default address for the internal http server InternalAddress string // DatabaseAddress is the default address for the database DbCfg db.DatabaseConfig DBConnectionString string // SwaggerFile is the file location of the swagger file to serve SwaggerFile string // ApplicationID associates a microservice with an application. The atlas // contacts application consists of only one service, so we identify both the // service and the application as "atlas-contacts-app" ApplicationID string // Log Level LogLevel string // Address of the authorization service AuthzAddr string ) func LoadConfig() { LoadAppConfig() LoadServerConfig() LoadDbConfig() if (LogLevel == "debug") { setting.ShowConfigSettings() } } func LoadAppConfig() { ApplicationID = setting.Cfg.Section("").Key("app_id").MustString("atlas-contacts-app") SwaggerFile = setting.Cfg.Section("paths").Key("swagger").MustString("./pkg/pb/contacts.swagger.json") LogLevel = setting.Cfg.Section("log").Key("level").MustString("info") } func LoadServerConfig() { server := setting.Cfg.Section("server") domain := server.Key("domain").MustString("localhost") serverPort := server.Key("server_port").MustString("9090") gatewayPort := server.Key("gateway_port").MustString("8080") internalPort := server.Key("internal_port").MustString("8081") ServerAddress = fmt.Sprintf("%s:%s",domain, serverPort) GatewayAddress = fmt.Sprintf("%s:%s",domain, gatewayPort) InternalAddress = fmt.Sprintf("%s:%s",domain, internalPort) AuthzAddr = server.Key("authz_addr").MustString("") } func LoadDbConfig(){ sec := setting.Cfg.Section("database") DbCfg.Host = sec.Key("host").String() DbCfg.Port = sec.Key("port").String() DbCfg.Name = sec.Key("name").String() DbCfg.User = sec.Key("user").String() DbCfg.Pwd = sec.Key("password").String() DbCfg.MaxOpenConn = sec.Key("max_open_conn").MustInt(0) DbCfg.MaxIdleConn = sec.Key("max_idle_conn").MustInt(0) DbCfg.SslMode = sec.Key("ssl_mode").String() DbCfg.CaCertPath = sec.Key("ca_cert_path").String() DbCfg.ClientKeyPath = sec.Key("client_key_path").String() DbCfg.ClientCertPath = sec.Key("client_cert_path").String() DbCfg.ServerCertName = sec.Key("server_cert_name").String() SetDbConnectionString() } func SetDbConnectionString() { if DbCfg.Pwd == "" { DbCfg.Pwd = "''" } if DbCfg.User == "" { DbCfg.User = "''" } DBConnectionString = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s sslcert=%s sslkey=%s sslrootcert=%s", DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Port, DbCfg.Name, DbCfg.SslMode, DbCfg.ClientCertPath, DbCfg.ClientKeyPath, DbCfg.CaCertPath) }
package dbsearch import ( "runtime" //"log" "reflect" "strconv" "testing" ) func Benchmark_TestSpeed_01(b *testing.B) { runtime.GOMAXPROCS(8) b.StopTimer() //stop the performance timer temporarily while doing initialization s := init_test_data() if s == nil { b.Fatal("Benchmark_TestSpeed_02") } main_speed_test_table(s, b, 40000) b.StartTimer() //restart timer for i := 0; i < b.N; i++ { _select_TestSpeedGet(true, b, s, i*10) } } func Benchmark_TestSpeed_02(b *testing.B) { runtime.GOMAXPROCS(8) b.StopTimer() //stop the performance timer temporarily while doing initialization s := init_test_data() if s == nil { b.Fatal("Benchmark_TestSpeed_02") } main_speed_test_table(s, b, 40000) b.StartTimer() //restart timer for i := 0; i < b.N; i++ { _select_TestSpeedGet(false, b, s, i*10) } } func Benchmark_TestSpeed_Json_03(b *testing.B) { runtime.GOMAXPROCS(8) b.StopTimer() //stop the performance timer temporarily while doing initialization s := init_test_data() if s == nil { b.Fatal("Benchmark_TestSpeed_Json_03") } main_speed_struct_test_table(s, b, 40000) b.StartTimer() //restart timer for i := 0; i < b.N; i++ { _select_TestSpeedJsonGet(false, b, s, i*10) } } func Benchmark_TestSpeed_Json_04(b *testing.B) { runtime.GOMAXPROCS(8) b.StopTimer() //stop the performance timer temporarily while doing initialization s := init_test_data() if s == nil { b.Fatal("Benchmark_TestSpeed_Json_04") } main_speed_struct_test_table(s, b, 40000) b.StartTimer() //restart timer for i := 0; i < b.N; i++ { _select_TestSpeedJsonGet(true, b, s, i*10) } } func main_speed_struct_test_table(s *Searcher, b *testing.B, count int) { sql_create := " CREATE TABLE public.test " + "( col1 serial, col2 json, col3 text, col4 integer[], col5 text[] )" js := `'{"mail":"weq","top":"up","list":[1,2,3,5,"assadasd",1233.87],"bool_1":true,"bool_2":true,"inner":{"mail":"weq","top":"up","list":[1,2,3,5,"assadasd",1233.87],"bool_1":true,"bool_2":true}}'` ar := `'{10,123,123213,-2323,4345,21232131,466856,123123}'` txt := `'{Великобритания,UK,"\"United '' Kingdom","UK,United Kingdom of \"Great , Britain\" ` + `and Northern Ireland","Соединенное Королевство Великобритании и Северной Ирландии","ВНУТРИ КАВЫКИ \",` + `С ЗАПЯТОЙ","\"",1,"1-2: 1\"2\"",NULL,"single slash: \\\" and \\\\\""}'` sql_cols := "INSERT INTO public.test(col2, col3, col4, col5) " int_vals := []string{ " VALUES (" + js + "::json," + js + ", " + ar + "::integer[], " + txt + "::text[])", " VALUES (" + js + "::json," + js + ", " + ar + "::integer[], " + txt + "::text[])", " VALUES (" + js + "::json," + js + ", " + ar + "::integer[], " + txt + "::text[])", } sql_vals := []string{} for count > 0 { count-- sql_vals = append(sql_vals, int_vals...) } s.Do("DROP TABLE IF EXISTS public.test") s.Do(sql_create) for _, v := range sql_vals { s.Do(sql_cols + v) } // Warmimg _select_TestSpeedJsonGet(false, b, s, 100) _select_TestSpeedJsonGet(true, b, s, 100) } func main_speed_test_table(s *Searcher, b *testing.B, count int) { sql_create := " CREATE TABLE public.test " + "(col1 int, col2 bigint, col3 smallint, col4 integer, " + "col5 serial, col6 bigserial, col7 text, col8 varchar(50), col9 char(10), " + " col11 real, col12 double precision, col13 numeric, col14 decimal, col15 money, col16 boolean " + ") " sql_cols := "INSERT INTO test(col1, col2, col3, col4, col5, col6, col7, col8, col9, col11, col12, col13, col14, col15, col16 ) " int_vals := []string{ "VALUES (1, 9223372036854775807, 883, 884, 885, 886, '123456789', '123456789', '1234567890', 12.13, 14.15, 16.17, 18.19, 20.21, TRUE )", "VALUES (2, -9223372036854775807, -883, -884, -885, -886, '-123456789', '-123456789', '-123456789', -12.13, -14.15, -16.17, -18.19, -20.21, FALSE )", "VALUES (3, null, null, null, 0, 0, null, null, null, null, null, null, null, null, null )", // check null - nil } sql_vals := []string{} for count > 0 { count-- sql_vals = append(sql_vals, int_vals...) } s.Do("DROP TABLE IF EXISTS public.test") s.Do(sql_create) for _, v := range sql_vals { s.Do(sql_cols + v) } // Warmimg _select_TestSpeedGet(false, b, s, 100) _select_TestSpeedGet(true, b, s, 100) } /* int32 test */ type speed_01_TestPlace struct { Col1 int32 `db:"col1" type:"int"` Col2 int32 `db:"col2" type:"bigint"` Col3 int32 `db:"col3" type:"smallint"` Col4 int32 `db:"col4" type:"integer"` Col5 int32 `db:"col5" type:"serial"` Col6 int32 `db:"col6" type:"bigserial"` Col7 int32 `db:"col7" type:"text"` Col8 int32 `db:"col8" type:"varchar"` Col9 int32 `db:"col9" type:"char"` Col11 int32 `db:"col11" type:"real"` Col12 int32 `db:"col12" type:"double"` Col13 int32 `db:"col13" type:"numeric"` Col14 int32 `db:"col14" type:"decimal"` Col15 int32 `db:"col15" type:"money"` Col16 int32 `db:"col16" type:"bool"` } var speed_01_mTestType *AllRows = &AllRows{ SType: reflect.TypeOf(speed_01_TestPlace{}), } func _select_TestSpeedGet(is_fork bool, b *testing.B, s *Searcher, N int) { p := []speed_01_TestPlace{} sql := "SELECT * FROM public.test ORDER BY 1 LIMIT " + strconv.Itoa(N) //log.Println(sql) if is_fork { s.GetFork(speed_01_mTestType, &p, sql) } else { s.Get(speed_01_mTestType, &p, sql) } if len(p) != N { b.Fatalf("Bad resault for %d\n", N) } } type speed_01_Json_TestPlace struct { Col1 int `db:"col1" type:"serial"` Col2 map[string]interface{} `db:"col2" type:"json"` Col3 map[string]interface{} `db:"col3" type:"json"` Col4 []int `db:"col4" type:"[]int"` Col5 []string `db:"col5" type:"[]text"` } var speed_01_Json_mTestType *AllRows = &AllRows{ SType: reflect.TypeOf(speed_01_Json_TestPlace{}), } func _select_TestSpeedJsonGet(is_fork bool, b *testing.B, s *Searcher, N int) { p := []speed_01_Json_TestPlace{} sql := "SELECT * FROM public.test ORDER BY 1 LIMIT " + strconv.Itoa(N) //log.Println(sql) if is_fork { s.GetFork(speed_01_Json_mTestType, &p, sql) } else { s.GetNoFork(speed_01_Json_mTestType, &p, sql) } if len(p) != N { b.Fatalf("Bad resault for %d\n", N) } }
package gpi import ( "io/ioutil" "os" "testing" ) func TestGetPageIds(t *testing.T) { file, err := os.Open("gpi_test.html") if err != nil { t.Errorf("%s", err.Error()) return } defer file.Close() b, err := ioutil.ReadAll(file) if err != nil { t.Errorf("%s", err.Error()) return } ids := GetPageIds(b) if len(ids) < 1 { t.Errorf("Got no ids") } if ids[0] != "SPDR006" { t.Errorf("Expceted SPDR006, got %s", ids[0]) } }
package controllers import ( "net/http" "strconv" m "github.com/fullstacktf/Narrativas-Backend/models" "github.com/gin-gonic/gin" ) func Get(c *gin.Context) { var stories m.Stories useridParam, _ := c.Get("user_id") userid := useridParam.(uint) err := stories.Get(userid) if err != nil { c.AbortWithStatus(http.StatusForbidden) return } c.JSON(http.StatusOK, gin.H{"stories": stories}) } func GetStory(c *gin.Context) { var story m.Story userid, _ := c.Get("user_id") story.UserID = userid.(uint) id, err := strconv.ParseUint(c.Params.ByName("id"), 10, 64) if err != nil { c.AbortWithStatus(400) return } err = story.Get(uint(id)) if err != nil { c.AbortWithStatus(http.StatusForbidden) return } c.JSON(http.StatusOK, story) } func DeleteStory(c *gin.Context) { id, err := strconv.ParseUint(c.Params.ByName("id"), 10, 64) var story m.Story userid, _ := c.Get("user_id") story.ID = uint(id) if err = story.Delete(userid.(uint)); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } c.Status(http.StatusOK) } func PostStory(c *gin.Context) { var story m.Story userid, _ := c.Get("user_id") story.UserID = userid.(uint) if err := c.BindJSON(&story); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if err := story.Insert(); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, story) } func PostEvent(c *gin.Context) { var event m.Event id, err := strconv.ParseUint(c.Params.ByName("id"), 10, 64) if err != nil { c.AbortWithStatus(400) return } if err := c.BindJSON(&event); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } event.StoryID = uint(id) if err := event.Insert(); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, event) } func PostEventRelation(c *gin.Context) { var relation m.EventRelation if err := c.BindJSON(&relation); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if err := relation.Insert(); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, relation) }
package main import ( "fmt" "log" "os" "time" "github.com/chedom/go_prog_lang/ch4/github" ) func main() { result, err := github.SearchIssues(os.Args[1:]) var lessThenMonth, lessThenYear, pastThenYear []*github.Issue if err != nil { log.Fatal(err) } now := time.Now() for _, v := range result.Items { switch h := now.Sub(v.CreatedAt).Hours(); { case h < 24*31: lessThenMonth = append(lessThenMonth, v) case h < 24*31: lessThenYear = append(lessThenYear, v) default: pastThenYear = append(pastThenYear, v) } } fmt.Println("Less then month") for _, item := range result.Items { fmt.Printf("#%-5d %9.9s %.55s\n", item.Number, item.User.Login, item.Title) } fmt.Println("Less then year") for _, item := range result.Items { fmt.Printf("#%-5d %9.9s %.55s\n", item.Number, item.User.Login, item.Title) } fmt.Println("Past then year") for _, item := range result.Items { fmt.Printf("#%-5d %9.9s %.55s\n", item.Number, item.User.Login, item.Title) } }
package kubeobjects import ( "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" ) func FindContainerInPod(pod corev1.Pod, name string) (*corev1.Container, error) { container := FindContainerInPodSpec(&pod.Spec, name) if container != nil { return container, nil } podName := GetPodName(pod) return nil, errors.Errorf("no container %s found for pod %s", name, podName) } func FindContainerInPodSpec(podSpec *corev1.PodSpec, containerName string) *corev1.Container { for i := range podSpec.Containers { container := &podSpec.Containers[i] if container.Name == containerName { return container } } return nil }
package connmgr import ( "fmt" "github.com/multivactech/MultiVAC/model/chaincfg" "github.com/multivactech/MultiVAC/model/wire" "net" "strings" "testing" "time" ) func TestSeedFromDNS(t *testing.T) { params := chaincfg.Params{ Name: "Davis", Net: 0, DefaultPort: "2333", DNSSeeds: []chaincfg.DNSSeed{ { Host: "127.0.0.1", HasFiltering: false, }, { Host: "210.31.32.128", HasFiltering: false, }, { Host: "192.168.1.12", HasFiltering: false, }, { Host: "230.230.230.230", HasFiltering: true, }, }, PowLimit: nil, PowLimitBits: 0, BIP0034Height: 0, BIP0065Height: 0, BIP0066Height: 0, CoinbaseMaturity: 0, SubsidyReductionInterval: 0, TargetTimespan: 0, TargetTimePerBlock: 0, RetargetAdjustmentFactor: 0, ReduceMinDifficulty: false, MinDiffReductionTime: 0, GenerateSupported: false, Checkpoints: nil, RuleChangeActivationThreshold: 0, MinerConfirmationWindow: 0, Deployments: [3]chaincfg.ConsensusDeployment{}, RelayNonStdTxs: false, Bech32HRPSegwit: "", PubKeyHashAddrID: 0, ScriptHashAddrID: 0, PrivateKeyID: 0, WitnessPubKeyHashAddrID: 0, WitnessScriptHashAddrID: 0, HDPrivateKeyID: [4]byte{}, HDPublicKeyID: [4]byte{}, HDCoinType: 0, } SeedFromDNS(&params, 0, lookupfun, seedfn) time.Sleep(4 * time.Second) } func seedfn(addrs []*wire.NetAddress) { for _, val := range addrs { fmt.Println(string(val.IP)) } } func lookupfun(s string) ([]net.IP, error) { if s == "127.0.0.1" { return []net.IP{ { 127, 0, 0, 1, }, { 127, 0, 0, 2, }, }, nil } if strings.Contains(s, "x") { return nil, fmt.Errorf("error from test,host:%v", s) } return []net.IP{}, nil }
package main import "fmt" //截取操作有带 2 个或者 3 个参数,形如:[i:j] 和 [i:j:k],假设截取对象的底层数组⻓度为 l。在操作符 [i:j] 中,如果 i 省略,默认 0,如果 j 省略,默认底层数组的⻓度,截取得到的切片⻓度和容量计算方法是 j- i、l-i。操作符 [i:j:k],k 主要是用来限制切片的容量,但是不能大于数组的⻓度 l,截取得到的切片⻓度 和容量计算方法是 j-i、k-i。 func main() { s := [3]int{1, 2, 3} a := s[:0] b := s[:2] c := s[1:2:cap(s)] fmt.Println(len(a), cap(a)) //03 fmt.Println(len(b), cap(b)) //23 fmt.Println(len(c), cap(c)) //12 }
package stack // // minOperations // func minOperations(logs []string) int { s := NewStack() for _, x := range logs { switch x { case "./": continue case "../": s.Pop() default: s.Push("../") } } return s.Count() } // // Count Stack // func NewStack() *stack { return &stack{} } type stack struct { count int } func (s *stack) Push(x string) { s.count++ } func (s *stack) Pop() { if s.count > 0 { s.count-- } } func (s *stack) Count() int { return s.count }
package session import ( "fmt" "github.com/trist725/mgsu/event" "github.com/trist725/myleaf/gate" "github.com/trist725/myleaf/log" "github.com/trist725/myleaf/timer" "mlgs/src/model" "sync/atomic" "time" ) //todo:心跳处理 type Session struct { id uint64 //事件管理器 eventHandlerMgr *event.HandlerManager //定时写库 timer *timer.Timer sign string // 日志标识 agent gate.Agent closeFlag int32 user *model.User // 需要保存到数据库的用户数据 account *model.Account // 帐号数据 //cache *cache.User // 不需要保存到数据库的临时数据 } var gSessionId uint64 func NewSession(agent gate.Agent, account *model.Account, user *model.User) *Session { session := &Session{ agent: agent, account: account, user: user, id: atomic.AddUint64(&gSessionId, 1), eventHandlerMgr: event.NewHandlerManager(), sign: fmt.Sprintf("user-%d-%s", user.ID, user.NickName), } //用于从agent获取到session session.agent.SetUserData(session.id) if gSessionManager == nil { panic("new session failed, because gSessionManager is nil") } gSessionManager.putSession(session) return session } func (s *Session) RegisterEventHandler(id event.ID, handler event.Handler) { s.eventHandlerMgr.Register(id, handler) } func (s *Session) ProcessEvent(ev event.IEvent) error { return s.eventHandlerMgr.Process(ev) } func (s *Session) ID() uint64 { return s.id } func (s *Session) AccountData() *model.Account { return s.account } func (s *Session) UserData() *model.User { return s.user } func (s *Session) SetAccountData(account *model.Account) { s.account = account } func (s *Session) SetUserData(user *model.User) { s.user = user } //func (s *Session) SetLeafAgent(a *gate.Agent) { // s.agent = a //} // //func (s *Session) LeafAgent() *gate.Agent{ // return s.agent //} func (s *Session) SaveData() { if s.user != nil { // 保存用户数据 log.Debug("[%s] save data on [%v]", s.sign, time.Now()) dbSession := model.GetSession() if err := s.user.UpdateByID(dbSession); err != nil { log.Error("[%s], save data error:[%s]", s.sign, err) } model.PutSession(dbSession) } } func (session *Session) IsClosed() bool { return atomic.LoadInt32(&session.closeFlag) == 1 } //todo:断线重连,deepcopy保存快照 func (s *Session) Close() error { if atomic.CompareAndSwapInt32(&s.closeFlag, 0, 1) { if gSessionManager == nil { panic("close session failed because gSessionManager is nil") } s.agent.Close() //更新最后登出时间 if s.user != nil { s.user.LastLogoutTime = time.Now().Unix() } s.SaveData() if s.timer != nil { s.timer.Stop() } gSessionManager.delSession(s) } return nil } func (s *Session) Sign() string { return s.sign } func (s *Session) SetSign(sign string) { s.sign = sign } func (s *Session) SetTimer(t *timer.Timer) { s.timer = t } func GetSession(sid uint64) *Session { mgr := SessionMgr() if mgr == nil { log.Fatal("gSessionManager is nil, get session id:[%d]", sid) return nil } session := mgr.getSession(sid) if session == nil { log.Debug("get session id:[%d] not exist", sid) return nil } return session }
package course_data_api import ( "encoding/json" "fmt" "github.com/andrewmthomas87/northwestern/models" "io/ioutil" "net/http" "strings" ) var badResponseError = fmt.Errorf("request returned an error") type Client struct { baseUrl string apiKey string apiKeyParameter string httpClient *http.Client } func NewClient(baseUrl, apiKey, apiKeyParameter string) *Client { return &Client{ baseUrl: baseUrl, apiKey: apiKey, apiKeyParameter: apiKeyParameter, httpClient: &http.Client{}, } } func (c *Client) newRequest(endpoint string, parameters []string) (*http.Request, error) { parameters = append(parameters, fmt.Sprintf("%s=%s", c.apiKeyParameter, c.apiKey)) url := fmt.Sprintf("%s%s?%s", c.baseUrl, endpoint, strings.Join(parameters, "&")) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } fmt.Printf("Created request: %s\n", url) return req, nil } func (c *Client) doRequest(req *http.Request) ([]byte, error) { resp, err := c.httpClient.Do(req) if err != nil { return nil, err } else if resp.StatusCode != http.StatusOK { return nil, badResponseError } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil } type apiTerm struct { Id int `json:"id"` Name string `json:"name"` StartDate string `json:"start_date"` EndDate string `json:"end_date"` } func (c *Client) Terms() ([]*models.Term, error) { req, err := c.newRequest("terms", nil) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiTerms []apiTerm if err := json.Unmarshal(body, &apiTerms); err != nil { return nil, err } terms := make([]*models.Term, len(apiTerms)) for i, apiTerm := range apiTerms { terms[i] = &models.Term{ Id: apiTerm.Id, Name: apiTerm.Name, StartDate: apiTerm.StartDate, EndDate: apiTerm.EndDate, } } return terms, nil } type apiSchool struct { Symbol string `json:"symbol"` Name string `json:"name"` } func (c *Client) Schools() ([]*models.School, error) { req, err := c.newRequest("schools", nil) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiSchools []apiSchool if err := json.Unmarshal(body, &apiSchools); err != nil { return nil, err } schools := make([]*models.School, len(apiSchools)) for i, apiSchool := range apiSchools { schools[i] = &models.School{ Symbol: apiSchool.Symbol, Name: apiSchool.Name, } } return schools, nil } type apiSubject struct { Symbol string `json:"symbol"` Name string `json:"name"` } func (c *Client) Subjects(term int, school string) ([]*models.Subject, error) { var parameters []string if term != -1 { parameters = append(parameters, fmt.Sprintf("term=%d", term)) } if len(school) > 0 { parameters = append(parameters, fmt.Sprintf("school=%s", school)) } req, err := c.newRequest("subjects", parameters) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiSubjects []apiSubject if err := json.Unmarshal(body, &apiSubjects); err != nil { return nil, err } subjects := make([]*models.Subject, len(apiSubjects)) for i, apiSubject := range apiSubjects { subjects[i] = &models.Subject{ Symbol: apiSubject.Symbol, Name: apiSubject.Name, } } return subjects, nil } type apiInstructor struct { Id int `json:"id"` Name string `json:"name"` Phone string `json:"phone"` } func (c *Client) Instructors(subject string) ([]*models.Instructor, error) { parameters := []string{fmt.Sprintf("subject=%s", subject)} req, err := c.newRequest("instructors", parameters) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiInstructors []apiInstructor if err := json.Unmarshal(body, &apiInstructors); err != nil { return nil, err } instructors := make([]*models.Instructor, len(apiInstructors)) for i, apiInstructor := range apiInstructors { instructors[i] = &models.Instructor{ Id: apiInstructor.Id, Name: apiInstructor.Name, Phone: apiInstructor.Phone, } } return instructors, nil } type apiBuilding struct { Id int `json:"id"` Name string `json:"name"` Lat float64 `json:"lat"` Lon float64 `json:"lon"` } func (c *Client) Buildings() ([]*models.Building, error) { req, err := c.newRequest("buildings", nil) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiBuildings []apiBuilding if err := json.Unmarshal(body, &apiBuildings); err != nil { return nil, err } buildings := make([]*models.Building, len(apiBuildings)) for i, apiBuilding := range apiBuildings { buildings[i] = &models.Building{ Id: apiBuilding.Id, Name: apiBuilding.Name, Lat: apiBuilding.Lat, Lon: apiBuilding.Lon, } } return buildings, nil } type apiRoom struct { Id int `json:"id"` BuildingId int `json:"building_id"` Name string `json:"name"` } func (c *Client) Rooms(building int) ([]*models.Room, error) { parameters := []string{fmt.Sprintf("building=%d", building)} req, err := c.newRequest("rooms", parameters) if err != nil { return nil, err } body, err := c.doRequest(req) if err != nil { return nil, err } var apiRooms []apiRoom if err := json.Unmarshal(body, &apiRooms); err != nil { return nil, err } rooms := make([]*models.Room, len(apiRooms)) for i, apiRoom := range apiRooms { rooms[i] = &models.Room{ Id: apiRoom.Id, BuildingId: apiRoom.BuildingId, Name: apiRoom.Name, } } return rooms, nil } type apiCourse struct { Id int `json:"id"` Title string `json:"title"` Term string `json:"term"` School string `json:"school"` Instructor struct { Name string `json:"name"` Bio string `json:"bio"` Address string `json:"address"` Phone string `json:"phone"` OfficeHours string `json:"office_hours"` } `json:"instructor"` Subject string `json:"subject"` CatalogNum string `json:"catalog_num"` Section string `json:"section"` Room struct { Id int `json:"id"` BuildingId int `json:"building_id"` BuildingName string `json:"building_name"` Name string `json:"name"` } `json:"room"` MeetingDays string `json:"meeting_days"` StartTime string `json:"start_time"` EndTime string `json:"end_time"` StartDate string `json:"start_date"` EndDate string `json:"end_date"` Seats int `json:"seats"` Overview string `json:"overview"` Topic string `json:"topic"` Attributes string `json:"attributes"` Requirements string `json:"requirements"` Component string `json:"component"` ClassNum int `json:"class_num"` CourseId int `json:"course_id"` CourseDescriptions []struct { Name string `json:"name"` Desc string `json:"desc"` } `json:"course_descriptions"` CourseComponents []struct { Component string `json:"component"` MeetingDays string `json:"meeting_days"` StartTime string `json:"start_time"` EndTime string `json:"end_time"` Section string `json:"section"` Room string `json:"room"` } `json:"course_components"` } func (c *Client) Courses(term int, subject string, instructors map[string]int) ([]*models.Course, []*models.CourseDescription, []*models.CourseComponent, error) { parameters := []string{ fmt.Sprintf("term=%d", term), fmt.Sprintf("subject=%s", subject), } req, err := c.newRequest("courses/details", parameters) if err != nil { return nil, nil, nil, err } body, err := c.doRequest(req) if err != nil { return nil, nil, nil, err } var apiCourses []apiCourse if err := json.Unmarshal(body, &apiCourses); err != nil { return nil, nil, nil, err } courses := make([]*models.Course, len(apiCourses)) courseDescriptions := make([]*models.CourseDescription, 0) courseComponents := make([]*models.CourseComponent, 0) for i, apiCourse := range apiCourses { courses[i] = &models.Course{ Id: apiCourse.Id, Title: apiCourse.Title, Term: term, School: apiCourse.School, Instructor: instructors[apiCourse.Instructor.Name], Subject: apiCourse.Subject, CatalogNum: apiCourse.CatalogNum, Section: apiCourse.Section, Room: apiCourse.Room.Id, MeetingDays: apiCourse.MeetingDays, StartTime: apiCourse.StartTime, EndTime: apiCourse.EndTime, StartDate: apiCourse.StartDate, EndDate: apiCourse.EndDate, Seats: apiCourse.Seats, Overview: apiCourse.Overview, Topic: apiCourse.Topic, Attributes: apiCourse.Attributes, Requirements: apiCourse.Requirements, Component: apiCourse.Component, ClassNum: apiCourse.ClassNum, CourseId: apiCourse.CourseId, } for _, apiCourseDescription := range apiCourse.CourseDescriptions { courseDescriptions = append(courseDescriptions, &models.CourseDescription{ Course: apiCourse.Id, Name: apiCourseDescription.Name, Desc: apiCourseDescription.Desc, }) } for _, apiCourseComponent := range apiCourse.CourseComponents { courseComponents = append(courseComponents, &models.CourseComponent{ Course: apiCourse.Id, Component: apiCourseComponent.Component, MeetingDays: apiCourseComponent.MeetingDays, StartTime: apiCourseComponent.StartTime, EndTime: apiCourseComponent.EndTime, Section: apiCourseComponent.Section, Room: apiCourseComponent.Room, }) } } return courses, courseDescriptions, courseComponents, nil }
package models import ( "time" ) type CelebrationModel struct { ID uint `gorm:"primaryKey" json:"id"` WorkArea string `json:"work_area"` ChamberTerritoryID string `json:"chamber_territory_id"` DrChildID string `json:"dr_child_id"` DoctorName string `json:"doctor_name"` ChamberAddress string `gorm:"default:NULL" json:"chamber_address"` CellPhone string `gorm:"default:NULL" json:"cell_phone"` Email string `gorm:"default:NULL" json:"email"` DateOfBirth string `json:"date_of_birth"` RequestWorkArea string `json:"request_work_area"` CelebrationType int `gorm:"default:NULL" json:"celebration_type"` // 1=Birthday; 2=Marragrday CelebrationStatus int `json:"celebration_status"` // Celebration=1; 0=Not Celebration; CelebrationCancelText string `gorm:"default:NULL" json:"celebration_cancel_text"` PermissionStatus int `gorm:"default:NULL" json:"permission_status"` // 1=ASK; 2=Permitted; 3=Cancle; PermissionRequestDateTime time.Time `gorm:"default:NULL" json:"permission_request_date_time"` PermissionResponseDateTime time.Time `gorm:"default:NULL" json:"permission_response_date_time"` PermissionResponseType uint `gorm:"default:NULL" json:"permission_response_type"` // 0=Do Not Celebration; 1=Gift; 2=SMS; 3=EMAIL; PermissionResponseTypeText string `gorm:"default:NULL" json:"permission_response_type_text"` // GIFT,SMS,EMAIL PermissionResponseTypeEmail uint `gorm:"default:0" json:"permission_response_type_email"` // EMAIL; 0 not 1 yes PermissionResponseTypeSms uint `gorm:"default:0" json:"permission_response_type_sms"` // SMS; 0 not 1 yes PermissionResponseTypeGift uint `gorm:"default:0" json:"permission_response_type_gift"` // All type of gift; 0 not 1 yes PermissionResponseText string `gorm:"default:NULL" json:"permission_response_text"` ResponseDateTime time.Time `gorm:"default:NULL" json:"response_date_time"` ResponseType int `gorm:"default:0" json:"response_type"` // 0=Not Complete; 1=Complete TextMessageID int64 `gorm:"default:NULL" json:"text_message_id"` Picture string `gorm:"default:NULL" json:"picture"` Feedback string `gorm:"default:NULL" json:"feedback"` Status int `gorm:"default:1"` CreatedAt time.Time `gorm:"type:DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP"` UpdatedAt time.Time `gorm:"type:DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"` TextMessage string `sql:"-" json:"text_message"` UserName string `sql:"-" json:"user_name"` ResponseTypeInput string `sql:"-" json:"response_type_input"` CelebrateStatusText string `sql:"-" json:"celebrate_status_text"` CelebrateStatus string `sql:"-" json:"celebrate_status"` } func (b *CelebrationModel) TableName() string { return "celebrations" }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package metrics import ( "strconv" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) const ( provisionerNamespace = "provisioner" provisionerSubsystemAPI = "api" provisionerSubsystemApp = "app" ) // CloudMetrics holds all of the metrics needed to properly instrument // the Provisioning server type CloudMetrics struct { // API APIRequestsCounter prometheus.Counter APITimesHistograms *prometheus.HistogramVec // Installation InstallationCreationDurationHist *prometheus.HistogramVec InstallationUpdateDurationHist *prometheus.HistogramVec InstallationHibernationDurationHist *prometheus.HistogramVec InstallationWakeUpDurationHist *prometheus.HistogramVec InstallationDeletionDurationHist *prometheus.HistogramVec // ClusterInstallation ClusterInstallationReconcilingDurationHist *prometheus.HistogramVec ClusterInstallationDeletionDurationHist *prometheus.HistogramVec // Cluster ClusterCreationDurationHist *prometheus.HistogramVec ClusterUpgradeDurationHist *prometheus.HistogramVec ClusterProvisioningDurationHist *prometheus.HistogramVec ClusterResizeDurationHist *prometheus.HistogramVec ClusterDeletionDurationHist *prometheus.HistogramVec } // New creates a new Prometheus-based Metrics object to be used // throughout the Provisioner in order to record various performance // metrics func New() *CloudMetrics { return &CloudMetrics{ APIRequestsCounter: promauto.NewCounter(prometheus.CounterOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemAPI, Name: "requests_total", Help: "The total number of http API requests", }), APITimesHistograms: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemAPI, Name: "requests_duration", Help: "The duration of http API requests", }, []string{"handler", "method", "status_code"}, ), InstallationCreationDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "installation_creation_duration_seconds", Help: "The duration of installation creation tasks", Buckets: standardDurationBuckets(), }, []string{"group"}, ), InstallationUpdateDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "installation_update_duration_seconds", Help: "The duration of installation update tasks", Buckets: standardDurationBuckets(), }, []string{"group"}, ), InstallationHibernationDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "installation_hibernation_duration_seconds", Help: "The duration of installation hibernation tasks", Buckets: standardDurationBuckets(), }, []string{"group"}, ), InstallationWakeUpDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "installation_wakeup_duration_seconds", Help: "The duration of installation wake up tasks", Buckets: standardDurationBuckets(), }, []string{"group"}, ), InstallationDeletionDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "installation_deletion_duration_seconds", Help: "The duration of installation deletion tasks", Buckets: standardDurationBuckets(), }, []string{"group"}, ), ClusterInstallationReconcilingDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_installation_reconciling_duration_seconds", Help: "The duration of cluster installation reconciliation tasks", Buckets: standardDurationBuckets(), }, []string{"cluster"}, ), ClusterInstallationDeletionDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_installation_deletion_duration_seconds", Help: "The duration of cluster installation deletion tasks", Buckets: standardDurationBuckets(), }, []string{"cluster"}, ), ClusterCreationDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_creation_duration_seconds", Help: "The duration of cluster creation tasks", Buckets: standardDurationBuckets(), }, []string{}, ), ClusterUpgradeDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_upgrade_duration_seconds", Help: "The duration of cluster upgrade tasks", Buckets: standardDurationBuckets(), }, []string{}, ), ClusterProvisioningDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_provisioning_duration_seconds", Help: "The duration of cluster provisioning tasks", Buckets: standardDurationBuckets(), }, []string{}, ), ClusterResizeDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_resize_duration_seconds", Help: "The duration of cluster resize tasks", Buckets: standardDurationBuckets(), }, []string{}, ), ClusterDeletionDurationHist: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: provisionerNamespace, Subsystem: provisionerSubsystemApp, Name: "cluster_deletion_duration_seconds", Help: "The duration of cluster deletion tasks", Buckets: standardDurationBuckets(), }, []string{}, ), } } // IncrementAPIRequest increases APIRequestsCounter by one. func (cm *CloudMetrics) IncrementAPIRequest() { cm.APIRequestsCounter.Inc() } // ObserveAPIEndpointDuration observes the duration of an API request. func (cm *CloudMetrics) ObserveAPIEndpointDuration(handler, method string, statusCode int, elapsed float64) { cm.APITimesHistograms.With(prometheus.Labels{"handler": handler, "method": method, "status_code": strconv.Itoa(statusCode)}).Observe(elapsed) } // 15 second buckets up to 5 minutes. func standardDurationBuckets() []float64 { return prometheus.LinearBuckets(0, 15, 20) }
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package gossip import ( "bytes" "sort" "github.com/cockroachdb/cockroach/pkg/config" "github.com/cockroachdb/cockroach/pkg/roachpb" ) // SystemConfigDeltaFilter keeps track of SystemConfig values so that unmodified // values can be filtered out from a SystemConfig update. This can prevent // repeatedly unmarshaling and processing the same SystemConfig values. // // A SystemConfigDeltaFilter is not safe for concurrent use by multiple // goroutines. type SystemConfigDeltaFilter struct { keyPrefix roachpb.Key lastCfg config.SystemConfigEntries } // MakeSystemConfigDeltaFilter creates a new SystemConfigDeltaFilter. The filter // will ignore all key-values without the specified key prefix, if one is // provided. func MakeSystemConfigDeltaFilter(keyPrefix roachpb.Key) SystemConfigDeltaFilter { return SystemConfigDeltaFilter{ keyPrefix: keyPrefix, } } // ForModified calls the provided function for all SystemConfig kvs that were modified // since the last call to this method. func (df *SystemConfigDeltaFilter) ForModified( newCfg *config.SystemConfig, fn func(kv roachpb.KeyValue), ) { // Save newCfg in the filter. lastCfg := df.lastCfg df.lastCfg.Values = newCfg.Values // SystemConfig values are always sorted by key, so scan over new and old // configs in order to find new keys and modified values. Before doing so, // skip all keys in each list of values that are less than the keyPrefix. lastIdx, newIdx := 0, 0 if df.keyPrefix != nil { lastIdx = sort.Search(len(lastCfg.Values), func(i int) bool { return bytes.Compare(lastCfg.Values[i].Key, df.keyPrefix) >= 0 }) newIdx = sort.Search(len(newCfg.Values), func(i int) bool { return bytes.Compare(newCfg.Values[i].Key, df.keyPrefix) >= 0 }) } for { if newIdx == len(newCfg.Values) { // All out of new keys. break } newKV := newCfg.Values[newIdx] if df.keyPrefix != nil && !bytes.HasPrefix(newKV.Key, df.keyPrefix) { // All out of new keys matching prefix. break } if lastIdx < len(lastCfg.Values) { oldKV := lastCfg.Values[lastIdx] switch oldKV.Key.Compare(newKV.Key) { case -1: // Deleted key. lastIdx++ case 0: if !newKV.Value.EqualTagAndData(oldKV.Value) { // Modified value. fn(newKV) } lastIdx++ newIdx++ case 1: // New key. fn(newKV) newIdx++ } } else { // New key. fn(newKV) newIdx++ } } }
package main import ( "fmt" "net/http" "time" ) // Display a greeting and the current date/time to a user. func greeting(w http.ResponseWriter, r *http.Request) { dt := time.Now() fmt.Fprintf(w, "Hello! Welcome to my containerized web server in Golang!\nToday's date and time is: %s", dt.Format("02-01-2006 15:04:05 Monday")) } // Define routes and start server on port 8080 func main() { fmt.Println("Server started") http.HandleFunc("/", greeting) http.ListenAndServe(":8080", nil) }
package main import ( "net/http" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func createServer() *echo.Echo { e := echo.New() e.Use(middleware.CORS()) e.GET("/note", func(c echo.Context) error { return c.NoContent(http.StatusOK) }) e.POST("/note/:user", func(c echo.Context) error { user := c.Param("user") body := new(note) if err := c.Bind(body); err != nil { return err } note, err := createNote(user, *body) if err != nil { c.Error(err) } return c.JSON(http.StatusCreated, note) }) e.GET("/note/:user", func(c echo.Context) error { user := c.Param("user") id := c.QueryParam("from") notes, err := getNotes(user, id) if err != nil { c.Error(err) } return c.JSON(http.StatusOK, notes) }) e.PUT("/note/:user/:id", func(c echo.Context) error { user := c.Param("user") id := c.Param("id") body := &note{} if err := c.Bind(body); err != nil { return err } note, err := updateNote(user, id, *body) if err != nil { c.Error(err) } return c.JSON(http.StatusCreated, note) }) e.DELETE("/note/:user/:id", func(c echo.Context) error { user := c.Param("user") id := c.Param("id") if err := deleteNote(user, id); err != nil { c.Error(err) } return c.NoContent(http.StatusAccepted) }) return e }
package plugin import ( "fmt" "net" log "github.com/golang/glog" osclient "github.com/openshift/origin/pkg/client" osconfigapi "github.com/openshift/origin/pkg/cmd/server/api" "github.com/openshift/origin/pkg/util/netutils" kclient "k8s.io/kubernetes/pkg/client/unversioned" kerrors "k8s.io/kubernetes/pkg/util/errors" ) type OsdnMaster struct { registry *Registry subnetAllocator *netutils.SubnetAllocator vnids *vnidMap netIDManager *netutils.NetIDAllocator adminNamespaces []string } func StartMaster(networkConfig osconfigapi.MasterNetworkConfig, osClient *osclient.Client, kClient *kclient.Client) error { if !IsOpenShiftNetworkPlugin(networkConfig.NetworkPluginName) { return nil } log.Infof("Initializing SDN master of type %q", networkConfig.NetworkPluginName) master := &OsdnMaster{ registry: newRegistry(osClient, kClient), vnids: newVnidMap(), adminNamespaces: make([]string, 0), } // Validate command-line/config parameters ni, err := validateClusterNetwork(networkConfig.ClusterNetworkCIDR, networkConfig.HostSubnetLength, networkConfig.ServiceNetworkCIDR, networkConfig.NetworkPluginName) if err != nil { return err } changed, net_err := master.isClusterNetworkChanged(ni) if changed { if err = master.validateNetworkConfig(ni); err != nil { return err } if err = master.registry.UpdateClusterNetwork(ni); err != nil { return err } } else if net_err != nil { if err = master.registry.CreateClusterNetwork(ni); err != nil { return err } } if err = master.SubnetStartMaster(ni.ClusterNetwork, networkConfig.HostSubnetLength); err != nil { return err } if IsOpenShiftMultitenantNetworkPlugin(networkConfig.NetworkPluginName) { if err = master.VnidStartMaster(); err != nil { return err } } return nil } func (master *OsdnMaster) validateNetworkConfig(ni *NetworkInfo) error { hostIPNets, err := netutils.GetHostIPNetworks([]string{TUN, LBR}) if err != nil { return err } errList := []error{} // Ensure cluster and service network don't overlap with host networks for _, ipNet := range hostIPNets { if ipNet.Contains(ni.ClusterNetwork.IP) { errList = append(errList, fmt.Errorf("Error: Cluster IP: %s conflicts with host network: %s", ni.ClusterNetwork.IP.String(), ipNet.String())) } if ni.ClusterNetwork.Contains(ipNet.IP) { errList = append(errList, fmt.Errorf("Error: Host network with IP: %s conflicts with cluster network: %s", ipNet.IP.String(), ni.ClusterNetwork.String())) } if ipNet.Contains(ni.ServiceNetwork.IP) { errList = append(errList, fmt.Errorf("Error: Service IP: %s conflicts with host network: %s", ni.ServiceNetwork.String(), ipNet.String())) } if ni.ServiceNetwork.Contains(ipNet.IP) { errList = append(errList, fmt.Errorf("Error: Host network with IP: %s conflicts with service network: %s", ipNet.IP.String(), ni.ServiceNetwork.String())) } } // Ensure each host subnet is within the cluster network subnets, err := master.registry.GetSubnets() if err != nil { return fmt.Errorf("Error in initializing/fetching subnets: %v", err) } for _, sub := range subnets { subnetIP, _, _ := net.ParseCIDR(sub.Subnet) if subnetIP == nil { errList = append(errList, fmt.Errorf("Failed to parse network address: %s", sub.Subnet)) continue } if !ni.ClusterNetwork.Contains(subnetIP) { errList = append(errList, fmt.Errorf("Error: Existing node subnet: %s is not part of cluster network: %s", sub.Subnet, ni.ClusterNetwork.String())) } } // Ensure each service is within the services network services, err := master.registry.GetServices() if err != nil { return err } for _, svc := range services { if !ni.ServiceNetwork.Contains(net.ParseIP(svc.Spec.ClusterIP)) { errList = append(errList, fmt.Errorf("Error: Existing service with IP: %s is not part of service network: %s", svc.Spec.ClusterIP, ni.ServiceNetwork.String())) } } return kerrors.NewAggregate(errList) } func (master *OsdnMaster) isClusterNetworkChanged(curNetwork *NetworkInfo) (bool, error) { oldNetwork, err := master.registry.GetNetworkInfo() if err != nil { return false, err } if curNetwork.ClusterNetwork.String() != oldNetwork.ClusterNetwork.String() || curNetwork.HostSubnetLength != oldNetwork.HostSubnetLength || curNetwork.ServiceNetwork.String() != oldNetwork.ServiceNetwork.String() { return true, nil } return false, nil }
/* * Paged * * Handles CRUD operations for events * * API version: 0.0.1 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package main import ( "fmt" "log" "github.com/tuuturu/pager-event-service/pkg/core/router" "github.com/tuuturu/pager-event-service/pkg/core" ) func main() { log.Printf("Server started") cfg := core.LoadConfig() err := cfg.Validate() if err != nil { log.Fatal(err) } r := router.New(cfg) log.Fatal(r.Run(fmt.Sprintf(":%s", cfg.Port))) }
package services import ( "errors" "github/Hiinnn/practice-go/config" "github/Hiinnn/practice-go/models" "time" "unicode" "github.com/dgrijalva/jwt-go" "golang.org/x/crypto/bcrypt" ) var secretKey []byte /* -------------------------------------------------------------------------- */ /* Public Function */ /* -------------------------------------------------------------------------- */ // Register -> Create new user func Register(user *models.User) error { // validate username & password isMatch := validateUsername(user.Username) if !isMatch { return errors.New("invalid username") } isMatch = validatePassword(user.Password) if !isMatch { return errors.New("invalid password") } // hash password hashedPW, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) if err != nil { return err } user.Password = string(hashedPW) // insert user & check username exist if result := config.DB.FirstOrCreate(user); result.RowsAffected == 0 { return errors.New("username exists") } return nil } // Signin -> Check valid username & password, Create JWT token func Signin(user *models.User) (string, error) { var queryUser models.User config.DB.Find(&queryUser, "username = ?", user.Username) compareErr := bcrypt.CompareHashAndPassword([]byte(queryUser.Password), []byte(user.Password)) if queryUser.Username == user.Username && compareErr == nil { token, err := createJWTToken(user.Username) return token, err } return "", errors.New("Invalid Username or Password") } // GetUSerData -> Check token is valid func GetUSerData(tokenString string) (interface{}, error) { var user models.User claims, err := parseJWTToken(tokenString) if err != nil { return "", err } result := config.DB.Find(&user, "username = ?", claims.(jwt.MapClaims)["aud"]) if result.Error != nil { return "", result.Error } return user, nil } // SetSecretKey -> Set secret key from file func SetSecretKey(key []byte) { secretKey = key } /* -------------------------------------------------------------------------- */ /* Private Function */ /* -------------------------------------------------------------------------- */ func createJWTToken(username string) (string, error) { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["iss"] = "hiinnn" //isseur claims["aud"] = username //audience claims["exp"] = time.Now().Add(time.Hour * 72).Unix() // expiration time t, err := token.SignedString(secretKey) if err != nil { return "", err } return t, nil } func parseJWTToken(token string) (interface{}, error) { t, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { return secretKey, nil }) if err != nil { return "", err } return t.Claims, err } func validatePassword(password string) bool { var ( upp, low, num, sym bool tot uint8 ) for _, char := range password { switch { case unicode.IsUpper(char): upp = true tot++ case unicode.IsLower(char): low = true tot++ case unicode.IsNumber(char): num = true tot++ case unicode.IsPunct(char) || unicode.IsSymbol(char): sym = true tot++ default: return false } } if !upp || !low || !num || !sym || tot < 8 { return false } return true } func validateUsername(username string) bool { for _, char := range username { if unicode.IsPunct(char) || unicode.IsSymbol(char) { return false } } return true }
// Copyright (c) 2020 StackRox 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 ioutils import "io" // CopyNFull does the same as io.CopyN, but it returns io.ErrUnexpectedEOF // if CopyN returns io.EOF and the number of bytes written greater than zero. func CopyNFull(dst io.Writer, src io.Reader, n int64) (int64, error) { written, err := io.CopyN(dst, src, n) if err == io.EOF && written != 0 { err = io.ErrUnexpectedEOF } return written, err }
package stringify import "encoding/hex" func SliceOfBytes(value []byte) string { switch { case value == nil: return "<nil>" case len(value) == 0: return "<empty>" default: return "0x" + hex.EncodeToString(value) + "" } }
package scheduler import ( "context" "encoding/json" "io/ioutil" "os" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "nidavellir/config" "nidavellir/libs" "nidavellir/services/iofiles" rp "nidavellir/services/repo" "nidavellir/services/store" ) type JobManager struct { ctx context.Context db IStore errs chan error queue *JobQueue started bool // An array of completed jobs by the manager, this is primarily used for testing purposes CompletedJobs []int // Path to folder/volume that stores task output and logs AppFolderPath string token string provider string } // The manager holds a queue of job. Whenever there are new jobs, it will dispatch // the job. At any one time, it can only run one job. Thus the jobs are queued. // You should not be creating a JobManager, but should call NewScheduler which will // create a JobManager internally. func NewJobManager(db IStore, ctx context.Context, conf config.AppConfig) (*JobManager, error) { if !libs.PathExists(conf.WorkDir) { err := os.MkdirAll(conf.WorkDir, 0777) if err != nil { return nil, errors.Wrap(err, "could not create data folder") } } return &JobManager{ ctx: ctx, db: db, errs: make(chan error), queue: NewJobQueue(), started: false, CompletedJobs: []int{}, AppFolderPath: conf.WorkDir, token: conf.PAT.Token, provider: conf.PAT.Provider, }, nil } // Starts watching for jobs and executing work func (m *JobManager) Start() { if !m.started { m.started = true go m.searchForWork() go m.dispatchJobs() } } // Returns all errors from the JobManager. This will clean up errors in the channel // which means that only "new" errors are seen func (m *JobManager) Errors() []error { close(m.errs) var errs []error for err := range m.errs { errs = append(errs, err) } m.errs = make(chan error) return errs } // Stops all job and the job manager. func (m *JobManager) Close() { m.started = false } // Adds a job into the manager queue. Jobs are saved as TaskGroups in the // manager queue func (m *JobManager) AddJob(source *store.Source, trigger string) error { job, err := m.db.AddJob(source.Id, trigger) if err != nil { return err } repo, err := rp.NewRepo(source.RepoUrl, source.UniqueName, m.AppFolderPath, m.provider, m.token) if err != nil { return err } tg, err := NewTaskGroup(repo, m.ctx, source.Id, job.Id, source.NextTime, m.AppFolderPath) if err != nil { return err } extraEnv := source.SecretMap() extraEnv["task_date"] = source.NextTime.Format("2006-01-02 15:04:05") tg.AddEnvVar(extraEnv) switch trigger { case store.TriggerManual: m.queue.EnqueueTop(tg) default: m.queue.Enqueue(tg) } return nil } // Looks for new job every 10 seconds. If there are any, inserts them into the JobQueue func (m *JobManager) searchForWork() { ticker := time.NewTicker(10 * time.Second) for { select { case <-ticker.C: todos, err := m.db.GetSources(&store.GetSourceOption{ ScheduledToRun: true, }) if err != nil { m.errs <- errors.Wrap(err, "could not fetch sources in scheduler") continue } for _, t := range todos { if err := m.AddJob(t, store.TriggerSchedule); err != nil { m.errs <- errors.Wrap(err, "could not add new job") } } case <-m.ctx.Done(): return } } } // Dispatches any job from the jobQueue if any func (m *JobManager) dispatchJobs() { ch := make(chan bool, 1) ticker := time.NewTicker(5 * time.Second) maxJobs := 1 numJobs := 0 for { select { case <-ticker.C: if numJobs < maxJobs && m.queue.HasJob() { numJobs += 1 go m.dispatch(m.queue.Dequeue(), ch) } case <-ch: numJobs -= 1 case <-m.ctx.Done(): return } } } // Executes the TaskGroup func (m *JobManager) dispatch(taskGroup *TaskGroup, done chan<- bool) { defer func() { done <- true data, err := json.MarshalIndent(struct { Name string `json:"name"` Date string `json:"date"` }{taskGroup.Name, taskGroup.TaskDate}, "", "") if err != nil { log.Printf("could not save task meta data: %s", err.Error()) } path := iofiles.GetMetaFilePath(m.AppFolderPath, taskGroup.SourceId, taskGroup.JobId) _ = ioutil.WriteFile(path, data, 0666) }() if taskGroup == nil { return } logFile, err := iofiles.NewLogFile(m.AppFolderPath, taskGroup.SourceId, taskGroup.JobId, false) if err != nil { log.Println(errors.Wrap(err, "could not create log file")) return } defer logFile.Close() source, job, err := m.retrieveWorkDetails(taskGroup) if err != nil { err = multierror.Append(err, logFile.Write(err)) log.Println(err) return } err = m.initWork(source, job) if err != nil { err = multierror.Append(err, logFile.Write(err)) log.Println(err) return } // Execute tasks and save logs if any r, err := taskGroup.Execute() if err != nil { err = multierror.Append(err, m.failWork(source, job)) err = multierror.Append(err, logFile.Write(err)) log.Println(err) return } if err := m.completeWork(source, job); err != nil { err = multierror.Append(err, logFile.Write(err)) log.Println(err) } _ = logFile.Write(r.Logs) m.CompletedJobs = append(m.CompletedJobs, job.Id) } // Fetches details about the job from the database func (m *JobManager) retrieveWorkDetails(tg *TaskGroup) (*store.Source, *store.Job, error) { source, err := m.db.GetSource(tg.SourceId) if err != nil { return nil, nil, errors.Wrap(err, "source could not be retrieved from db") } job, err := m.db.GetJob(tg.JobId) if err != nil { return nil, nil, errors.Wrap(err, "job could not be retrieved from db") } return source, job, nil } // Announces that the job is completed func (m *JobManager) completeWork(source *store.Source, job *store.Job) error { source.ToCompleted() if err := job.ToSuccessState(); err != nil { return err } return m.updateJobAndSourceStatus(source, job) } // Initializes the work func (m *JobManager) initWork(source *store.Source, job *store.Job) error { source.ToRunning() if err := job.ToStartState(); err != nil { return err } return m.updateJobAndSourceStatus(source, job) } // Announces that the job has failed func (m *JobManager) failWork(source *store.Source, job *store.Job) error { source.ToCompleted() if err := job.ToFailureState(); err != nil { return err } return m.updateJobAndSourceStatus(source, job) } // Updates the job status func (m *JobManager) updateJobAndSourceStatus(source *store.Source, job *store.Job) error { if _, err := m.db.UpdateJob(job); err != nil { return errors.Wrap(err, "could not update job status") } if _, err := m.db.UpdateSource(source); err != nil { return errors.Wrap(err, "could not update source status") } return nil }
package main import ( "testing" ) func TestURLify(t *testing.T) { tests := map[string]struct { str string want string }{ "1": { str: "Mr John Smith ", want: "Mr%20John%20Smith", }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { if got := urlify(tt.str); got != tt.want { t.Errorf("got %v, want %v", got, tt.want) } }) } } func urlify(s string) string { // fmt.Println(s) var ss []string origin := toSlice(s) // fmt.Println(origin, len(origin)) origin = trim(reverse(origin)) // fmt.Println(origin, len(origin)) for _, v := range origin { ss = append(ss, replace(v)) } return toString(reverse(ss)) } func toSlice(s string) []string { var ss []string for i := 0; i < len(s); i++ { ss = append(ss, string(s[i])) } return ss } func trim(origin []string) []string { cnt := 0 var ss []string for _, v := range origin { if v == " " && cnt == 0 { continue } ss = append(ss, v) cnt++ } return ss } func replace(s string) string { if s == " " { return "%20" } return s } func reverse(origin []string) []string { var ss []string for i := len(origin) - 1; i >= 0; i-- { ss = append(ss, origin[i]) } return ss } // 上のreverseは以下でもいい func reverse2(ss []string) []string { for i, j := 0, len(ss)-1; i < j; i, j = i+1, j-1 { ss[i], ss[j] = ss[j], ss[i] } return ss } func toString(ss []string) string { var s string for _, v := range ss { s = s + v } return s }
package token import ( "fmt" "net/url" "os" "path/filepath" "strings" homedir "github.com/mitchellh/go-homedir" "github.com/cloudflare/cloudflared/config" ) // GenerateSSHCertFilePathFromURL will return a file path for creating short lived certificates func GenerateSSHCertFilePathFromURL(url *url.URL, suffix string) (string, error) { configPath, err := getConfigPath() if err != nil { return "", err } name := strings.Replace(fmt.Sprintf("%s%s-%s", url.Hostname(), url.EscapedPath(), suffix), "/", "-", -1) return filepath.Join(configPath, name), nil } // GenerateAppTokenFilePathFromURL will return a filepath for given Access org token func GenerateAppTokenFilePathFromURL(appDomain, aud string, suffix string) (string, error) { configPath, err := getConfigPath() if err != nil { return "", err } name := fmt.Sprintf("%s-%s-%s", appDomain, aud, suffix) name = strings.Replace(strings.Replace(name, "/", "-", -1), "*", "-", -1) return filepath.Join(configPath, name), nil } // generateOrgTokenFilePathFromURL will return a filepath for given Access application token func generateOrgTokenFilePathFromURL(authDomain string) (string, error) { configPath, err := getConfigPath() if err != nil { return "", err } name := strings.Replace(fmt.Sprintf("%s-org-token", authDomain), "/", "-", -1) return filepath.Join(configPath, name), nil } func getConfigPath() (string, error) { configPath, err := homedir.Expand(config.DefaultConfigSearchDirectories()[0]) if err != nil { return "", err } ok, err := config.FileExists(configPath) if !ok && err == nil { // create config directory if doesn't already exist err = os.Mkdir(configPath, 0700) } return configPath, err }
package msgbroker // MessageBroker defines our interface for connecting, producing and consuming messages type MessageBroker interface { PublishOnQueue(body []byte, queueName string) error Subscribe(exchangeName string, handlerFunc func(data []byte)) error Close() } /* // Defines our interface for connecting, producing and consuming messages. type IMessagingClient interface { ConnectToBroker(connectionString string) Publish(msg []byte, exchangeName string, exchangeType string) error PublishOnQueue(msg []byte, queueName string) error Subscribe(exchangeName string, exchangeType string, consumerName string, handlerFunc func(amqp.Delivery)) error SubscribeToQueue(queueName string, consumerName string, handlerFunc func(amqp.Delivery)) error Close() } */
// Shows a dialog with a multiline, a text, a list and some buttons. You can test the multiline attributes by clicking on the buttons. Each button is related to an attribute. Select if you want to set or get an attribute using the dropdown list. The value in the text will be used as value when a button is pressed. package main import ( "fmt" "github.com/matwachich/iup" ) func main() { iup.Open() defer iup.Close() multi := iup.MultiLine().SetHandle("multi").SetAttributes(`EXPAND=YES`) text := iup.MultiLine().SetHandle("text").SetAttributes(`EXPAND=HORIZONTAL`) list := iup.List().SetHandle("list").SetAttributes(`DROPDOWN=YES, 1=SET, 2=GET`) btn_append := iup.Button("Append").SetCallback("ACTION", btn_append_cb) btn_insert := iup.Button("Insert").SetCallback("ACTION", btn_insert_cb) btn_border := iup.Button("Border").SetCallback("ACTION", btn_border_cb) btn_caret := iup.Button("Caret").SetCallback("ACTION", btn_caret_cb) btn_readonly := iup.Button("Read only").SetCallback("ACTION", btn_readonly_cb) btn_selection := iup.Button("Selection").SetCallback("ACTION", btn_selection_cb) btn_selectedtext := iup.Button("Selected Text").SetCallback("ACTION", btn_selectedtext_cb) btn_nc := iup.Button("Number of characters").SetCallback("ACTION", btn_nc_cb) btn_value := iup.Button("Value").SetCallback("ACTION", btn_value_cb) dlg := iup.Dialog( iup.Vbox( multi, iup.Hbox(text, list), iup.Hbox(btn_append, btn_insert, btn_border, btn_caret, btn_readonly, btn_selection), iup.Hbox(btn_selectedtext, btn_nc, btn_value), ), ).SetAttributes(`TITLE="IupMultiLine Example", SIZE=HALFxQUARTER`) iup.Show(dlg) iup.MainLoop() } func btn_append_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("APPEND") } else { getAttrib("APPEND") } return iup.DEFAULT } func btn_insert_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("INSERT") } else { getAttrib("INSERT") } return iup.DEFAULT } func btn_border_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("BORDER") } else { getAttrib("BORDER") } return iup.DEFAULT } func btn_caret_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("CARET") } else { getAttrib("CARET") } return iup.DEFAULT } func btn_readonly_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("READONLY") } else { getAttrib("READONLY") } return iup.DEFAULT } func btn_selection_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("SELECTION") } else { getAttrib("SELECTION") } return iup.DEFAULT } func btn_selectedtext_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("SELECTEDTEXT") } else { getAttrib("SELECTEDTEXT") } return iup.DEFAULT } func btn_nc_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("NC") } else { getAttrib("NC") } return iup.DEFAULT } func btn_value_cb() int { if iup.GetHandle("list").GetInt("VALUE") == 1 { setAttrib("VALUE") } else { getAttrib("VALUE") } return iup.DEFAULT } func setAttrib(attrib string) { multi, text := iup.GetHandle("multi"), iup.GetHandle("text") multi.SetAttribute(attrib, text.GetAttribute("VALUE")) iup.Message("Set Attribute", fmt.Sprintf("Attribute %q set with value %q", attrib, text.GetAttribute("VALUE"))) } func getAttrib(attrib string) { multi, text := iup.GetHandle("multi"), iup.GetHandle("text") text.SetAttribute("VALUE", multi.GetAttribute(attrib)) }
package container import ( "errors" "fmt" ) var ( ErrObjectNotFound = errors.New("not found in container") ErrArgsNotInstanced = errors.New("args not instanced") ErrInvalidReturnValueCount = errors.New("invalid return value count") ErrRepeatedBind = errors.New("repeated bind") ErrInvalidArgs = errors.New("invalid args") ) //func isErrorType(t reflect.Type) bool { // return t.Implements(reflect.TypeOf((*error)(nil)).Elem()) //} // buildObjectNotFoundError is an error object represent object not found func buildObjectNotFoundError(msg string) error { return fmt.Errorf("%w: %s", ErrObjectNotFound, msg) } // buildArgNotInstancedError is an error object represent arg not instanced func buildArgNotInstancedError(msg string) error { return fmt.Errorf("%w: %s", ErrArgsNotInstanced, msg) } // buildInvalidReturnValueCountError is an error object represent return values count not match func buildInvalidReturnValueCountError(msg string) error { return fmt.Errorf("%w: %s", ErrInvalidReturnValueCount, msg) } // buildRepeatedBindError is an error object represent bind a value repeated func buildRepeatedBindError(msg string) error { return fmt.Errorf("%w: %s", ErrRepeatedBind, msg) } // buildInvalidArgsError is an error object represent invalid args func buildInvalidArgsError(msg string) error { return fmt.Errorf("%w: %s", ErrInvalidArgs, msg) }