text
stringlengths
11
4.05M
package main import ( "fmt" "log" ) type Point struct { x int y int } type Square struct { Centre Point Length int } func (p *Point) Move(x int, y int) { p.x += x p.y += y } func NewSquare(x int, y int, length int ) (* Square, error) { if length <=0 { return nil, fmt.Errorf("lengh must be >=0") } s := &Square{ Centre: Point{x,y}, Length: length, } return s, nil } func (s *Square) Move(dx int, dy int) { s.Centre.Move(dx,dy) } func(s *Square) Area() int { return s.Length * s.Length } func main() { s,err := NewSquare(1,1,10) if err != nil { log.Fatalf("Error : Cant' create square") } fmt.Printf("%+v\n",s) s.Move(2,3) fmt.Printf("%+v\n",s) fmt.Println(s.Area()) }
package logs import ( "context" "fmt" "io" "runtime" "time" ) var ( // std is the name of the standard logger in stdlib `log` std = New() callerPrettyfier = func(frame *runtime.Frame) (function string, file string) { function = fmt.Sprintf("%s()", frame.Function) file = frame.File short := file for i := len(file) - 1; i > 0; i-- { if file[i] == '/' || file[i] == '\\' { short = file[i+1:] break } } file = fmt.Sprintf("%s:%d", short, frame.Line) return } ) func AddFileHook(appName string) { rotateFileHook, _ := NewRotateFileHook(RotateFileConfig{ Filename: "./log/<level>_" + appName + ".log", MaxSize: 5, //MB MaxBackups: 7, SeparateLevelFile: true, MaxAge: 7, Level: DebugLevel, Formatter: &TextFormatter{ ForceColors: false, DisableColors: true, FullTimestamp: true, TimestampFormat: defaultTimestampFormat, QuoteEmptyFields: true, CallerPrettifier: callerPrettyfier, }, }) std.AddHook(rotateFileHook) } func Log() *Logger { return std } // SetOutput sets the standard logger output. func SetOutput(out io.Writer) { std.SetOutput(out) } // SetFormatter sets the standard logger formatter. func SetFormatter(formatter Formatter) { std.SetFormatter(formatter) } // SetReportCaller sets whether the standard logger will include the calling // method as a field. func SetReportCaller(include bool) { std.SetReportCaller(include) } // SetLevel sets the standard logger level. func SetLevel(level Level) { std.SetLevel(level) } // GetLevel returns the standard logger level. func GetLevel() Level { return std.GetLevel() } // IsLevelEnabled checks if the log level of the standard logger is greater than the level param func IsLevelEnabled(level Level) bool { return std.IsLevelEnabled(level) } // AddHook adds a hook to the standard logger hooks. func AddHook(hook Hook) { std.AddHook(hook) } // WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. func WithError(err error) *Entry { return std.WithField(ErrorKey, err) } // WithContext creates an entry from the standard logger and adds a context to it. func WithContext(ctx context.Context) *Entry { return std.WithContext(ctx) } // WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithField(key string, value interface{}) *Entry { return std.WithField(key, value) } // WithFields creates an entry from the standard logger and adds multiple // fields to it. This is simply a helper for `WithField`, invoking it // once for each field. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithFields(fields Fields) *Entry { return std.WithFields(fields) } // WithTime creats an entry from the standard logger and overrides the time of // logs generated with it. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithTime(t time.Time) *Entry { return std.WithTime(t) } // Trace logs a message at level Trace on the standard logger. func Trace(args ...interface{}) { std.Trace(args...) } // Debug logs a message at level Debug on the standard logger. func Debug(args ...interface{}) { std.Debug(args...) } // Print logs a message at level Info on the standard logger. func Print(args ...interface{}) { std.Print(args...) } // Info logs a message at level Info on the standard logger. func Info(args ...interface{}) { std.Info(args...) } // Warn logs a message at level Warn on the standard logger. func Warn(args ...interface{}) { std.Warn(args...) } // Warning logs a message at level Warn on the standard logger. func Warning(args ...interface{}) { std.Warning(args...) } // Error logs a message at level Error on the standard logger. func Error(args ...interface{}) { std.Error(args...) } // Panic logs a message at level Panic on the standard logger. func Panic(args ...interface{}) { std.Panic(args...) } // Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatal(args ...interface{}) { std.Fatal(args...) } // Tracef logs a message at level Trace on the standard logger. func Tracef(format string, args ...interface{}) { std.Tracef(format, args...) } // Debugf logs a message at level Debug on the standard logger. func Debugf(format string, args ...interface{}) { std.Debugf(format, args...) } // Printf logs a message at level Info on the standard logger. func Printf(format string, args ...interface{}) { std.Printf(format, args...) } // Infof logs a message at level Info on the standard logger. func Infof(format string, args ...interface{}) { std.Infof(format, args...) } // Warnf logs a message at level Warn on the standard logger. func Warnf(format string, args ...interface{}) { std.Warnf(format, args...) } // Warningf logs a message at level Warn on the standard logger. func Warningf(format string, args ...interface{}) { std.Warningf(format, args...) } // Errorf logs a message at level Error on the standard logger. func Errorf(format string, args ...interface{}) { std.Errorf(format, args...) } // Panicf logs a message at level Panic on the standard logger. func Panicf(format string, args ...interface{}) { std.Panicf(format, args...) } // Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalf(format string, args ...interface{}) { std.Fatalf(format, args...) } // Traceln logs a message at level Trace on the standard logger. func Traceln(args ...interface{}) { std.Traceln(args...) } // Debugln logs a message at level Debug on the standard logger. func Debugln(args ...interface{}) { std.Debugln(args...) } // Println logs a message at level Info on the standard logger. func Println(args ...interface{}) { std.Println(args...) } // Infoln logs a message at level Info on the standard logger. func Infoln(args ...interface{}) { std.Infoln(args...) } // Warnln logs a message at level Warn on the standard logger. func Warnln(args ...interface{}) { std.Warnln(args...) } // Warningln logs a message at level Warn on the standard logger. func Warningln(args ...interface{}) { std.Warningln(args...) } // Errorln logs a message at level Error on the standard logger. func Errorln(args ...interface{}) { std.Errorln(args...) } // Panicln logs a message at level Panic on the standard logger. func Panicln(args ...interface{}) { std.Panicln(args...) } // Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalln(args ...interface{}) { std.Fatalln(args...) }
package repositoryTemplate import ( "context" "errors" "fmt" "github.com/google/go-github/v19/github" "github.com/hashicorp/terraform/helper/schema" "gopkg.in/src-d/go-billy.v4/memfs" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/config" "gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing/object" "gopkg.in/src-d/go-git.v4/storage/memory" "io/ioutil" "os" "regexp" "time" ) func resourceRepositoryTemplateGitHub() *schema.Resource { return &schema.Resource{ Create: resourceRepositoryTemplateGitHubCreate, Read: resourceRepositoryTemplateGitHubRead, Update: resourceRepositoryTemplateGitHubUpdate, Delete: resourceRepositoryTemplateGitHubDelete, Schema: map[string]*schema.Schema{ "repository_owner": { Type: schema.TypeString, Required: true, }, "repository_name": { Type: schema.TypeString, Required: true, }, "target_branch": { Type: schema.TypeString, Required: true, }, "working_branch": { Type: schema.TypeString, Required: true, }, "files": { Type: schema.TypeMap, Required: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, }, } } func cloneRepository(d *schema.ResourceData, client *Client) (*git.Repository, error) { if client.GitHubClient == nil { return nil, errors.New("GitHub was not configured. Make sure that the provider configuration contains all required GitHub credentials") } prs, _, gitHubErr := client.GitHubClient.PullRequests.List(context.Background(), d.Get("repository_owner").(string), d.Get("repository_name").(string), &github.PullRequestListOptions{ State: "open", Base: d.Get("target_branch").(string), Head: fmt.Sprintf("%s:%s", d.Get("repository_owner").(string), d.Get("working_branch").(string)), Sort: "updated", Direction: "desc", }) if gitHubErr != nil { return nil, fmt.Errorf("Error while searching for PRs on GitHub: %s", gitHubErr) } branchName := d.Get("target_branch").(string) if len(prs) > 0 { branchName = *prs[0].Head.Ref } fs := memfs.New() storer := memory.NewStorage() // Clones the repository into the worktree (fs) and store all the .git content into the storer repository, cloneErr := git.Clone(storer, fs, &git.CloneOptions{ URL: fmt.Sprintf("https://github.com/%s/%s.git", d.Get("repository_owner").(string), d.Get("repository_name").(string)), Auth: client.GitHubGitAuth, RemoteName: "origin", ReferenceName: plumbing.NewBranchReferenceName(branchName), SingleBranch: true, NoCheckout: false, Depth: 1, RecurseSubmodules: git.NoRecurseSubmodules, Progress: nil, Tags: git.NoTags, }) if cloneErr != nil { return nil, fmt.Errorf("Error while checking out repository: %s", cloneErr) } return repository, nil } func resourceRepositoryTemplateGitHubCreate(d *schema.ResourceData, meta interface{}) error { err := resourceRepositoryTemplateGitHubUpdate(d, meta) if err != nil { return err } d.SetId(fmt.Sprintf("%s/%s", d.Get("repository_owner").(string), d.Get("repository_name").(string))) return nil } func resourceRepositoryTemplateGitHubUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*Client) repository, cloneErr := cloneRepository(d, client) if cloneErr != nil { return cloneErr } worktree, worktreeError := repository.Worktree() if worktreeError != nil { return fmt.Errorf("Error getting repository worktree: %s", worktreeError) } head, headErr := repository.Head() if headErr != nil { return fmt.Errorf("Error getting repository head: %s", headErr) } if head.Name().String() != fmt.Sprintf("refs/heads/%s", d.Get("working_branch").(string)) { checkoutErr := worktree.Checkout(&git.CheckoutOptions{ Hash: head.Hash(), Branch: plumbing.NewBranchReferenceName(d.Get("working_branch").(string)), Create: true, }) if checkoutErr != nil { return fmt.Errorf("Error checking out working branch: %s", checkoutErr) } } for filePath, contents := range d.Get("files").(map[string]interface{}) { file, openErr := worktree.Filesystem.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664) if openErr != nil { return fmt.Errorf("Error while opening file at path %s: %s", filePath, openErr) } _, writeErr := file.Write([]byte(contents.(string))) if writeErr != nil { return fmt.Errorf("Error while writing file at path %s: %s", filePath, writeErr) } closeErr := file.Close() if closeErr != nil { return fmt.Errorf("Error while closing file at path %s: %s", filePath, closeErr) } _, addErr := worktree.Add(filePath) if addErr != nil { return fmt.Errorf("Error while adding file at path %s to the Git index: %s", addErr) } } status, statusErr := worktree.Status() if statusErr != nil { return fmt.Errorf("Error getting the working tree status: %s", statusErr) } if !status.IsClean() { _, commitErr := worktree.Commit(client.CommitMessage, &git.CommitOptions{ All: false, Author: &object.Signature{ Email: client.CommitAuthorEmail, Name: client.CommitAuthorName, When: time.Now(), }, }) if commitErr != nil { return fmt.Errorf("Error committing changes: %s", commitErr) } pushErr := repository.Push(&git.PushOptions{ RemoteName: "origin", RefSpecs: []config.RefSpec{config.RefSpec("+refs/heads/*:refs/heads/*")}, Auth: client.GitHubGitAuth, Progress: nil, }) if pushErr != nil { return fmt.Errorf("Error pushing changes: %s", pushErr) } _, _, pullRequestErr := client.GitHubClient.PullRequests.Create(context.Background(), d.Get("repository_owner").(string), d.Get("repository_name").(string), &github.NewPullRequest{ Title: github.String(client.CommitMessage), Base: github.String(d.Get("target_branch").(string)), Head: github.String(d.Get("working_branch").(string)), Body: github.String("This PR was created by Terraform."), MaintainerCanModify: github.Bool(true), }) if !pullRequestAlreadyExists(pullRequestErr) { if pullRequestErr != nil { return fmt.Errorf("Error creating pull request: %s", pullRequestErr) } } } return nil } func pullRequestAlreadyExists(pullRequestErr error) bool { return pullRequestErr != nil && regexp.MustCompile(`^POST https://api.github.com/repos/[^/]+/[^/]+/pulls: 422 Validation Failed \[{Resource:PullRequest Field: Code:custom Message:A pull request already exists for .+\.}\]`).MatchString(pullRequestErr.Error()) } func resourceRepositoryTemplateGitHubRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*Client) repository, cloneErr := cloneRepository(d, client) if cloneErr != nil { return cloneErr } worktree, worktreeError := repository.Worktree() if worktreeError != nil { return fmt.Errorf("Error getting repository worktree: %s", worktreeError) } files := map[string]string{} for filePath, _ := range d.Get("files").(map[string]interface{}) { file, openErr := worktree.Filesystem.OpenFile(filePath, os.O_RDONLY, 0664) if openErr != nil { fmt.Errorf("Error while opening file: %s", filePath) } if file != nil { contents, readErr := ioutil.ReadAll(file) files[filePath] = string(contents) if readErr != nil { fmt.Errorf("Error while reading file at path %s: %s", filePath, readErr) } file.Close() } } d.Set("files", files) return nil } func resourceRepositoryTemplateGitHubDelete(d *schema.ResourceData, meta interface{}) error { // The delete step essentially does nothing, as it's unclear what it means to // "delete" a template. Should the files be removed? Should the files be reverted // to what they were before the template was first applied? How do we know when // the template was first applied? The safest option, therefore, is to just // leave the repository in the state that it's currently in. return nil }
package main import ( "bufio" "fmt" "log" "os" ) func main() { // First Attempt at opening file with bufio // file, err := os.Open("info.txt") // if err != nil { // log.Fatal(err) // } // // defer file.Close() // scan := bufio.NewScanner(file) // for scan.Scan() { // fmt.Println(scan.Text()) // } // opening the file in read-only mode. The file must exist (in the current working directory) // use a valid path! file, err := os.Open("info.txt") // error handling if err != nil { log.Fatal(err) } // defer closing the file defer file.Close() // the file value returned by os.Open() is wrapped in a bufio.Scanner just like a buffered reader. scanner := bufio.NewScanner(file) // reading the whole file line by line: for scanner.Scan() { fmt.Println(scanner.Text()) } // checking for any possible errors: if err := scanner.Err(); err != nil { log.Fatal(err) } }
package v1alpha1 import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" // DNSRecord represents the DNSRecord CRD which maps a set of hosts and cnames to a DNSZone. // +kubebuilder:object:root=true // +kubebuilder:subresource:status type DNSRecord struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata"` Spec DNSRecordSpec `json:"spec"` } // DNSRecordSpec defines the specification for a DNSRecord CRD. type DNSRecordSpec struct { DNSRecordHosts `json:",inline"` // +kubebuilder:validation:MinItems=1 Zones []DNSZoneRef `json:"zones"` TTL *TimeToLive `json:"ttl,omitempty"` TLS *TLSSpec `json:"tls,omitempty"` } // DNSZoneRef references a DNS zone and optionally overrides the default IP source. type DNSZoneRef struct { IPSource `json:",inline"` Name string `json:"name"` TTL *TimeToLive `json:"ttl,omitempty"` } // TLSSpec defines a specification to obtain a TLS certificate for a set of hostnames. type TLSSpec struct { CertificateName string `json:"certificateName"` SecretName string `json:"secretName,omitempty"` Issuer IssuerRef `json:"issuer"` } // IssuerRef is used to reference a cert-manager issuer. type IssuerRef struct { Name string `json:"name"` Kind IssuerKind `json:"kind,omitempty"` } // DNSRecordList represent multiple DNSRecord CRDs. // +kubebuilder:object:root=true type DNSRecordList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []DNSRecord `json:"items"` }
package context import ( "bytes" "fmt" "github.com/irisnet/irishub/app/v2/coinswap" "io" "os" "strings" "github.com/irisnet/irishub/app/protocol" "github.com/irisnet/irishub/app/v1/asset" "github.com/irisnet/irishub/app/v1/auth" "github.com/irisnet/irishub/client" "github.com/irisnet/irishub/client/keys" "github.com/irisnet/irishub/codec" cskeys "github.com/irisnet/irishub/crypto/keys" sdk "github.com/irisnet/irishub/types" "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" tmlite "github.com/tendermint/tendermint/lite" tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" ) // CLIContext implements a typical CLI context created in SDK modules for // transaction handling and queries. type CLIContext struct { Codec *codec.Codec AccDecoder auth.AccountDecoder Client rpcclient.Client Logger io.Writer OutputFormat string Height int64 NodeURI string AccountStore string TrustNode bool UseLedger bool Commit bool Async bool JSON bool PrintResponse bool Verifier tmlite.Verifier GenerateOnly bool fromAddress sdk.AccAddress fromName string Indent bool DryRun bool } // NewCLIContext returns a new initialized CLIContext with parameters from the // command line using Viper. func NewCLIContext() CLIContext { var rpc rpcclient.Client from := viper.GetString(client.FlagFrom) fromAddress, fromName := fromFields(from) nodeURI := viper.GetString(client.FlagNode) if nodeURI != "" { rpc = rpcclient.NewHTTP(nodeURI, "/websocket") } return CLIContext{ Client: rpc, NodeURI: nodeURI, AccountStore: protocol.AccountStore, Height: viper.GetInt64(client.FlagHeight), OutputFormat: viper.GetString(cli.OutputFlag), TrustNode: viper.GetBool(client.FlagTrustNode), UseLedger: viper.GetBool(client.FlagUseLedger), Async: viper.GetBool(client.FlagAsync), Commit: viper.GetBool(client.FlagCommit), JSON: viper.GetBool(client.FlagJson), PrintResponse: viper.GetBool(client.FlagPrintResponse), Verifier: createVerifier(rpc), DryRun: viper.GetBool(client.FlagDryRun), GenerateOnly: viper.GetBool(client.FlagGenerateOnly), fromAddress: fromAddress, fromName: fromName, Indent: viper.GetBool(client.FlagIndentResponse), } } func createVerifier(rpc rpcclient.SignClient) tmlite.Verifier { trustNodeDefined := viper.IsSet(client.FlagTrustNode) if !trustNodeDefined { return nil } trustNode := viper.GetBool(client.FlagTrustNode) if trustNode { return nil } else { height := int64(1) if _, err := rpc.Commit(&height); err != nil { fmt.Printf("snapshot's node can't verify the proof of result, you must set '--trust-node=true'\n") os.Exit(1) } } chainID := viper.GetString(client.FlagChainID) home := viper.GetString(cli.HomeFlag) nodeURI := viper.GetString(client.FlagNode) var errMsg bytes.Buffer if chainID == "" { errMsg.WriteString("--chain-id ") } if home == "" { errMsg.WriteString("--home ") } if nodeURI == "" { errMsg.WriteString("--node ") } if errMsg.Len() != 0 { fmt.Printf("Must specify these options: %s when --trust-node is false\n", errMsg.String()) os.Exit(1) } node := rpcclient.NewHTTP(nodeURI, "/websocket") cacheSize := 10 // TODO: determine appropriate cache size verifier, err := tmliteProxy.NewVerifier( chainID, home, node, log.NewNopLogger(), cacheSize, ) if err != nil { fmt.Printf("Create verifier failed: %s\n", err.Error()) fmt.Printf("Please check network connection and verify the address of the node to connect to\n") os.Exit(1) } return verifier } func fromFields(from string) (fromAddr sdk.AccAddress, fromName string) { // In generate-only mode, if the signer key doesn't exist in keystore, the fromAddress can be specified by --from-addr if from == "" { fromAddrString := viper.GetString(client.FlagFromAddr) if fromAddrString == "" { return nil, "" } address, err := sdk.AccAddressFromBech32(fromAddrString) if err != nil { fmt.Printf("invalid from address %s\n", fromAddrString) os.Exit(1) } fromAddr = address fromName = "" return } keybase, err := keys.GetKeyBase() if err != nil { fmt.Println("no keybase found") os.Exit(1) } var info cskeys.Info if addr, err := sdk.AccAddressFromBech32(from); err == nil { info, err = keybase.GetByAddress(addr) if err != nil { fmt.Printf("could not find key %s\n", from) os.Exit(1) } } else { info, err = keybase.Get(from) if err != nil { fmt.Fprint(os.Stderr, fmt.Sprintf("could not find key %s\n", from)) os.Exit(1) } } fromAddr = info.GetAddress() fromName = info.GetName() return } // WithCodec returns a copy of the context with an updated codec. func (cliCtx CLIContext) WithCodec(cdc *codec.Codec) CLIContext { cliCtx.Codec = cdc return cliCtx } // WithHeight returns a copy of the context with an updated height. func (cliCtx CLIContext) WithHeight(height int64) CLIContext { cliCtx.Height = height return cliCtx } // WithAccountDecoder returns a copy of the context with an updated account // decoder. func (cliCtx CLIContext) WithAccountDecoder(decoder auth.AccountDecoder) CLIContext { cliCtx.AccDecoder = decoder return cliCtx } // WithLogger returns a copy of the context with an updated logger. func (cliCtx CLIContext) WithLogger(w io.Writer) CLIContext { cliCtx.Logger = w return cliCtx } // WithAccountStore returns a copy of the context with an updated AccountStore. func (cliCtx CLIContext) WithAccountStore(accountStore string) CLIContext { cliCtx.AccountStore = accountStore return cliCtx } // WithTrustNode returns a copy of the context with an updated TrustNode flag. func (cliCtx CLIContext) WithTrustNode(trustNode bool) CLIContext { cliCtx.TrustNode = trustNode return cliCtx } // WithNodeURI returns a copy of the context with an updated node URI. func (cliCtx CLIContext) WithNodeURI(nodeURI string) CLIContext { cliCtx.NodeURI = nodeURI cliCtx.Client = rpcclient.NewHTTP(nodeURI, "/websocket") return cliCtx } // WithClient returns a copy of the context with an updated RPC client // instance. func (cliCtx CLIContext) WithClient(client rpcclient.Client) CLIContext { cliCtx.Client = client return cliCtx } // WithUseLedger returns a copy of the context with an updated UseLedger flag. func (cliCtx CLIContext) WithUseLedger(useLedger bool) CLIContext { cliCtx.UseLedger = useLedger return cliCtx } // WithCertifier - return a copy of the context with an updated Certifier func (cliCtx CLIContext) WithCertifier(verifier tmlite.Verifier) CLIContext { cliCtx.Verifier = verifier return cliCtx } func (cliCtx CLIContext) GetCoinType(coinName string) (sdk.CoinType, error) { var coinType sdk.CoinType coinName = strings.ToLower(coinName) if coinName == "" { return sdk.CoinType{}, fmt.Errorf("coin name is empty") } if coinName == sdk.Iris { coinType = sdk.IrisCoinType } else if strings.HasPrefix(coinName, coinswap.FormatUniABSPrefix) { return coinswap.GetUniCoinType(coinName) } else { params := asset.QueryTokenParams{ TokenId: coinName, } bz, err := cliCtx.Codec.MarshalJSON(params) if err != nil { return sdk.CoinType{}, err } res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", protocol.AssetRoute, asset.QueryToken), bz) if err != nil { return sdk.CoinType{}, fmt.Errorf("unsupported coin type \"%s\"", coinName) } var token asset.FungibleToken err = cliCtx.Codec.UnmarshalJSON(res, &token) if err != nil { return sdk.CoinType{}, err } coinType = token.GetCoinType() } return coinType, nil } func (cliCtx CLIContext) ConvertToMainUnit(coinsStr string) (coins []string, err error) { if len(coinsStr) == 0 { return coins, nil } coinStrs := strings.Split(coinsStr, ",") for _, coinStr := range coinStrs { mainUnit, err := sdk.GetCoinName(coinStr) coinType, err := cliCtx.GetCoinType(mainUnit) if err != nil { coins = append(coins, coinStr) continue } coin, err := coinType.Convert(coinStr, mainUnit) if err != nil { return nil, err } coins = append(coins, coin) } return coins, nil } func (cliCtx CLIContext) ParseCoin(coinStr string) (sdk.Coin, error) { mainUnit, err := sdk.GetCoinName(coinStr) if err != nil { return sdk.Coin{}, err } coinType, err := cliCtx.GetCoinType(mainUnit) if err != nil { return sdk.ParseCoin(coinStr) } coin, err := coinType.ConvertToMinDenomCoin(coinStr) if err != nil { return sdk.Coin{}, err } return coin, nil } func (cliCtx CLIContext) ParseCoins(coinsStr string) (coins sdk.Coins, err error) { if len(coinsStr) == 0 { return coins, nil } coinStrs := strings.Split(coinsStr, ",") coinMap := make(map[string]sdk.Coin) for _, coinStr := range coinStrs { coin, err := cliCtx.ParseCoin(coinStr) if err != nil { return sdk.Coins{}, err } if _, ok := coinMap[coin.Denom]; ok { coinMap[coin.Denom] = coinMap[coin.Denom].Add(coin) } else { coinMap[coin.Denom] = coin } } for _, coin := range coinMap { coins = append(coins, coin) } return sdk.NewCoins(coins...), nil } func (cliCtx CLIContext) ToMainUnit(coins sdk.Coins) string { ss, _ := cliCtx.ConvertToMainUnit(coins.String()) return strings.Join(ss, ",") }
package helper import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha1" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "restauranteapi/security" "strings" "time" ) // DatabaseX is a struct type DatabaseX struct { Location string // location of the database localhost, something.com, etc Database string // database name Collection string // collection name APIServer string // apiserver name } // Resultado is a struct type Resultado struct { ErrorCode string // error code ErrorDescription string // description IsSuccessful string // Y or N ReturnedValue string } // Credentials is a struct // ---------------------------------------------------- type Credentials struct { UserID string // error code UserName string // description KeyJWT string JWT string Expiry string CentroID string Roles []string // Y or N ClaimSet []security.Claim // Y or N ApplicationID string // IsAdmin string // IsAnonymous string // } // Claim is type Claim struct { Type string Value string } func add() { } func check(e error) { if e != nil { panic(e) } } // RestEnvVariables = restaurante environment variables // type RestEnvVariables struct { APIMongoDBLocation string // location of the database localhost, something.com, etc APIMongoDBDatabase string // database name APIAPIServerPort string // collection name APIAPIServerIPAddress string // apiserver name WEBDebug string // debug RecordCurrencyTick string // debug RunningFromServer string // debug WEBServerPort string // collection name ConfigFileFound string // collection name ApplicationID string // collection name UserID string // collection name AppFestaJuninaEnabled string AppBelnorthEnabled string AppBitcoinEnabled string } // Readfileintostruct is func Readfileintostruct() RestEnvVariables { dat, err := ioutil.ReadFile("restaurante.ini") check(err) fmt.Print(string(dat)) var restenv RestEnvVariables json.Unmarshal(dat, &restenv) if restenv.APIAPIServerIPAddress == "" { restenv.APIAPIServerIPAddress = "localhost" restenv.APIAPIServerPort = "1520" restenv.WEBServerPort = ":1510" restenv.RunningFromServer = "Ubuntu" restenv.WEBDebug = "Y" restenv.ConfigFileFound = "Not found - hardcoded values" } return restenv } func keyfortheday(day int) string { var key = "De tudo, ao meu amor serei atento antes" + "E com tal zelo, e sempre, e tanto" + "Que mesmo em face do maior encanto" + "Dele se encante mais meu pensamento" + "Quero vivê-lo em cada vão momento" + "E em seu louvor hei de espalhar meu canto" + "E rir meu riso e derramar meu pranto" + "Ao seu pesar ou seu contentamento" + "E assim quando mais tarde me procure" + "Quem sabe a morte, angústia de quem vive" + "Quem sabe a solidão, fim de quem ama" + "Eu possa lhe dizer do amor (que tive):" + "Que não seja imortal, posto que é chama" + "Mas que seja infinito enquanto dure" stringSlice := strings.Split(key, " ") var stringSliceFinal []string x := 0 for i := 0; i < len(stringSlice); i++ { if len(stringSlice[0]) > 3 { stringSliceFinal[x] = stringSlice[i] x++ } } return stringSliceFinal[day] } func getjwtfortoday() string { _, _, day := time.Now().Date() s := keyfortheday(day) h := sha1.New() h.Write([]byte(s)) sha1hash := hex.EncodeToString(h.Sum(nil)) return sha1hash } // Encrypt string to base64 crypto using AES func Encrypt(key []byte, text string) string { // key := []byte(keyText) plaintext := []byte(text) block, err := aes.NewCipher(key) if err != nil { panic(err) } // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { panic(err) } stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) // convert to base64 return base64.URLEncoding.EncodeToString(ciphertext) } // Decrypt from base64 to decrypted string func Decrypt(key []byte, cryptoText string) string { ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText) block, err := aes.NewCipher(key) if err != nil { panic(err) } // The IV needs to be unique, but not secure. Therefore it's common to // include it at the beginning of the ciphertext. if len(ciphertext) < aes.BlockSize { panic("ciphertext too short") } iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv) // XORKeyStream can work in-place if the two arguments are the same. stream.XORKeyStream(ciphertext, ciphertext) return fmt.Sprintf("%s", ciphertext) }
package main import ( "fmt" "sync" ) func main() { aux := 0 myPool := &sync.Pool{ New: func() interface{} { aux += 1 fmt.Println("Creating new instance") return aux }, } instance := myPool.Get() instance2 := myPool.Get() myPool.Put(instance) myPool.Put(instance2) a1 := myPool.Get() a2 := myPool.Get() a3 := myPool.Get() fmt.Println(a1) fmt.Println(a2) fmt.Println(a3) }
package main import ( "fmt" "github.com/zhoujiagen/localutils" ) func main() { // 捕获panic defer func() { if err := recover(); err != nil { fmt.Println(err) } }() // ====================================================== 1 创建和初始化 dict := make(map[string]int) localutils.Render(&dict) dict2 := map[string]string{"Red": "#da1337", "Orange": "#e95a22"} localutils.Render(&dict2) dict = map[string]int{} localutils.Render(dict == nil) // 键的选择 //The map key can be a value from any built-in or struct type // as long as the value can be used in an expression with the == operator. // Slices, functions, and struct types that contain slices can’t be used as map keys. // This will produce a compiler error. // dict3 := make(map[[]string]int) dict3 := make(map[int][]string) localutils.Render(&dict3) // ====================================================== 2 使用map var colors map[string]string localutils.Render(len(colors)) // 0 // colors["Red"] = "#da1337" // assignment to entry in nil map localutils.Render(colors == nil) // true // colors = make(map[string]string{"Red": "#da1337", "Orange": "#e95a22"}) // NO! colors = map[string]string{"Red": "#da1337", "Orange": "#e95a22"} localutils.Render(&colors) // 键值 if value, exist := colors["Blue"]; exist { localutils.Render(value) } else { localutils.Render("Not found") } value := colors["Blue"] localutils.Render(value) // 空字符串 // 遍历 colors = map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } localutils.Render(len(colors)) // 4 // 移除 //delete(colors, "Coral") removeColor(colors, "Coral") localutils.Render(len(colors)) // 3 // 添加 //colors["Coral"] = "#ff7F50" addColor(colors, "Coral", "#ff7F50") localutils.Render(len(colors)) // 4 for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } } // removeColor 移除 func removeColor(colors map[string]string, key string) { delete(colors, key) } // addColor 添加 func addColor(colors map[string]string, key string, value string) { colors[key] = value }
package httpsign import ( "errors" "github.com/gin-gonic/gin" ) func newPublicError(msg string) *gin.Error { return &gin.Error{ Err: errors.New(msg), Type: gin.ErrorTypePublic, } } var ( // ErrInvalidAuthorizationHeader error when get invalid format of Authorization header ErrInvalidAuthorizationHeader = newPublicError("Authorization header format is incorrect") // ErrInvalidKeyID error when KeyID in header does not provided ErrInvalidKeyID = newPublicError("Invalid keyId") // ErrDateNotFound error when no date in header ErrDateNotFound = newPublicError("There is no Date on Headers") // ErrIncorrectAlgorithm error when Algorithm in header does not match with secret key ErrIncorrectAlgorithm = newPublicError("Algorithm does not match") // ErrHeaderNotEnough error when requirements header do not appear on header field ErrHeaderNotEnough = newPublicError("Header field is not match requirement") // ErrNoSignature error when no Signature not found in header ErrNoSignature = newPublicError("No Signature header found in request") // ErrInvalidSign error when signing string do not match ErrInvalidSign = newPublicError("Invalid sign") // ErrMissingKeyID error when keyId not in header ErrMissingKeyID = newPublicError("keyId must be on header") // ErrMissingSignature error when signature not in header ErrMissingSignature = newPublicError("signature must be on header") // ErrUnterminatedParameter err when could not parse value ErrUnterminatedParameter = newPublicError("Unterminated parameter") // ErrMisingDoubleQuote err when after character = not have double quote ErrMisingDoubleQuote = newPublicError(`Missing " after = character`) // ErrMisingEqualCharacter err when there is no character = before " or , character ErrMisingEqualCharacter = newPublicError(`Missing = character =`) )
package stringutil_test import ( "fmt" "github.com/AdguardTeam/golibs/stringutil" ) func ExampleSet() { const s = "a" const nl = "\n" set := stringutil.NewSet() ok := set.Has(s) fmt.Printf(`%s contains "a" is %t`+nl, set, ok) set.Add(s) ok = set.Has(s) fmt.Printf(`%s contains "a" is %t`+nl, set, ok) other := stringutil.NewSet("a") ok = set.Equal(other) fmt.Printf("%s is equal to %s is %t\n", set, other, ok) fmt.Printf("values of %s are %q\n", set, set.Values()) set.Range(func(s string) (cont bool) { fmt.Printf("got value %q\n", s) return false }) set.Del(s) ok = set.Has(s) fmt.Printf(`%s contains "a" is %t`+nl, set, ok) set = stringutil.NewSet(s) fmt.Printf("%s has length %d\n", set, set.Len()) // Output: // // [] contains "a" is false // ["a"] contains "a" is true // ["a"] is equal to ["a"] is true // values of ["a"] are ["a"] // got value "a" // [] contains "a" is false // ["a"] has length 1 } func ExampleSet_Clone() { var set *stringutil.Set fmt.Printf("nil: %#v\n", set.Clone()) set = stringutil.NewSet("a") clone := set.Clone() clone.Add("b") fmt.Printf("orig: %t %t\n", set.Has("a"), set.Has("b")) fmt.Printf("clone: %t %t\n", clone.Has("a"), clone.Has("b")) // Output: // nil: (*stringutil.Set)(nil) // orig: true false // clone: true true } func ExampleSet_Equal() { set := stringutil.NewSet("a") fmt.Printf("same: %t\n", set.Equal(stringutil.NewSet("a"))) fmt.Printf("other elem: %t\n", set.Equal(stringutil.NewSet("b"))) fmt.Printf("other len: %t\n", set.Equal(stringutil.NewSet("a", "b"))) fmt.Printf("nil: %t\n", set.Equal(nil)) fmt.Printf("nil eq nil: %t\n", (*stringutil.Set)(nil).Equal(nil)) // Output: // same: true // other elem: false // other len: false // nil: false // nil eq nil: true } func ExampleSet_nil() { const s = "a" var set *stringutil.Set panicked := false setPanicked := func() { if v := recover(); v != nil { panicked = true } } func() { defer setPanicked() set.Del(s) }() fmt.Printf("panic after del: %t\n", panicked) func() { defer setPanicked() set.Has(s) }() fmt.Printf("panic after has: %t\n", panicked) func() { defer setPanicked() set.Len() }() fmt.Printf("panic after len: %t\n", panicked) func() { defer setPanicked() set.Range(func(s string) (cont bool) { fmt.Printf("got value %q\n", s) return true }) }() fmt.Printf("panic after range: %t\n", panicked) func() { defer setPanicked() set.Values() }() fmt.Printf("panic after values: %t\n", panicked) func() { defer setPanicked() set.Add(s) }() fmt.Printf("panic after add: %t\n", panicked) // Output: // // panic after del: false // panic after has: false // panic after len: false // panic after range: false // panic after values: false // panic after add: true }
// Copyright 2023 PingCAP, Inc. Licensed under Apache-2.0. package utils_test import ( "context" "sync" "testing" "time" "github.com/pingcap/errors" "github.com/pingcap/tidb/br/pkg/utils" "github.com/stretchr/testify/require" "github.com/tikv/client-go/v2/tikv" ) func TestRetryAdapter(t *testing.T) { req := require.New(t) begin := time.Now() bo := utils.AdaptTiKVBackoffer(context.Background(), 200, errors.New("everything is alright")) // This should sleep for 100ms. bo.Inner().Backoff(tikv.BoTiKVRPC(), errors.New("TiKV is in a deep dream")) sleeped := bo.TotalSleepInMS() req.GreaterOrEqual(sleeped, 50) req.LessOrEqual(sleeped, 150) requestedBackOff := [...]int{10, 20, 5, 0, 42, 48} wg := new(sync.WaitGroup) wg.Add(len(requestedBackOff)) for _, bms := range requestedBackOff { bms := bms go func() { bo.RequestBackOff(bms) wg.Done() }() } wg.Wait() req.Equal(bo.NextSleepInMS(), 48) req.NoError(bo.BackOff()) req.Equal(bo.TotalSleepInMS(), sleeped+48) bo.RequestBackOff(150) req.NoError(bo.BackOff()) bo.RequestBackOff(150) req.ErrorContains(bo.BackOff(), "everything is alright", "total = %d / %d", bo.TotalSleepInMS(), bo.MaxSleepInMS()) req.Greater(time.Since(begin), 200*time.Millisecond) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //402. Remove K Digits //Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. //Note: //The length of num is less than 10002 and will be ≥ k. //The given num does not contain any leading zero. //Example 1: //Input: num = "1432219", k = 3 //Output: "1219" //Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. //Example 2: //Input: num = "10200", k = 1 //Output: "200" //Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. //Example 3: //Input: num = "10", k = 2 //Output: "0" //Explanation: Remove all the digits from the number and it is left with nothing which is 0. //func removeKdigits(num string, k int) string { //} // Time Is Money
package bot import "testing" func TestMessageHandler(t *testing.T) { }
package hallOrderManager import ( "log" "os" "../config" "../elevio" "../localOrderDelegation" msg "../messageTypes" "../timer" "../utility" ) // This is the driver function for the hall order manager // and contains a for-select, thus should be called as a goroutine. func OrderManager( id string, localRequestCh <-chan localOrderDelegation.LocalOrder, fsmChannels msg.FSMChannels, channels msg.NetworkChannels) { manager := initializeManager(id, localRequestCh, fsmChannels, channels) for { select { ///////////////////////////// Channel from local order delegator to the hall order manager ///////////////////////////// case request := <-manager.localRequestChannel: if !manager.orders.anyActiveOrdersToFloor(request.Floor, request.Dir) { order := msg.HallOrder{ OwnerID: manager.id, ID: manager.orderIDCounter, State: msg.Received, Floor: request.Floor, Dir: request.Dir} manager.orderIDCounter++ order.Costs = make(map[string]int) manager.requestElevatorCost <- msg.RequestCost{ Order: msg.OrderStamped{ OrderID: order.ID, Floor: order.Floor, Dir: order.Dir}, RequestFrom: msg.HallOrderManager} order.Costs[manager.id] = <-manager.elevatorCost manager.orders.update(order) timer.SendWithDelayInt(config.ORDER_REPLY_TIME, manager.orderReplyTimeoutChannel, order.ID) timer.SendWithDelayHallOrder(config.ORDER_COMPLETION_TIMEOUT, manager.orderCompleteTimeoutChannel, order) orderToNet := msg.OrderStamped{ OrderID: order.ID, Floor: order.Floor, Dir: order.Dir} manager.logger.Printf("New order ID%v: %#v", order.ID, order) manager.requestToNetwork <- orderToNet } ///////////////////////////// Channels from local elevator fsm to the hall order manager ///////////////////////////// case buttonEvent := <-manager.orderComplete: dir := int(buttonEvent.Button) floor := buttonEvent.Floor setHallLight(dir, floor, false) for _, order := range manager.orders.getOrdersToFloorWithDir(floor, dir) { if order.State != msg.Completed { order.State = msg.Completed manager.orders.update(order) manager.logger.Printf("Order completed ID%v: %#v\n", order.ID, order) syncOrderWithOtherElevators(order, &manager) } } ///////////////////////////// Channel from network to the hall order manager ///////////////////////////// case reply := <-manager.replyToRequestFromNetwork: order, orderIsValid := manager.orders.getOrder(manager.id, reply.OrderID) if orderIsValid && order.State == msg.Received { order.Costs[reply.ID] = reply.Cost manager.orders.update(order) manager.logger.Printf("New reply to order ID%v: %#v", order.ID, order) } case confirm := <-manager.orderDelegationConfirmFromNetwork: order, orderIsValid := manager.orders.getOrder(manager.id, confirm.OrderID) if orderIsValid && order.State == msg.Delegate { order.State = msg.Serving manager.orders.update(order) manager.logger.Printf("Confirmed ID%v: %#v", order.ID, order) syncOrderWithOtherElevators(order, &manager) setHallLight(order.Dir, order.Floor, true) } case delegation := <-manager.delegationFromNetwork: incomingOrder := msg.HallOrder{ OwnerID: delegation.ID, ID: delegation.OrderID, DelegatedToID: manager.id, State: msg.Serving, Floor: delegation.Floor, Dir: delegation.Dir} manager.orders.update(incomingOrder) manager.logger.Printf("Received order from net: %#v", incomingOrder) orderForFSM := elevio.ButtonEvent{ Floor: delegation.Floor, Button: elevio.ButtonType(delegation.Dir)} manager.delegateToLocalElevator <- orderForFSM replyToNetwork := msg.OrderStamped{ ID: incomingOrder.OwnerID, OrderID: incomingOrder.ID, Floor: incomingOrder.Floor, Dir: incomingOrder.Dir} manager.delegationConfirmToNetwork <- replyToNetwork setHallLight(incomingOrder.Dir, incomingOrder.Floor, true) case order := <-manager.orderSyncFromNetwork: orderSaved, orderExists := manager.orders.getOrder(order.OwnerID, order.ID) // Conditionally synchronize the order itself if !orderExists || (orderExists && order.State >= orderSaved.State) { if !orderExists { timer.SendWithDelayHallOrder( config.ORDER_COMPLETION_TIMEOUT, manager.orderCompleteTimeoutChannel, order) } manager.orders.update(order) manager.logger.Printf("Sync from net: %#v", order) // Make sure lights are updated in accordance with the synched order if order.State == msg.Serving { setHallLight(order.Dir, order.Floor, true) } if order.State == msg.Completed { setHallLight(order.Dir, order.Floor, false) } } ///////////////////////////// Timeout channels ///////////////////////////// case orderID := <-manager.orderReplyTimeoutChannel: // Once the window of time we listen to replies runs out, // we can start delegating the hall order order, orderIsValid := manager.orders.getOrder(manager.id, orderID) if orderIsValid && order.State == msg.Received { id := getIDOfLowestCost(order.Costs, manager.id) order.DelegatedToID = id if id == manager.id { selfServeHallOrder(order, &manager) order.State = msg.Serving manager.logger.Printf("Delegating to local elevator order ID%v: %v", order.ID, order) syncOrderWithOtherElevators(order, &manager) setHallLight(order.Dir, order.Floor, true) } else { // Order will be given to another elevator on the network manager.logger.Printf("Delegate order ID%v to net (%v replies): %#v", order.ID, len(order.Costs), order) timer.SendWithDelayInt(config.ORDER_DELEGATION_TIME, manager.orderDelegationTimeoutChannel, orderID) order.State = msg.Delegate delegatedOrder := msg.OrderStamped{ ID: order.DelegatedToID, OrderID: orderID, Floor: order.Floor, Dir: order.Dir} manager.delegateToNetwork <- delegatedOrder } manager.orders.update(order) } case orderID := <-manager.orderDelegationTimeoutChannel: order, orderIsValid := manager.orders.getOrder(manager.id, orderID) if orderIsValid && order.State == msg.Delegate { order.DelegatedToID = manager.id selfServeHallOrder(order, &manager) order.State = msg.Serving manager.logger.Printf("Timeout delegation ID%v, sending to local elevator: %v", order.ID, order) manager.orders.update(order) syncOrderWithOtherElevators(order, &manager) setHallLight(order.Dir, order.Floor, true) } case order := <-manager.orderCompleteTimeoutChannel: orderSaved, orderExists := manager.orders.getOrder(order.OwnerID, order.ID) if orderExists && orderSaved.State != msg.Completed { manager.logger.Printf("Order timeout ID%v: %#v", order.ID, order) selfServeHallOrder(order, &manager) } case <-manager.ElevatorUnavailable: manager.logger.Printf("Local elevator unavailable, redelegating orders") orders := manager.orders.getOrderToID(manager.id) for _, order := range orders { redelegateOrder(order, &manager) } ///////////////////////////// Peer update channel ///////////////////////////// case peerUpdate := <-manager.peerUpdateChannel: for _, nodeid := range peerUpdate.Lost { manager.logger.Printf("Node lost connection: %v", nodeid) orders := manager.orders.getOrderToID(nodeid) for _, order := range orders { if order.OwnerID == manager.id { redelegateOrder(order, &manager) } else if !utility.IsStringInSlice(order.OwnerID, peerUpdate.Peers) && !utility.IsStringInSlice(order.DelegatedToID, peerUpdate.Peers) { redelegateOrder(order, &manager) } } } if len(peerUpdate.New) > 0 { manager.logger.Printf("New node(s) connected") orders := manager.orders.getOrderFromID(manager.id) for _, order := range orders { if order.State == msg.Serving { syncOrderWithOtherElevators(order, &manager) } } } } } } func initializeManager( id string, localRequestCh <-chan localOrderDelegation.LocalOrder, fsmChannels msg.FSMChannels, channels msg.NetworkChannels) HallOrderManager { var manager HallOrderManager manager.id = id manager.orders = make(OrderMap) manager.orderIDCounter = 1 manager.localRequestChannel = localRequestCh manager.requestToNetwork = channels.RequestToNetwork manager.delegateToNetwork = channels.DelegateOrderToNetwork manager.orderSyncToNetwork = channels.SyncOrderToNetwork manager.delegationConfirmToNetwork = channels.DelegationConfirmToNetwork manager.replyToRequestFromNetwork = channels.ReplyToRequestFromNetwork manager.orderDelegationConfirmFromNetwork = channels.DelegationConfirmFromNetwork manager.orderSyncFromNetwork = channels.SyncOrderFromNetwork manager.orderDelegationConfirmFromNetwork = channels.DelegationConfirmFromNetwork manager.delegationFromNetwork = channels.DelegateFromNetwork manager.peerUpdateChannel = channels.PeerUpdate manager.delegateToLocalElevator = fsmChannels.DelegateHallOrder manager.elevatorCost = fsmChannels.ReplyToHallOrderManager manager.requestElevatorCost = fsmChannels.RequestCost manager.orderComplete = fsmChannels.OrderComplete manager.ElevatorUnavailable = fsmChannels.ElevatorUnavailable manager.orderReplyTimeoutChannel = make(chan int) manager.orderDelegationTimeoutChannel = make(chan int) manager.orderCompleteTimeoutChannel = make(chan msg.HallOrder) filepath := "log/" + manager.id + "-hallOrderManager.log" file, _ := os.Create(filepath) manager.logger = log.New(file, "", log.Ltime|log.Lmicroseconds) // Turn off all hall lights on init for f := 0; f < config.N_FLOORS; f++ { for b := elevio.ButtonType(0); b < 2; b++ { elevio.SetButtonLamp(b, f, false) } } return manager } func selfServeHallOrder(order msg.HallOrder, manager *HallOrderManager) { orderToFSM := elevio.ButtonEvent{ Floor: order.Floor, Button: elevio.ButtonType(order.Dir)} manager.delegateToLocalElevator <- orderToFSM } func syncOrderWithOtherElevators(order msg.HallOrder, manager *HallOrderManager) { manager.orderSyncToNetwork <- order manager.logger.Printf("Sync order ID%v to net:%#v", order.ID, order) } func redelegateOrder(o msg.HallOrder, manager *HallOrderManager) { order, ok := manager.orders.getOrder(o.OwnerID, o.ID) if ok && order.State != msg.Completed { manager.logger.Printf("Redelegate order ID%v: %#v", order.ID, order) if order.OwnerID != manager.id { order.OwnerID = manager.id order.ID = manager.orderIDCounter manager.orderIDCounter++ } order.Costs = make(map[string]int) order.DelegatedToID = "" order.State = msg.Received manager.requestElevatorCost <- msg.RequestCost{ Order: msg.OrderStamped{ OrderID: order.ID, Floor: order.Floor, Dir: order.Dir}, RequestFrom: msg.HallOrderManager} order.Costs[manager.id] = <-manager.elevatorCost manager.orders.update(order) timer.SendWithDelayInt(config.ORDER_REPLY_TIME, manager.orderReplyTimeoutChannel, order.ID) timer.SendWithDelayHallOrder(config.ORDER_COMPLETION_TIMEOUT, manager.orderCompleteTimeoutChannel, order) orderToNet := msg.OrderStamped{ OrderID: order.ID, Floor: order.Floor, Dir: order.Dir} manager.requestToNetwork <- orderToNet } }
// Copyright 2023 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pool import ( "errors" "sync/atomic" "time" atomicutil "go.uber.org/atomic" ) var ( // ErrPoolClosed will be returned when submitting task to a closed pool. ErrPoolClosed = errors.New("this pool has been closed") // ErrPoolOverload will be returned when the pool is full and no workers available. ErrPoolOverload = errors.New("the number of concurrency has reached the upper limit and Block is set") // ErrPoolParamsInvalid will be returned when the pool params are invalid. ErrPoolParamsInvalid = errors.New("the pool params are invalid") ) // BasePool is base class of pool type BasePool struct { lastTuneTs atomicutil.Time name string generator atomic.Uint64 } // NewBasePool is to create a new BasePool. func NewBasePool() BasePool { return BasePool{ lastTuneTs: *atomicutil.NewTime(time.Now()), } } // SetName is to set name. func (p *BasePool) SetName(name string) { p.name = name } // Name is to get name. func (p *BasePool) Name() string { return p.name } // GenTaskID is to get a new task ID. func (p *BasePool) GenTaskID() uint64 { return p.generator.Add(1) } // LastTunerTs returns the last time when the pool was tuned. func (p *BasePool) LastTunerTs() time.Time { return p.lastTuneTs.Load() } // SetLastTuneTs sets the last time when the pool was tuned. func (p *BasePool) SetLastTuneTs(t time.Time) { p.lastTuneTs.Store(t) }
package app import ( "appengine" "github.com/codegangsta/negroni" "github.com/gorilla/mux" "github.com/unrolled/render" "github.com/vidoss/guithis/context" h "github.com/vidoss/guithis/handlers" "github.com/vidoss/guithis/views" "log" "net/http" ) type appHandler struct { c *context.AppContext fn func(*context.AppContext, http.ResponseWriter, *http.Request) } func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ah.c.GaeContext = appengine.NewContext(r) ah.fn(ah.c, w, r) } func init() { // Init context context := context.NewAppContext(render.Options{ Directory: "../templates", Layout: "layout", }) log.Println("Setting up handlers...") r := mux.NewRouter() n := negroni.Classic() r.Handle("/", appHandler{context, views.HomeHandler}).Methods("GET") r.Handle("/resource", appHandler{context, h.GetAllResources}).Methods("GET") r.Handle("/resource/{id}", appHandler{context, h.GetResource}).Methods("GET") r.Handle("/resource", appHandler{context, h.CreateResource}).Methods("POST") n.UseHandler(r) http.Handle("/", n) }
package handler import ( "context" "errors" "fmt" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" ) // GetUserPreferences 得到用户的偏好 func (j *JinmuIDService) GetUserPreferences(ctx context.Context, req *proto.GetUserPreferencesRequest, resp *proto.GetUserPreferencesResponse) error { token, ok := TokenFromContext(ctx) if !ok { return NewError(ErrInvalidUser, errors.New("failed to get token from context")) } userID, err := j.datastore.FindUserIDByToken(ctx, token) if err != nil { return NewError(ErrUserUnauthorized, fmt.Errorf("failed to find userID by token: %s", err.Error())) } if userID != req.UserId { return NewError(ErrInvalidUser, fmt.Errorf("user %d from request and user %d from token are inconsistent", req.UserId, userID)) } userPreferences, err := j.datastore.GetUserPreferencesByUserID(ctx, req.UserId) if err != nil { return NewError(ErrDatabase, fmt.Errorf("failed to get user preferences by userID %d: %s", req.UserId, err.Error())) } resp.Preferences = &proto.Preferences{ EnableHeartRateChart: userPreferences.EnableHeartRateChart, EnablePulseWaveChart: userPreferences.EnablePulseWaveChart, EnableWarmPrompt: userPreferences.EnableWarmPrompt, EnableChooseStatus: userPreferences.EnableChooseStatus, EnableConstitutionDifferentiation: userPreferences.EnableConstitutionDifferentiation, EnableSyndromeDifferentiation: userPreferences.EnableSyndromeDifferentiation, EnableWesternMedicineAnalysis: userPreferences.EnableWesternMedicineAnalysis, EnableMeridianBarGraph: userPreferences.EnableMeridianBarGraph, EnableComment: userPreferences.EnableComment, EnableHealthTrending: userPreferences.EnableHealthTrending, EnableLocalNotification: userPreferences.EnableLocationNotification, } return nil }
package model import ( "github.com/sairoutine/RenmeriMaker/server/constant" ) // Emoji is. type Emoji struct { ID uint64 `gorm:"AUTO_INCREMENT"` // multiple unique key NovelID uint64 `gorm:" unique_index:idx_novel_id_type"` Type string `gorm:"size:255;unique_index:idx_novel_id_type"` Count uint64 } func (e *Emoji) FileName() string { return constant.EmojiMap[e.Type] } func NewEmoji(novelID uint64, typ string) Emoji { return Emoji{ NovelID: novelID, Type: typ, Count: 0, } }
package nonceStore import ( dbComm "github.com/HNB-ECO/HNB-Blockchain/HNB/db/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/ledger/wrongStore/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/logging" ) var BlockLog logging.LogModule type WrongStore struct { db dbComm.KVStore } const ( LOGTABLE_WRONG string = "wrongIndex" WRONG = "wrong" ) func NewWrongStore(db dbComm.KVStore) common.WrongIndexStore { BlockLog = logging.GetLogIns() bc := &WrongStore{db: db} BlockLog.Info(LOGTABLE_WRONG, "create wrong index store") return bc } func (ws *WrongStore)GetWrongIndex(txid []byte) (string, error){ key := append([]byte(WRONG), txid[:]...) reason, err := ws.db.Get(key) if err != nil { return "", err } return string(reason), nil } func (ws *WrongStore)SetWrongIndex(txid []byte, reason string) error{ key := append([]byte(WRONG), txid[:]...) err := ws.db.Put(key, []byte(reason)) return err }
package common //Result const ( RESULT_OK int32 = 0 RESULT_ERR int32 = 1 ) //TaskType const ( TASK_ERROR int32 = 0 TASK_INSERT int32 = 1 TASK_SELECT int32 = 2 TASK_FLUSH int32 = 3 TASK_INFO int32 = 4 ) //NodeStatus const ( NODE_ERROR int32 = 0 NODE_CONNECTED int32 = 1 NODE_READY int32 = 2 ) //Common constants const ( CONST_UNINITIALIZED = -1 CONST_INT_MIN_VALUE = -CONST_INT_MAX_VALUE CONST_INT_MAX_VALUE = (int(^uint(0) >> 1)) CONST_UINT64_MAX_VALUE = (^(uint64(0))) ) //Device const ( ALL_GPUs = CONST_UNINITIALIZED TASK_UNINITIALIZED = CONST_UNINITIALIZED )
package main import ( "errors" "fmt" ) type matrix [3][6]bool func main() { fmt.Println("Hello, playground") TestSolve() } // O(n x m) func solve(m *matrix) (ret int, err error) { if m == nil { return -1, errors.New("expecting 3 x 6 matrix") } for m.removeNext() { } return m.eval(), nil } // O(log(n x m)) func (m *matrix) removeNext() bool { smallest := struct{ v, r, c int }{} for r := range m { for c := range m[r] { if !m[r][c] { continue } v := m.val(r, c) if v == 1 { m[r][c] = false return true } if v <= smallest.v { continue } smallest.v = v smallest.c = c smallest.r = r } } if smallest.v > 0 { m[smallest.r][smallest.c] = false return true } return false } // O(n x m) func (m *matrix) eval() (ret int) { for r := range m { for c := range m[r] { if m[r][c] { ret++ } } } return ret } // O(n + m) func (m matrix) val(row, col int) (ret int) { for i, r := range m { if i == row { for j := range r { if j != col && m[i][j] { ret++ } } } else if r[col] { ret++ } } return ret } func TestSolve() { type stest struct { input *matrix expected int } tests := []stest{ { input: &matrix{ [6]bool{true, false, true, false, false, true}, [6]bool{false, false, false, false, false, true}, [6]bool{false, false, false, false, true, false}, }, expected: 2, }, { input: &matrix{ [6]bool{true, false, true, false, false, true}, [6]bool{false, false, false, false, false, true}, [6]bool{false, false, true, false, true, false}, }, expected: 1, }, { input: &matrix{ [6]bool{true, false, true, false, false, false}, [6]bool{false, true, false, false, false, true}, [6]bool{false, false, false, true, true, false}, }, expected: 3, }, } for i, t := range tests { actual, err := solve(t.input) if err != nil { fmt.Printf("test %d: cannot solve this matrix, %s\n", i, err) } if actual != t.expected { fmt.Printf("test %d: expected %d, actual %d\n", i, t.expected, actual) } else { fmt.Printf("test %d: passed, %d\n", i, actual) } } }
package dbcon import ( "database/sql" "encoding/json" "fmt" "os" _ "github.com/lib/pq" ) type Config struct { User string `json:"user"` Dbname string `json:"dbname"` Password string `json:"password"` Host string `json:"host"` Sslmode string `json:"sslmode"` } func readConfigFile(filename string) (Config, error) { var setup Config file, err := os.ReadFile(filename) if err != nil { panic(err.Error()) } json.Unmarshal(file, &setup) return setup, err } func ConectaBD() *sql.DB { wdir, err := os.Getwd() if err != nil { panic(err.Error()) } configFileName := wdir + "/config/dbsetup.json" loadConfig, _ := readConfigFile(configFileName) conexao := fmt.Sprintf("user=%s dbname=%s password=%s host=%s sslmode=%s", loadConfig.User, loadConfig.Dbname, loadConfig.Password, loadConfig.Host, loadConfig.Sslmode) db, err := sql.Open("postgres", conexao) if err != nil { panic(err.Error()) } return db }
package qiwi import ( "context" "fmt" "time" ) // expirationTime set session expiration time for card payment const expirationTime time.Duration = 5 * time.Minute type T3DSStatus string const ( Ok3DS T3DSStatus = "PASSED" // Possible values - PASSED (3-D Secure passed), Fail3DS T3DSStatus = "NOT_PASSED" // NOT_PASSED (3-D Secure not passed), None3DS T3DSStatus = "WITHOUT" // WITHOUT (3-D Secure not required) ) type Card struct { CheckDate time.Time `json:"checkOperationDate"` // System date of the operation RequestID string `json:"requestUid"` // Card verification operation unique identifier String(200) Status Status `json:"status"` // Card verification status String Valid bool `json:"isValidCard"` // Logical flag means card is valid for purchases Bool T3DS T3DSStatus `json:"threeDsStatus"` // Information on customer authentication status. CardMethod CardMethod `json:"paymentMethod,omitempty"` // Payment method data for card CardInfo CardInfo `json:"cardInfo,omitempty"` // Card information CardToken CardToken `json:"createdToken,omitempty"` // Payment token data } type CardMethod struct { Type string `json:"type"` // Payment method type Payment string `json:"maskedPan"` // Masked card PAN Expiration string `json:"cardExpireDate"` // Card expiration date (MM/YY) Name string `json:"cardHolder"` // Cardholder name } type CardInfo struct { Country string `json:"issuingCountry"` // Issuer country code String(3) Bank string `json:"issuingBank"` // Issuer name String PaymentSystem string `json:"paymentSystem"` // Card's payment system String CardType string `json:"fundingSource"` // Card's type (debit/credit/..) String Product string `json:"paymentSystemProduct"` // Card's category String } type CardToken struct { Token string `json:"token"` // Card payment token String Name string `json:"name"` // Masked card PAN for which payment token issued String ExpirationDate time.Time `json:"expiredDate"` // Payment token expiration date. ISO-8601 Account string `json:"account"` // Customer account for which payment token issued String } func (p *Payment) CardRequest(ctx context.Context, pubKey string, amount int) (err error) { // Moscow time moscow_timezone, err := time.LoadLocation("Europe/Moscow") if err != nil { return err } moscow_now := time.Now().In(moscow_timezone) p.PublicKey = pubKey p.Amount = NewAmountInRubles(amount) p.Expiration = QIWITime{Time: moscow_now.Add(expirationTime)} // Make request link requestLink := fmt.Sprintf("/payin/v1/sites/%s/payments/%s", p.SiteID, p.PaymentID) return proceedRequest(ctx, "PUT", requestLink, p) }
package user import ( "net/http" "proximity/apis/http/utils" "proximity/config" "proximity/pkg/clients/db" grpcPkg "proximity/pkg/clients/grpc" httpPkg "proximity/pkg/clients/http" user "proximity/pkg/user" "proximity/pkg/user/favourite" "proximity/pkg/user/rating" userRepo "proximity/pkg/user/repo" "github.com/gin-gonic/gin" "github.com/ralstan-vaz/go-errors" ) // Service contains the methods required to perfom operation's on users type Service struct { user user.UsersInterface } // NewUserService Create a new instance of a Service with the given dependencies. func NewUserService(conf config.IConfig, db *db.Instances, httpReq httpPkg.IRequest, grpcConn grpcPkg.IGrpcConnections) *Service { userRating := rating.NewRating(conf, httpReq) userFavourites := favourite.NewFavourite(conf, grpcConn) userRepo := userRepo.NewUserRepo(conf, db) userService := user.NewUser(conf, userRepo, userRating, userFavourites) return &Service{user: userService} } func (service *Service) getAll(ctx *gin.Context) { var err error defer utils.HandleError(ctx, &err) users, err := service.user.GetAll() if err != nil { return } ctx.JSON(http.StatusOK, users) } func (service *Service) getOne(ctx *gin.Context) { var err error defer utils.HandleError(ctx, &err) userID := ctx.Param("userID") users, err := service.user.GetOne(userID) if err != nil { return } ctx.JSON(http.StatusOK, users) } func (service *Service) getWithInfo(ctx *gin.Context) { var err error defer utils.HandleError(ctx, &err) userID := ctx.Param("userID") users, err := service.user.GetWithInfo(userID) if err != nil { return } ctx.JSON(http.StatusOK, users) } func (service *Service) insert(ctx *gin.Context) { var err error defer utils.HandleError(ctx, &err) var user user.User if err = ctx.ShouldBindJSON(&user); err != nil { err = errors.NewBadRequest("Could not bind request to model").SetCode("APIS.HTTP.USER.REQUEST_BIND_FAILD") return } err = service.user.Insert(user) if err != nil { return } ctx.JSON(http.StatusOK, nil) }
/* Description A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1, a2, ..., aN) be any sequence (ai1, ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8). Your program, when given the numeric sequence, must find the length of its longest ordered subsequence. Input The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000 Output Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence. Sample Input 7 1 7 3 5 9 4 8 Sample Output 4 Source Northeastern Europe 2002, Far-Eastern Subregion */ package main import "slices" func main() { assert(longest([]int{1, 7, 3, 5, 9, 4, 8}) == 4) } func assert(x bool) { if !x { panic("assertion failed") } } func longest(a []int) int { n := len(a) p := make([]int, n) for i := 0; i < n; i++ { p[i] = 1 for j := 0; j < i; j++ { if a[i] > a[j] && p[i] < p[j]+1 { p[i] = p[j] + 1 } } } return slices.Max(p) }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" computepb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/compute_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute" ) // Server implements the gRPC interface for HealthCheck. type HealthCheckServer struct{} // ProtoToHealthCheckHttp2HealthCheckPortSpecificationEnum converts a HealthCheckHttp2HealthCheckPortSpecificationEnum enum from its proto representation. func ProtoToComputeHealthCheckHttp2HealthCheckPortSpecificationEnum(e computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum) *compute.HealthCheckHttp2HealthCheckPortSpecificationEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum_name[int32(e)]; ok { e := compute.HealthCheckHttp2HealthCheckPortSpecificationEnum(n[len("ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum"):]) return &e } return nil } // ProtoToHealthCheckHttp2HealthCheckProxyHeaderEnum converts a HealthCheckHttp2HealthCheckProxyHeaderEnum enum from its proto representation. func ProtoToComputeHealthCheckHttp2HealthCheckProxyHeaderEnum(e computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum) *compute.HealthCheckHttp2HealthCheckProxyHeaderEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum_name[int32(e)]; ok { e := compute.HealthCheckHttp2HealthCheckProxyHeaderEnum(n[len("ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum"):]) return &e } return nil } // ProtoToHealthCheckHttpHealthCheckPortSpecificationEnum converts a HealthCheckHttpHealthCheckPortSpecificationEnum enum from its proto representation. func ProtoToComputeHealthCheckHttpHealthCheckPortSpecificationEnum(e computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum) *compute.HealthCheckHttpHealthCheckPortSpecificationEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum_name[int32(e)]; ok { e := compute.HealthCheckHttpHealthCheckPortSpecificationEnum(n[len("ComputeHealthCheckHttpHealthCheckPortSpecificationEnum"):]) return &e } return nil } // ProtoToHealthCheckHttpHealthCheckProxyHeaderEnum converts a HealthCheckHttpHealthCheckProxyHeaderEnum enum from its proto representation. func ProtoToComputeHealthCheckHttpHealthCheckProxyHeaderEnum(e computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum) *compute.HealthCheckHttpHealthCheckProxyHeaderEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum_name[int32(e)]; ok { e := compute.HealthCheckHttpHealthCheckProxyHeaderEnum(n[len("ComputeHealthCheckHttpHealthCheckProxyHeaderEnum"):]) return &e } return nil } // ProtoToHealthCheckHttpsHealthCheckPortSpecificationEnum converts a HealthCheckHttpsHealthCheckPortSpecificationEnum enum from its proto representation. func ProtoToComputeHealthCheckHttpsHealthCheckPortSpecificationEnum(e computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum) *compute.HealthCheckHttpsHealthCheckPortSpecificationEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum_name[int32(e)]; ok { e := compute.HealthCheckHttpsHealthCheckPortSpecificationEnum(n[len("ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum"):]) return &e } return nil } // ProtoToHealthCheckHttpsHealthCheckProxyHeaderEnum converts a HealthCheckHttpsHealthCheckProxyHeaderEnum enum from its proto representation. func ProtoToComputeHealthCheckHttpsHealthCheckProxyHeaderEnum(e computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum) *compute.HealthCheckHttpsHealthCheckProxyHeaderEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum_name[int32(e)]; ok { e := compute.HealthCheckHttpsHealthCheckProxyHeaderEnum(n[len("ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum"):]) return &e } return nil } // ProtoToHealthCheckSslHealthCheckPortSpecificationEnum converts a HealthCheckSslHealthCheckPortSpecificationEnum enum from its proto representation. func ProtoToComputeHealthCheckSslHealthCheckPortSpecificationEnum(e computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum) *compute.HealthCheckSslHealthCheckPortSpecificationEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum_name[int32(e)]; ok { e := compute.HealthCheckSslHealthCheckPortSpecificationEnum(n[len("ComputeHealthCheckSslHealthCheckPortSpecificationEnum"):]) return &e } return nil } // ProtoToHealthCheckSslHealthCheckProxyHeaderEnum converts a HealthCheckSslHealthCheckProxyHeaderEnum enum from its proto representation. func ProtoToComputeHealthCheckSslHealthCheckProxyHeaderEnum(e computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum) *compute.HealthCheckSslHealthCheckProxyHeaderEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum_name[int32(e)]; ok { e := compute.HealthCheckSslHealthCheckProxyHeaderEnum(n[len("ComputeHealthCheckSslHealthCheckProxyHeaderEnum"):]) return &e } return nil } // ProtoToHealthCheckTcpHealthCheckPortSpecificationEnum converts a HealthCheckTcpHealthCheckPortSpecificationEnum enum from its proto representation. func ProtoToComputeHealthCheckTcpHealthCheckPortSpecificationEnum(e computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum) *compute.HealthCheckTcpHealthCheckPortSpecificationEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum_name[int32(e)]; ok { e := compute.HealthCheckTcpHealthCheckPortSpecificationEnum(n[len("ComputeHealthCheckTcpHealthCheckPortSpecificationEnum"):]) return &e } return nil } // ProtoToHealthCheckTcpHealthCheckProxyHeaderEnum converts a HealthCheckTcpHealthCheckProxyHeaderEnum enum from its proto representation. func ProtoToComputeHealthCheckTcpHealthCheckProxyHeaderEnum(e computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum) *compute.HealthCheckTcpHealthCheckProxyHeaderEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum_name[int32(e)]; ok { e := compute.HealthCheckTcpHealthCheckProxyHeaderEnum(n[len("ComputeHealthCheckTcpHealthCheckProxyHeaderEnum"):]) return &e } return nil } // ProtoToHealthCheckTypeEnum converts a HealthCheckTypeEnum enum from its proto representation. func ProtoToComputeHealthCheckTypeEnum(e computepb.ComputeHealthCheckTypeEnum) *compute.HealthCheckTypeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeHealthCheckTypeEnum_name[int32(e)]; ok { e := compute.HealthCheckTypeEnum(n[len("ComputeHealthCheckTypeEnum"):]) return &e } return nil } // ProtoToHealthCheckHttp2HealthCheck converts a HealthCheckHttp2HealthCheck resource from its proto representation. func ProtoToComputeHealthCheckHttp2HealthCheck(p *computepb.ComputeHealthCheckHttp2HealthCheck) *compute.HealthCheckHttp2HealthCheck { if p == nil { return nil } obj := &compute.HealthCheckHttp2HealthCheck{ Port: dcl.Int64OrNil(p.Port), PortName: dcl.StringOrNil(p.PortName), PortSpecification: ProtoToComputeHealthCheckHttp2HealthCheckPortSpecificationEnum(p.GetPortSpecification()), Host: dcl.StringOrNil(p.Host), RequestPath: dcl.StringOrNil(p.RequestPath), ProxyHeader: ProtoToComputeHealthCheckHttp2HealthCheckProxyHeaderEnum(p.GetProxyHeader()), Response: dcl.StringOrNil(p.Response), } return obj } // ProtoToHealthCheckHttpHealthCheck converts a HealthCheckHttpHealthCheck resource from its proto representation. func ProtoToComputeHealthCheckHttpHealthCheck(p *computepb.ComputeHealthCheckHttpHealthCheck) *compute.HealthCheckHttpHealthCheck { if p == nil { return nil } obj := &compute.HealthCheckHttpHealthCheck{ Port: dcl.Int64OrNil(p.Port), PortName: dcl.StringOrNil(p.PortName), PortSpecification: ProtoToComputeHealthCheckHttpHealthCheckPortSpecificationEnum(p.GetPortSpecification()), Host: dcl.StringOrNil(p.Host), RequestPath: dcl.StringOrNil(p.RequestPath), ProxyHeader: ProtoToComputeHealthCheckHttpHealthCheckProxyHeaderEnum(p.GetProxyHeader()), Response: dcl.StringOrNil(p.Response), } return obj } // ProtoToHealthCheckHttpsHealthCheck converts a HealthCheckHttpsHealthCheck resource from its proto representation. func ProtoToComputeHealthCheckHttpsHealthCheck(p *computepb.ComputeHealthCheckHttpsHealthCheck) *compute.HealthCheckHttpsHealthCheck { if p == nil { return nil } obj := &compute.HealthCheckHttpsHealthCheck{ Port: dcl.Int64OrNil(p.Port), PortName: dcl.StringOrNil(p.PortName), PortSpecification: ProtoToComputeHealthCheckHttpsHealthCheckPortSpecificationEnum(p.GetPortSpecification()), Host: dcl.StringOrNil(p.Host), RequestPath: dcl.StringOrNil(p.RequestPath), ProxyHeader: ProtoToComputeHealthCheckHttpsHealthCheckProxyHeaderEnum(p.GetProxyHeader()), Response: dcl.StringOrNil(p.Response), } return obj } // ProtoToHealthCheckSslHealthCheck converts a HealthCheckSslHealthCheck resource from its proto representation. func ProtoToComputeHealthCheckSslHealthCheck(p *computepb.ComputeHealthCheckSslHealthCheck) *compute.HealthCheckSslHealthCheck { if p == nil { return nil } obj := &compute.HealthCheckSslHealthCheck{ Port: dcl.Int64OrNil(p.Port), PortName: dcl.StringOrNil(p.PortName), PortSpecification: ProtoToComputeHealthCheckSslHealthCheckPortSpecificationEnum(p.GetPortSpecification()), Request: dcl.StringOrNil(p.Request), Response: dcl.StringOrNil(p.Response), ProxyHeader: ProtoToComputeHealthCheckSslHealthCheckProxyHeaderEnum(p.GetProxyHeader()), } return obj } // ProtoToHealthCheckTcpHealthCheck converts a HealthCheckTcpHealthCheck resource from its proto representation. func ProtoToComputeHealthCheckTcpHealthCheck(p *computepb.ComputeHealthCheckTcpHealthCheck) *compute.HealthCheckTcpHealthCheck { if p == nil { return nil } obj := &compute.HealthCheckTcpHealthCheck{ Port: dcl.Int64OrNil(p.Port), PortName: dcl.StringOrNil(p.PortName), PortSpecification: ProtoToComputeHealthCheckTcpHealthCheckPortSpecificationEnum(p.GetPortSpecification()), Request: dcl.StringOrNil(p.Request), Response: dcl.StringOrNil(p.Response), ProxyHeader: ProtoToComputeHealthCheckTcpHealthCheckProxyHeaderEnum(p.GetProxyHeader()), } return obj } // ProtoToHealthCheck converts a HealthCheck resource from its proto representation. func ProtoToHealthCheck(p *computepb.ComputeHealthCheck) *compute.HealthCheck { obj := &compute.HealthCheck{ CheckIntervalSec: dcl.Int64OrNil(p.CheckIntervalSec), Description: dcl.StringOrNil(p.Description), HealthyThreshold: dcl.Int64OrNil(p.HealthyThreshold), Http2HealthCheck: ProtoToComputeHealthCheckHttp2HealthCheck(p.GetHttp2HealthCheck()), HttpHealthCheck: ProtoToComputeHealthCheckHttpHealthCheck(p.GetHttpHealthCheck()), HttpsHealthCheck: ProtoToComputeHealthCheckHttpsHealthCheck(p.GetHttpsHealthCheck()), Name: dcl.StringOrNil(p.Name), SslHealthCheck: ProtoToComputeHealthCheckSslHealthCheck(p.GetSslHealthCheck()), TcpHealthCheck: ProtoToComputeHealthCheckTcpHealthCheck(p.GetTcpHealthCheck()), Type: ProtoToComputeHealthCheckTypeEnum(p.GetType()), UnhealthyThreshold: dcl.Int64OrNil(p.UnhealthyThreshold), TimeoutSec: dcl.Int64OrNil(p.TimeoutSec), Region: dcl.StringOrNil(p.Region), Project: dcl.StringOrNil(p.Project), SelfLink: dcl.StringOrNil(p.SelfLink), Location: dcl.StringOrNil(p.Location), } return obj } // HealthCheckHttp2HealthCheckPortSpecificationEnumToProto converts a HealthCheckHttp2HealthCheckPortSpecificationEnum enum to its proto representation. func ComputeHealthCheckHttp2HealthCheckPortSpecificationEnumToProto(e *compute.HealthCheckHttp2HealthCheckPortSpecificationEnum) computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum { if e == nil { return computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum(0) } if v, ok := computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum_value["HealthCheckHttp2HealthCheckPortSpecificationEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum(v) } return computepb.ComputeHealthCheckHttp2HealthCheckPortSpecificationEnum(0) } // HealthCheckHttp2HealthCheckProxyHeaderEnumToProto converts a HealthCheckHttp2HealthCheckProxyHeaderEnum enum to its proto representation. func ComputeHealthCheckHttp2HealthCheckProxyHeaderEnumToProto(e *compute.HealthCheckHttp2HealthCheckProxyHeaderEnum) computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum { if e == nil { return computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum(0) } if v, ok := computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum_value["HealthCheckHttp2HealthCheckProxyHeaderEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum(v) } return computepb.ComputeHealthCheckHttp2HealthCheckProxyHeaderEnum(0) } // HealthCheckHttpHealthCheckPortSpecificationEnumToProto converts a HealthCheckHttpHealthCheckPortSpecificationEnum enum to its proto representation. func ComputeHealthCheckHttpHealthCheckPortSpecificationEnumToProto(e *compute.HealthCheckHttpHealthCheckPortSpecificationEnum) computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum { if e == nil { return computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum(0) } if v, ok := computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum_value["HealthCheckHttpHealthCheckPortSpecificationEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum(v) } return computepb.ComputeHealthCheckHttpHealthCheckPortSpecificationEnum(0) } // HealthCheckHttpHealthCheckProxyHeaderEnumToProto converts a HealthCheckHttpHealthCheckProxyHeaderEnum enum to its proto representation. func ComputeHealthCheckHttpHealthCheckProxyHeaderEnumToProto(e *compute.HealthCheckHttpHealthCheckProxyHeaderEnum) computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum { if e == nil { return computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum(0) } if v, ok := computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum_value["HealthCheckHttpHealthCheckProxyHeaderEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum(v) } return computepb.ComputeHealthCheckHttpHealthCheckProxyHeaderEnum(0) } // HealthCheckHttpsHealthCheckPortSpecificationEnumToProto converts a HealthCheckHttpsHealthCheckPortSpecificationEnum enum to its proto representation. func ComputeHealthCheckHttpsHealthCheckPortSpecificationEnumToProto(e *compute.HealthCheckHttpsHealthCheckPortSpecificationEnum) computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum { if e == nil { return computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum(0) } if v, ok := computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum_value["HealthCheckHttpsHealthCheckPortSpecificationEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum(v) } return computepb.ComputeHealthCheckHttpsHealthCheckPortSpecificationEnum(0) } // HealthCheckHttpsHealthCheckProxyHeaderEnumToProto converts a HealthCheckHttpsHealthCheckProxyHeaderEnum enum to its proto representation. func ComputeHealthCheckHttpsHealthCheckProxyHeaderEnumToProto(e *compute.HealthCheckHttpsHealthCheckProxyHeaderEnum) computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum { if e == nil { return computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum(0) } if v, ok := computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum_value["HealthCheckHttpsHealthCheckProxyHeaderEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum(v) } return computepb.ComputeHealthCheckHttpsHealthCheckProxyHeaderEnum(0) } // HealthCheckSslHealthCheckPortSpecificationEnumToProto converts a HealthCheckSslHealthCheckPortSpecificationEnum enum to its proto representation. func ComputeHealthCheckSslHealthCheckPortSpecificationEnumToProto(e *compute.HealthCheckSslHealthCheckPortSpecificationEnum) computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum { if e == nil { return computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum(0) } if v, ok := computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum_value["HealthCheckSslHealthCheckPortSpecificationEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum(v) } return computepb.ComputeHealthCheckSslHealthCheckPortSpecificationEnum(0) } // HealthCheckSslHealthCheckProxyHeaderEnumToProto converts a HealthCheckSslHealthCheckProxyHeaderEnum enum to its proto representation. func ComputeHealthCheckSslHealthCheckProxyHeaderEnumToProto(e *compute.HealthCheckSslHealthCheckProxyHeaderEnum) computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum { if e == nil { return computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum(0) } if v, ok := computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum_value["HealthCheckSslHealthCheckProxyHeaderEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum(v) } return computepb.ComputeHealthCheckSslHealthCheckProxyHeaderEnum(0) } // HealthCheckTcpHealthCheckPortSpecificationEnumToProto converts a HealthCheckTcpHealthCheckPortSpecificationEnum enum to its proto representation. func ComputeHealthCheckTcpHealthCheckPortSpecificationEnumToProto(e *compute.HealthCheckTcpHealthCheckPortSpecificationEnum) computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum { if e == nil { return computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum(0) } if v, ok := computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum_value["HealthCheckTcpHealthCheckPortSpecificationEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum(v) } return computepb.ComputeHealthCheckTcpHealthCheckPortSpecificationEnum(0) } // HealthCheckTcpHealthCheckProxyHeaderEnumToProto converts a HealthCheckTcpHealthCheckProxyHeaderEnum enum to its proto representation. func ComputeHealthCheckTcpHealthCheckProxyHeaderEnumToProto(e *compute.HealthCheckTcpHealthCheckProxyHeaderEnum) computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum { if e == nil { return computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum(0) } if v, ok := computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum_value["HealthCheckTcpHealthCheckProxyHeaderEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum(v) } return computepb.ComputeHealthCheckTcpHealthCheckProxyHeaderEnum(0) } // HealthCheckTypeEnumToProto converts a HealthCheckTypeEnum enum to its proto representation. func ComputeHealthCheckTypeEnumToProto(e *compute.HealthCheckTypeEnum) computepb.ComputeHealthCheckTypeEnum { if e == nil { return computepb.ComputeHealthCheckTypeEnum(0) } if v, ok := computepb.ComputeHealthCheckTypeEnum_value["HealthCheckTypeEnum"+string(*e)]; ok { return computepb.ComputeHealthCheckTypeEnum(v) } return computepb.ComputeHealthCheckTypeEnum(0) } // HealthCheckHttp2HealthCheckToProto converts a HealthCheckHttp2HealthCheck resource to its proto representation. func ComputeHealthCheckHttp2HealthCheckToProto(o *compute.HealthCheckHttp2HealthCheck) *computepb.ComputeHealthCheckHttp2HealthCheck { if o == nil { return nil } p := &computepb.ComputeHealthCheckHttp2HealthCheck{ Port: dcl.ValueOrEmptyInt64(o.Port), PortName: dcl.ValueOrEmptyString(o.PortName), PortSpecification: ComputeHealthCheckHttp2HealthCheckPortSpecificationEnumToProto(o.PortSpecification), Host: dcl.ValueOrEmptyString(o.Host), RequestPath: dcl.ValueOrEmptyString(o.RequestPath), ProxyHeader: ComputeHealthCheckHttp2HealthCheckProxyHeaderEnumToProto(o.ProxyHeader), Response: dcl.ValueOrEmptyString(o.Response), } return p } // HealthCheckHttpHealthCheckToProto converts a HealthCheckHttpHealthCheck resource to its proto representation. func ComputeHealthCheckHttpHealthCheckToProto(o *compute.HealthCheckHttpHealthCheck) *computepb.ComputeHealthCheckHttpHealthCheck { if o == nil { return nil } p := &computepb.ComputeHealthCheckHttpHealthCheck{ Port: dcl.ValueOrEmptyInt64(o.Port), PortName: dcl.ValueOrEmptyString(o.PortName), PortSpecification: ComputeHealthCheckHttpHealthCheckPortSpecificationEnumToProto(o.PortSpecification), Host: dcl.ValueOrEmptyString(o.Host), RequestPath: dcl.ValueOrEmptyString(o.RequestPath), ProxyHeader: ComputeHealthCheckHttpHealthCheckProxyHeaderEnumToProto(o.ProxyHeader), Response: dcl.ValueOrEmptyString(o.Response), } return p } // HealthCheckHttpsHealthCheckToProto converts a HealthCheckHttpsHealthCheck resource to its proto representation. func ComputeHealthCheckHttpsHealthCheckToProto(o *compute.HealthCheckHttpsHealthCheck) *computepb.ComputeHealthCheckHttpsHealthCheck { if o == nil { return nil } p := &computepb.ComputeHealthCheckHttpsHealthCheck{ Port: dcl.ValueOrEmptyInt64(o.Port), PortName: dcl.ValueOrEmptyString(o.PortName), PortSpecification: ComputeHealthCheckHttpsHealthCheckPortSpecificationEnumToProto(o.PortSpecification), Host: dcl.ValueOrEmptyString(o.Host), RequestPath: dcl.ValueOrEmptyString(o.RequestPath), ProxyHeader: ComputeHealthCheckHttpsHealthCheckProxyHeaderEnumToProto(o.ProxyHeader), Response: dcl.ValueOrEmptyString(o.Response), } return p } // HealthCheckSslHealthCheckToProto converts a HealthCheckSslHealthCheck resource to its proto representation. func ComputeHealthCheckSslHealthCheckToProto(o *compute.HealthCheckSslHealthCheck) *computepb.ComputeHealthCheckSslHealthCheck { if o == nil { return nil } p := &computepb.ComputeHealthCheckSslHealthCheck{ Port: dcl.ValueOrEmptyInt64(o.Port), PortName: dcl.ValueOrEmptyString(o.PortName), PortSpecification: ComputeHealthCheckSslHealthCheckPortSpecificationEnumToProto(o.PortSpecification), Request: dcl.ValueOrEmptyString(o.Request), Response: dcl.ValueOrEmptyString(o.Response), ProxyHeader: ComputeHealthCheckSslHealthCheckProxyHeaderEnumToProto(o.ProxyHeader), } return p } // HealthCheckTcpHealthCheckToProto converts a HealthCheckTcpHealthCheck resource to its proto representation. func ComputeHealthCheckTcpHealthCheckToProto(o *compute.HealthCheckTcpHealthCheck) *computepb.ComputeHealthCheckTcpHealthCheck { if o == nil { return nil } p := &computepb.ComputeHealthCheckTcpHealthCheck{ Port: dcl.ValueOrEmptyInt64(o.Port), PortName: dcl.ValueOrEmptyString(o.PortName), PortSpecification: ComputeHealthCheckTcpHealthCheckPortSpecificationEnumToProto(o.PortSpecification), Request: dcl.ValueOrEmptyString(o.Request), Response: dcl.ValueOrEmptyString(o.Response), ProxyHeader: ComputeHealthCheckTcpHealthCheckProxyHeaderEnumToProto(o.ProxyHeader), } return p } // HealthCheckToProto converts a HealthCheck resource to its proto representation. func HealthCheckToProto(resource *compute.HealthCheck) *computepb.ComputeHealthCheck { p := &computepb.ComputeHealthCheck{ CheckIntervalSec: dcl.ValueOrEmptyInt64(resource.CheckIntervalSec), Description: dcl.ValueOrEmptyString(resource.Description), HealthyThreshold: dcl.ValueOrEmptyInt64(resource.HealthyThreshold), Http2HealthCheck: ComputeHealthCheckHttp2HealthCheckToProto(resource.Http2HealthCheck), HttpHealthCheck: ComputeHealthCheckHttpHealthCheckToProto(resource.HttpHealthCheck), HttpsHealthCheck: ComputeHealthCheckHttpsHealthCheckToProto(resource.HttpsHealthCheck), Name: dcl.ValueOrEmptyString(resource.Name), SslHealthCheck: ComputeHealthCheckSslHealthCheckToProto(resource.SslHealthCheck), TcpHealthCheck: ComputeHealthCheckTcpHealthCheckToProto(resource.TcpHealthCheck), Type: ComputeHealthCheckTypeEnumToProto(resource.Type), UnhealthyThreshold: dcl.ValueOrEmptyInt64(resource.UnhealthyThreshold), TimeoutSec: dcl.ValueOrEmptyInt64(resource.TimeoutSec), Region: dcl.ValueOrEmptyString(resource.Region), Project: dcl.ValueOrEmptyString(resource.Project), SelfLink: dcl.ValueOrEmptyString(resource.SelfLink), Location: dcl.ValueOrEmptyString(resource.Location), } return p } // ApplyHealthCheck handles the gRPC request by passing it to the underlying HealthCheck Apply() method. func (s *HealthCheckServer) applyHealthCheck(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeHealthCheckRequest) (*computepb.ComputeHealthCheck, error) { p := ProtoToHealthCheck(request.GetResource()) res, err := c.ApplyHealthCheck(ctx, p) if err != nil { return nil, err } r := HealthCheckToProto(res) return r, nil } // ApplyHealthCheck handles the gRPC request by passing it to the underlying HealthCheck Apply() method. func (s *HealthCheckServer) ApplyComputeHealthCheck(ctx context.Context, request *computepb.ApplyComputeHealthCheckRequest) (*computepb.ComputeHealthCheck, error) { cl, err := createConfigHealthCheck(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return s.applyHealthCheck(ctx, cl, request) } // DeleteHealthCheck handles the gRPC request by passing it to the underlying HealthCheck Delete() method. func (s *HealthCheckServer) DeleteComputeHealthCheck(ctx context.Context, request *computepb.DeleteComputeHealthCheckRequest) (*emptypb.Empty, error) { cl, err := createConfigHealthCheck(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteHealthCheck(ctx, ProtoToHealthCheck(request.GetResource())) } // ListComputeHealthCheck handles the gRPC request by passing it to the underlying HealthCheckList() method. func (s *HealthCheckServer) ListComputeHealthCheck(ctx context.Context, request *computepb.ListComputeHealthCheckRequest) (*computepb.ListComputeHealthCheckResponse, error) { cl, err := createConfigHealthCheck(ctx, request.ServiceAccountFile) if err != nil { return nil, err } resources, err := cl.ListHealthCheck(ctx, request.Project, request.Location) if err != nil { return nil, err } var protos []*computepb.ComputeHealthCheck for _, r := range resources.Items { rp := HealthCheckToProto(r) protos = append(protos, rp) } return &computepb.ListComputeHealthCheckResponse{Items: protos}, nil } func createConfigHealthCheck(ctx context.Context, service_account_file string) (*compute.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return compute.NewClient(conf), nil }
package sqldb import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/labels" "upper.io/db.v3" ) func Test_labelsClause(t *testing.T) { tests := []struct { name string dbType dbType requirements labels.Requirements want db.Compound }{ {"Empty", Postgres, requirements(""), db.And()}, {"DoesNotExist", Postgres, requirements("!foo"), db.And(db.Raw("not exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo')"))}, {"Equals", Postgres, requirements("foo=bar"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and value = 'bar')"))}, {"DoubleEquals", Postgres, requirements("foo==bar"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and value = 'bar')"))}, {"In", Postgres, requirements("foo in (bar,baz)"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and value in ('bar', 'baz'))"))}, {"NotEquals", Postgres, requirements("foo != bar"), db.And(db.Raw("not exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and value = 'bar')"))}, {"NotIn", Postgres, requirements("foo notin (bar,baz)"), db.And(db.Raw("not exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and value in ('bar', 'baz'))"))}, {"Exists", Postgres, requirements("foo"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo')"))}, {"GreaterThanPostgres", Postgres, requirements("foo>2"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and cast(value as int) > 2)"))}, {"GreaterThanMySQL", MySQL, requirements("foo>2"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and cast(value as signed) > 2)"))}, {"LessThanPostgres", Postgres, requirements("foo<2"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and cast(value as int) < 2)"))}, {"LessThanMySQL", MySQL, requirements("foo<2"), db.And(db.Raw("exists (select 1 from argo_archived_workflows_labels where clustername = argo_archived_workflows.clustername and uid = argo_archived_workflows.uid and name = 'foo' and cast(value as signed) < 2)"))}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := labelsClause(tt.dbType, tt.requirements) if assert.NoError(t, err) { assert.Equal(t, tt.want.Sentences(), got.Sentences()) } }) } } func requirements(selector string) []labels.Requirement { requirements, err := labels.ParseToRequirements(selector) if err != nil { panic(err) } return requirements }
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package wasmproc // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ type ScMaps struct { ScSandboxObject } func NewScMaps(vm *wasmProcessor) *ScMaps { a := &ScMaps{} a.vm = vm return a } func (a *ScMaps) GetObjectId(keyId int32, typeId int32) int32 { return GetArrayObjectId(a, keyId, typeId, func() WaspObject { return NewScDict(a.vm) }) }
package main import ( "fmt" "time" ) func main() { var anoNasc int currentYear := time.Now().Year() fmt.Scan(&anoNasc) currentAge := currentYear - anoNasc fmt.Println(currentAge) }
package store import ( "github.com/siddontang/ledisdb/store/driver" ) type Snapshot struct { driver.ISnapshot st *Stat } func (s *Snapshot) NewIterator() *Iterator { it := new(Iterator) it.it = s.ISnapshot.NewIterator() it.st = s.st s.st.IterNum.Add(1) return it } func (s *Snapshot) Get(key []byte) ([]byte, error) { v, err := s.ISnapshot.Get(key) s.st.statGet(v, err) return v, err } func (s *Snapshot) Close() { s.st.SnapshotCloseNum.Add(1) s.ISnapshot.Close() }
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00600102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.006.001.02 Document"` Message *MeetingInstructionStatusV02 `xml:"MtgInstrSts"` } func (d *Document00600102) AddMessage() *MeetingInstructionStatusV02 { d.Message = new(MeetingInstructionStatusV02) return d.Message } // Scope // The Receiver of the MeetingInstruction or MeetingInstructionCancellationRequest sends the MeetingInstructionStatus message to the Sender of these messages. // The message gives the status of a complete message or of one or more specific instructions within the message. // Usage // The MeetingInstructionStatus message is used for four purposes. // First, it provides the status on the processing of a MeetingInstructionCancellationRequest message, ie, whether the request message is rejected or accepted. // Second, it is used to provide a global processing or rejection status of a MeetingInstruction message. // Third, it is used to provide a detailed processing or rejection status of a MeetingInstruction message, ie, for each instruction in the MeetingInstruction message the processing or rejection status is individually reported by using the InstructionIdentification element. This identification allows the receiver of the status message to link the status confirmation to its original instruction. // The blocking of securities should be confirmed via an MT 508 (Intra-Position Advice). // Fourth, it is used as a reminder to request voting instructions. This is done by indicating NONREF in the Identification element of the InstructionIdentification component and by using the status code NotReceived in the ProcessingStatus. type MeetingInstructionStatusV02 struct { // Identifies the meeting instruction status message. MeetingInstructionStatusIdentification *iso20022.MessageIdentification1 `xml:"MtgInstrStsId"` // Identifies the meeting instruction message for which the status is provided. InstructionIdentification *iso20022.MessageIdentification `xml:"InstrId"` // Identifies the meeting instruction cancellation request message for which the status is provided. InstructionCancellationIdentification *iso20022.MessageIdentification `xml:"InstrCxlId"` // Series of elements which allow to identify a meeting. MeetingReference *iso20022.MeetingReference3 `xml:"MtgRef"` // Party reporting the status. ReportingParty *iso20022.PartyIdentification9Choice `xml:"RptgPty"` // Identifies the securities for which the meeting is organised. SecurityIdentification *iso20022.SecurityIdentification3 `xml:"SctyId"` // Status applying to the instruction request received. The instruction is identified by the InstructionIdentification. InstructionStatus *iso20022.InstructionStatus1Choice `xml:"InstrSts"` // Status applying to the instruction cancellation request received. The instruction cancellation is identified by the InstructionCancellationIdentification. CancellationStatus *iso20022.CancellationStatus1Choice `xml:"CxlSts"` } func (m *MeetingInstructionStatusV02) AddMeetingInstructionStatusIdentification() *iso20022.MessageIdentification1 { m.MeetingInstructionStatusIdentification = new(iso20022.MessageIdentification1) return m.MeetingInstructionStatusIdentification } func (m *MeetingInstructionStatusV02) AddInstructionIdentification() *iso20022.MessageIdentification { m.InstructionIdentification = new(iso20022.MessageIdentification) return m.InstructionIdentification } func (m *MeetingInstructionStatusV02) AddInstructionCancellationIdentification() *iso20022.MessageIdentification { m.InstructionCancellationIdentification = new(iso20022.MessageIdentification) return m.InstructionCancellationIdentification } func (m *MeetingInstructionStatusV02) AddMeetingReference() *iso20022.MeetingReference3 { m.MeetingReference = new(iso20022.MeetingReference3) return m.MeetingReference } func (m *MeetingInstructionStatusV02) AddReportingParty() *iso20022.PartyIdentification9Choice { m.ReportingParty = new(iso20022.PartyIdentification9Choice) return m.ReportingParty } func (m *MeetingInstructionStatusV02) AddSecurityIdentification() *iso20022.SecurityIdentification3 { m.SecurityIdentification = new(iso20022.SecurityIdentification3) return m.SecurityIdentification } func (m *MeetingInstructionStatusV02) AddInstructionStatus() *iso20022.InstructionStatus1Choice { m.InstructionStatus = new(iso20022.InstructionStatus1Choice) return m.InstructionStatus } func (m *MeetingInstructionStatusV02) AddCancellationStatus() *iso20022.CancellationStatus1Choice { m.CancellationStatus = new(iso20022.CancellationStatus1Choice) return m.CancellationStatus }
package main import ( "github.com/jsagl/go-from-scratch/http_server" "github.com/jsagl/go-from-scratch/storage" "github.com/jsagl/go-from-scratch/usecase" "go.uber.org/zap" ) func main() { l, _ := zap.NewDevelopment() defer l.Sync() logger := l.Sugar() logger.Infow("Starting application...") logger.Infow("Opening connection to postgres database...") connection, err := storage.NewPostgresConnection() if err != nil { logger.Panicw("Connection to postgres database failed", "error", err,) } logger.Infow("Postgres recipe store initializing...") recipeStore := storage.NewPostgresRecipeStore(connection) logger.Infow("Setting Recipe usecase...") recipeUseCase := usecase.NewRecipeUseCase(recipeStore) http_server.NewHTTPServer(logger, recipeUseCase) }
package main import ( "fmt" "log" "net/http" "os" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter8/middleware" ) func main() { // We apply from bottom up h := middleware.ApplyMiddleware( middleware.Handler, middleware.Logger(log.New(os.Stdout, "", 0)), middleware.SetID(100), ) http.HandleFunc("/", h) fmt.Println("Listening on port :3333") err := http.ListenAndServe(":3333", nil) panic(err) }
package security import ( "fmt" ) func connectorTask(am AccessManager) func(session Session, message map[string]interface{}) error { return func(session Session, message map[string]interface{}) error { scheduledconnector := message["scheduledconnector"].(string) connector, err := am.GetScheduledConnector(scheduledconnector, session) if err != nil { am.Error(session, `connector`, "Task(%s): error looking up scheduled connector: %s", message["type"].(string), err) fmt.Printf("Task(%s): error looking up scheduled connector: %s\n", message["type"].(string), err) return nil } if connector == nil { am.Error(session, `connector`, "Task(%s): connector not found. Uuid: %s Site: %s", message["type"].(string), scheduledconnector, session.Site()) fmt.Printf("Task(%s): connector not found. Uuid: %s Site: %s\n", message["type"].(string), scheduledconnector, session.Site()) return nil } found := am.GetConnectorInfoByLabel(connector.Label) if found != nil { if found.Run == nil { am.Error(session, `connector`, "Task(%s): failed: no run function for %s", message["type"].(string), connector.Label) return nil } err := found.Run(am, connector, session) if err != nil { fmt.Printf("Task(%s) failed. %s\n", message["type"].(string), err) am.Error(session, `connector`, "Task(%s) failed", message["type"].(string), err) return nil } am.Debug(session, `connector`, "Task(%s) success", message["type"].(string)) return nil } else { fmt.Printf("Task(%s): Scheduled connector contains unknown connector type label: %s", message["type"].(string), connector.Label) am.Error(session, `connector`, "Task(%s): Scheduled connector contains unknown connector type label: %s", message["type"].(string), connector.Label) return nil } } }
package dcmdata import ( "github.com/grayzone/godcm/ofstd" "testing" ) func TestNewDcmDataset(t *testing.T) { cases := []struct { want *DcmDataset }{ {&DcmDataset{DcmItem: *NewDcmItem(DCM_ItemTag, DCM_UndefinedLength), OriginalXfer: EXS_Unknown, CurrentXfer: EXS_LittleEndianExplicit}}, } for _, c := range cases { got := NewDcmDataset() if *got != *c.want { t.Errorf("NewDcmDataset() == want %v got %v", c.want, got) } } } func TestDcdatsetLoadFile(t *testing.T) { cases := []struct { in_0 DcmDataset in_1 string in_2 E_TransferSyntax in_3 E_GrpLenEncoding in_4 uint32 want ofstd.OFCondition }{ {DcmDataset{}, "", EXS_Unknown, EGL_noChange, DCM_MaxReadLength, ofstd.EC_InvalidFilename}, } for _, c := range cases { got := c.in_0.LoadFile(c.in_1, c.in_2, c.in_3, c.in_4) if got != c.want { t.Errorf("LoadFile() == want %v got %v", c.want, got) } } }
package httpapi import ( "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestWithStatsHandler(t *testing.T) { var api HTTP WithStatsHandler("/metrics", http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))(&api) assert.NotEmpty(t, api.statsEndpoint) assert.NotNil(t, api.statsHandler) }
package period import ( "reflect" "testing" "time" "github.com/steotia/go-analytics-crypto-api/marketdata" "github.com/stretchr/testify/assert" ) func TestNew(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") t2, _ := time.Parse( time.RFC3339, "2012-11-01T22:18:41+00:00") period := NewBlankPeriod(t1, t2) expected := PeriodSlot{ From: time.Time{}, To: time.Time{}, MarketDataPairsMap: map[string]*MarketDataPair{}, } if reflect.DeepEqual(*period, expected) { t.Errorf("expected '%v' but got '%v'", expected, *period) } } func TestValidatePeriodGeneratorForInvalidInputs(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute ps, err := NewBlankPeriodsBetween(t1, t1, gap) assert.NotNil(t, err) ps, err = NewBlankPeriodsBetween(t1.Add(gap), t1, gap) assert.NotNil(t, err) ps, err = NewBlankPeriodsBetween(t1, t1.Add(gap), gap) assert.Nil(t, err) assert.NotNil(t, ps) } func TestPeriodGeneratorWithLargeGap(t *testing.T) { largegap := time.Duration(5) * time.Minute lessgap := time.Duration(4) * time.Minute t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") t2 := t1.Add(lessgap) ps, err := NewBlankPeriodsBetween(t1, t2, largegap) assert.Nil(t, err) assert.Len(t, ps.PeriodSlots, 1) expected := NewBlankPeriod(t1, t2) assert.Equal(t, expected, ps.PeriodSlots[0]) } func TestPeriodGeneratorWithExactGap(t *testing.T) { gap := time.Duration(5) * time.Minute t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") t2 := t1.Add(gap) ps, err := NewBlankPeriodsBetween(t1, t2, gap) assert.Nil(t, err) assert.Len(t, ps.PeriodSlots, 1) expected := NewBlankPeriod(t1, t2) assert.Equal(t, expected, ps.PeriodSlots[0]) } func TestPeriodGeneratorWithSmallGap(t *testing.T) { // var buf bytes.Buffer // log.SetOutput(&buf) // defer func() { // log.SetOutput(os.Stderr) // }() largegap := time.Duration(9) * time.Minute lessgap := time.Duration(4) * time.Minute t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") t2 := t1.Add(largegap) ps, err := NewBlankPeriodsBetween(t1, t2, lessgap) assert.Nil(t, err) assert.Len(t, ps.PeriodSlots, 3) x1 := t1.Add(lessgap) x2 := x1.Add(lessgap) e1 := NewBlankPeriod(t1, x1) e2 := NewBlankPeriod(x1, x2) e3 := NewBlankPeriod(x2, t2) assert.Equal(t, *e1, *ps.PeriodSlots[0]) assert.Equal(t, *e2, *ps.PeriodSlots[1]) assert.Equal(t, *e3, *ps.PeriodSlots[2]) // t.Log(buf.String()) } func TestPeriodSlotPopulateWithMarketDataOutsidePeriod(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute t2 := t1.Add(gap) periods, _ := NewBlankPeriodsBetween(t1, t2, gap) mData := marketdata.MarketData{ High: 1, Timestamp: time.Time{}, } slot := periods.PeriodSlots[0] val, ok := slot.MarketDataPairsMap[mData.MarketName] assert.False(t, ok) periods.SetMarketData(mData) val, ok = slot.MarketDataPairsMap[mData.MarketName] assert.True(t, ok) assert.Equal(t, marketdata.MarketData{}, val.Left) assert.Equal(t, marketdata.MarketData{}, val.Right) } func TestPeriodSlotPopulateWithMarketDataExactPeriod(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute t2 := t1.Add(gap) periods, _ := NewBlankPeriodsBetween(t1, t2, gap) mData := marketdata.MarketData{ High: 1, Timestamp: time.Time{}, } slot := periods.PeriodSlots[0] mData.Timestamp = t1 periods.SetMarketData(mData) val, _ := slot.MarketDataPairsMap[mData.MarketName] assert.Equal(t, mData, val.Left) assert.Equal(t, marketdata.MarketData{}, val.Right) mData2 := marketdata.MarketData{ High: 2, Timestamp: t2, } periods.SetMarketData(mData2) assert.Equal(t, mData, val.Left) assert.Equal(t, mData2, val.Right) // assert.False(t, set) // assert.Empty(t, period.MarketDataPairs) } func TestPeriodSlotPopulateWithMarketDataInBetweenPeriod(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute lessthangap := time.Duration(3) * time.Minute t2 := t1.Add(gap) periods, _ := NewBlankPeriodsBetween(t1, t2, gap) slot := periods.PeriodSlots[0] mData := marketdata.MarketData{ High: 1, Timestamp: t1.Add(lessthangap), } periods.SetMarketData(mData) val, _ := slot.MarketDataPairsMap[mData.MarketName] assert.Equal(t, marketdata.MarketData{}, val.Left) assert.Equal(t, mData, val.Right) } func TestPeriodsNeighbouringSlotWithMarketData(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute sometime := time.Duration(13) * time.Minute t2 := t1.Add(5 * gap) periods, _ := NewBlankPeriodsBetween(t1, t2, gap) mData := marketdata.MarketData{ High: 1, Timestamp: t1.Add(sometime), } periods.SetMarketData(mData) prevslot := periods.PeriodSlots[1] slot := periods.PeriodSlots[2] nextslot := periods.PeriodSlots[3] nextnextslot := periods.PeriodSlots[4] prevval, _ := prevslot.MarketDataPairsMap[mData.MarketName] val, _ := slot.MarketDataPairsMap[mData.MarketName] nextval, _ := nextslot.MarketDataPairsMap[mData.MarketName] nextnextval, _ := nextnextslot.MarketDataPairsMap[mData.MarketName] assert.Equal(t, marketdata.MarketData{}, prevval.Left) assert.Equal(t, marketdata.MarketData{}, prevval.Right) assert.Equal(t, marketdata.MarketData{}, val.Left) assert.Equal(t, mData, val.Right) assert.Equal(t, mData, nextval.Left) assert.Equal(t, marketdata.MarketData{}, nextval.Right) assert.Equal(t, marketdata.MarketData{}, nextnextval.Left) assert.Equal(t, marketdata.MarketData{}, nextnextval.Right) } func TestPeriodsStabilityWithUnorderedUpdate(t *testing.T) { t1, _ := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") gap := time.Duration(5) * time.Minute sometime := time.Duration(13) * time.Minute beforesometime := time.Duration(12) * time.Minute t2 := t1.Add(5 * gap) periods, _ := NewBlankPeriodsBetween(t1, t2, gap) mData := marketdata.MarketData{ High: 1, Timestamp: t1.Add(sometime), } beforemData := marketdata.MarketData{ High: 2, Timestamp: t1.Add(beforesometime), } periods.SetMarketData(mData) periods.SetMarketData(beforemData) slot := periods.PeriodSlots[2] val, _ := slot.MarketDataPairsMap[mData.MarketName] assert.Equal(t, marketdata.MarketData{}, val.Left) assert.Equal(t, mData, val.Right) }
package main import ( "net" "bufio" "os" "fmt" "strings" ) func main() { client, _ := net.Dial("tcp", ":50000") inputReader := bufio.NewReader(os.Stdin) fmt.Println("please input user name") userName, _ := inputReader.ReadString('\n') userName = strings.Trim(userName, "\n") for { fmt.Println("what do you want to say?") content, _ := inputReader.ReadString('\n') if content == "quit\n" { client.Close() return } client.Write([]byte(userName + " says " + content)) } }
package main //给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。 // //说明:不要使用任何内置的库函数,如  sqrt。 // //示例 1: // //输入:16 //输出:True //示例 2: // //输入:14 //输出:False func main() { } // 简单二分 func isPerfectSquare(num int) bool { l, r := 0, num/2 for l <= r { mid := l + (r-l)>>1 if mid*mid == num { return true } else if mid*mid < num { l = mid + 1 } else { r = mid - 1 } } return (l * l) == num }
package main import ( "github.com/edaniels/golinters/errresp" "golang.org/x/tools/go/analysis/singlechecker" ) func main() { singlechecker.Main(errresp.Analyzer) }
package main import ( "fmt" "testing" ) func Test_isHappy(t *testing.T) { tts := []struct { input int expected bool }{ //{19, true}, {1221, true}, } for _, tt := range tts { tt := tt t.Run(fmt.Sprintf("input: %d", tt.input), func(t *testing.T) { t.Parallel() actual := isHappy(tt.input) if tt.expected != actual { t.Errorf("expected: %v <=> actual: %v", tt.expected, actual) } }) } }
// Package operator makes api calls to Reddit. package operator import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" "github.com/turnage/graw/internal/operator/internal/client" "github.com/turnage/redditproto" ) const ( // MaxLinks is the amount of posts reddit will return for a scrape // query. MaxLinks = 100 // deletedAuthor is the author value if a post or comment was deleted. deletedAuthor = "[deleted]" ) var ( // formEncoding is the encoding format of parameters in the body of // requests sent to Reddit. formEncoding = map[string][]string{ "content-type": {"application/x-www-form-urlencoded"}, } // domain is the domain Reddit lives on. domain = "reddit.com" // oauth2Host is the hostname of Reddit's OAuth2 server. oauth2Host = "oauth." + domain // baseURL is the url all requests extend from. baseURL = "https://" + oauth2Host ) // SetTestDomain is a test hook for end to end tests to specify an alternate, // test instance of Reddit to run against. func SetTestDomain(domain string) { oauth2Host = "oauth." + domain baseURL = "https://" + domain client.TokenURL = "https://" + "www." + domain + "/api/v1/access_token" client.TestMode = true } // Operator makes api calls to Reddit. type Operator interface { // Scrape returns the contents of a listing endpoint. Scrape(path, after, before string, limit uint) ([]*redditproto.Link, []*redditproto.Comment, []*redditproto.Message, error) // IsThereThing fetches a particular thing from reddit. IsThereThing // returns whether there is such a thing. IsThereThing(id string) (bool, error) // Thread fetches a post and its comment tree. Thread(permalink string) (*redditproto.Link, error) // Inbox fetches unread messages from the reddit inbox. Inbox() ([]*redditproto.Message, error) // MarkAsRead marks inbox items read. MarkAsRead() error // Reply replies to reddit item. Reply(parent, content string) error // Compose sends a private message to a user. Compose(user, subject, content string) error // Submit posts to Reddit. Submit(subreddit, kind, title, content string) error // GetInfo retrieves info about a link GetInfo(id string) (*redditproto.Link, error) } // operator implements Operator. type operator struct { cli client.Client } // New returns a new operator which uses agent as its identity. agent should be // a filename of a file containing a UserAgent protobuffer. func New(agent string) (Operator, error) { cli, err := client.New(agent) if err != nil { return nil, err } return &operator{cli: cli}, nil } // Scrape returns slices with the content of a listing endpoint. func (o *operator) Scrape( path, after, before string, limit uint, ) ( []*redditproto.Link, []*redditproto.Comment, []*redditproto.Message, error, ) { fmt.Printf("In scrape: limit %d, after %s, before %s, path %s\n", limit, after, before, path) // do a sleep to avoid throttling time.Sleep(5 * time.Second) bytes, err := o.exec( http.Request{ Method: "GET", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: path, RawQuery: listingParams(limit, after, before), }, Host: oauth2Host, }, ) if err != nil { return nil, nil, nil, err } links, comments, messages, err := redditproto.ParseListing(bytes) fmt.Printf("In scrape returned links: %d, comments: %d, messages: %d, err: %v\n", len(links), len(comments), len(messages), err) return links, comments, messages, err } // GetInfo retrieves info about a link func (o *operator) GetInfo(id string) (*redditproto.Link, error) { path := "/api/info.json" // api/info doesn't provide message types; these need to be fetched from // a different url. bytes, err := o.exec( http.Request{ Method: "GET", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: path, RawQuery: url.Values{ "id": []string{id}, "raw_json": []string{"1"}, }.Encode(), }, Host: oauth2Host, }, ) if err != nil { return nil, err } links, _, _, err := redditproto.ParseListing(bytes) if err != nil { return nil, err } if len(links) >= 1 { return links[0], nil } return nil, nil } // IsThereThing returns whether a thing by the given id exists. func (o *operator) IsThereThing(id string) (bool, error) { path := "/api/info.json" // api/info doesn't provide message types; these need to be fetched from // a different url. if strings.HasPrefix(id, "t4_") { id := strings.TrimPrefix(id, "t4_") path = fmt.Sprintf("/message/messages/%s", id) } bytes, err := o.exec( http.Request{ Method: "GET", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: path, RawQuery: url.Values{ "id": []string{id}, "raw_json": []string{"1"}, }.Encode(), }, Host: oauth2Host, }, ) if err != nil { return false, err } links, comments, messages, err := redditproto.ParseListing(bytes) if err != nil { return false, err } if len(links) == 1 { return links[0].GetAuthor() != deletedAuthor, nil } if len(comments) == 1 { return comments[0].GetAuthor() != deletedAuthor, nil } if len(messages) == 1 { return true, nil } return false, nil } // Thread returns a link; the Comments field will be filled with the comment // tree. Browse each comment's reply tree from the ReplyTree field. func (o *operator) Thread(permalink string) (*redditproto.Link, error) { bytes, err := o.exec( http.Request{ Method: "GET", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: fmt.Sprintf("%s.json", permalink), RawQuery: "raw_json=1", }, Host: oauth2Host, }, ) if err != nil { return nil, err } return redditproto.ParseThread(bytes) } // Inbox returns unread inbox items. func (o *operator) Inbox() ([]*redditproto.Message, error) { bytes, err := o.exec( http.Request{ Method: "GET", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: "/message/unread", RawQuery: "raw_json=1", }, Host: oauth2Host, }, ) if err != nil { return nil, err } _, _, messages, err := redditproto.ParseListing(bytes) return messages, err } // MarkAsRead marks inbox items as read, so they are no longer returned by calls // to Inbox(). func (o *operator) MarkAsRead() error { req := http.Request{ Method: "POST", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: "/api/read_all_messages", }, Header: formEncoding, Body: ioutil.NopCloser(bytes.NewBufferString("")), Host: oauth2Host, } _, err := o.cli.Do(&req) return err } // Reply replies to a post, message, or comment. func (o *operator) Reply(parent, content string) error { req := http.Request{ Method: "POST", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: "/api/comment", }, Header: formEncoding, Body: ioutil.NopCloser( bytes.NewBufferString( url.Values{ "thing_id": []string{parent}, "text": []string{content}, }.Encode(), ), ), Host: oauth2Host, } _, err := o.cli.Do(&req) return err } // Compose sends a private message to a user. func (o *operator) Compose(user, subject, content string) error { req := http.Request{ Method: "POST", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: "/api/compose", }, Header: formEncoding, Body: ioutil.NopCloser( bytes.NewBufferString( url.Values{ "to": []string{user}, "subject": []string{subject}, "text": []string{content}, }.Encode(), ), ), Host: oauth2Host, } _, err := o.cli.Do(&req) return err } // Submit submits a post. func (o *operator) Submit(subreddit, kind, title, content string) error { req := http.Request{ Method: "POST", Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Close: true, URL: &url.URL{ Scheme: "https", Host: oauth2Host, Path: "/api/submit", }, Header: formEncoding, Body: ioutil.NopCloser( bytes.NewBufferString( url.Values{ "sr": []string{subreddit}, "kind": []string{kind}, "title": []string{title}, "url": []string{content}, "text": []string{content}, }.Encode(), ), ), Host: oauth2Host, } _, err := o.cli.Do(&req) return err } // exec executes a request and returns the response body bytes. func (o *operator) exec(r http.Request) ([]byte, error) { response, err := o.cli.Do(&r) if err != nil { return nil, err } return responseBytes(response) } // listingParams returns encoded values for parameters to a Reddit listing // endpoint. func listingParams(limit uint, after, before string) string { return url.Values{ "limit": []string{strconv.Itoa(int(limit))}, "before": []string{before}, "after": []string{after}, "raw_json": []string{"1"}, }.Encode() } // responseBytes returns a slice of bytes from a response body. func responseBytes(response io.ReadCloser) ([]byte, error) { var buffer bytes.Buffer if _, err := buffer.ReadFrom(response); err != nil { return nil, err } return buffer.Bytes(), nil }
package hatch import ( "errors" "flag" "fmt" "go/ast" "go/parser" "go/token" "os" "regexp" "strings" "github.com/kr/pretty" ) type Service struct { InterfaceType *ast.InterfaceType Name string NoPrefix bool Package string Version string } func Scan(file string) ([]*Service, error) { f, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ParseComments) if err != nil { return nil, err } pretty.Println(f) if f.Name == nil { return nil, errors.New("no package name") } services := []*Service{} for _, decl := range f.Decls { genDecl, ok := decl.(*ast.GenDecl) if !ok { continue } if genDecl.Doc != nil && genDecl.Doc != nil && genDecl.Doc.List != nil { for _, comment := range genDecl.Doc.List { trimmed := strings.TrimSpace(comment.Text) annotation := "//pumapotion:generate" if !strings.HasPrefix(trimmed, annotation) { continue } for _, spec := range genDecl.Specs { typeSpec, ok := spec.(*ast.TypeSpec) if !ok { continue } if typeSpec.Type != nil { interfaceType, ok := typeSpec.Type.(*ast.InterfaceType) if !ok || typeSpec.Name == nil { continue } trimmed = strings.TrimSpace(strings.TrimPrefix(trimmed, annotation)) flags := regexp.MustCompile("\\s+").Split(trimmed, -1) fs := flag.NewFlagSet("pumapotion", flag.ErrorHandling(0)) noprefix := fs.Bool("noprefix", false, "prefix") version := fs.String("version", "", "version") if err := fs.Parse(flags); err != nil { return nil, err } services = append(services, &Service{InterfaceType: interfaceType, Name: typeSpec.Name.Name, NoPrefix: *noprefix, Package: f.Name.Name, Version: *version}) } } } } } return services, nil } func GenerateFile(file, content string) error { f, err := os.Create(file) if err != nil { return err } if _, err := f.Write([]byte(content)); err != nil { return err } return f.Close() } func GenerateClient(s *Service) error { var prefix string if !s.NoPrefix { prefix = s.Name } lower := strings.ToLower(s.Name) return GenerateFile(lower+"_client.go", fmt.Sprintf(`package %s import "net/rpc" var _ %s = &%sClient{} type %sClient struct { client *rpc.Client } func New%sClient(address string) (c *%sClient, err error) { client, err := rpc.DialHTTPPath("tcp", address, "/%s") if err == nil { return &%sClient{client: client}, nil } else { return nil, err } } `, s.Package, s.Name, prefix, prefix, prefix, prefix, lower, prefix)) } func GenerateServer(s *Service) error { var prefix string if !s.NoPrefix { prefix = s.Name } lower := strings.ToLower(s.Name) return GenerateFile(lower+"_server.go", fmt.Sprintf(`package %s import ( "net" "net/http" "net/rpc" ) type %sServer struct { Listener net.Listener Service *%sService } func New%sServer(address string) (s *%sServer, err error) { %sServer := &%sServer{Service: &%sService{}} rpcServer := rpc.NewServer() rpcServer.Register(%sServer) rpcServer.HandleHTTP("/%s", "/%s/debug") if %sServer.Listener, err = net.Listen("tcp", address); err == nil { go http.Serve(%sServer.Listener, nil) return %sServer, nil } else { return nil, err } } `, s.Package, prefix, prefix, prefix, prefix, prefix, lower, prefix)) } func GenerateService(s *Service) error { if err := GenerateClient(s); err != nil { return err } return nil } func Generate() error { file := flag.String("file", "", "file") flag.Parse() if flag.NFlag() != 1 { return errors.New("missing flag") } services, err := Scan(*file) if err != nil { return err } names := map[string]struct{}{} for _, service := range services { if _, ok := names[service.Name]; ok { return errors.New("duplicate service name: " + service.Name) } } for _, service := range services { if err := GenerateService(service); err != nil { return err } } return nil }
package config import ( "fmt" "github.com/spf13/viper" ) type Config struct { MysqlAdmin MySQL `json:"mysqlAdmin"` RedisAdmin Redis `json:"redisAdmin"` JWT JWT `json:"jwt"` Casbin Casbin `json:"casbin"` Logs Logs `json:"logs"` } type MySQL struct { Username string `json:"username"` Password string `json:"password"` Path string `json:"path"` DBName string `json:"dbname"` Config string `json:"config"` } type Redis struct { Path string `json:"path"` Password string `json:"password"` } type JWT struct { SigningKey string `mapstructure:"signing-key" json:"signingKey" yaml:"signing-key"` } type Casbin struct { ModelPath string `json:"modelPath"` } type Logs struct { Path string `json:"path"` Name string `json:"name"` } var AdminConfig Config var VTool *viper.Viper func init() { v := viper.New() v.SetConfigName("settings") v.AddConfigPath("./config/") v.SetConfigType("yaml") err := v.ReadInConfig() if err != nil { panic(fmt.Errorf("配置文件读取错误: %s \n", err)) } if err := v.Unmarshal(&AdminConfig); err != nil { fmt.Println(err) } VTool = v }
// Copyright 2018 The OpenSDS Authors. // // 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 connector import ( "fmt" "log" "net" "os/exec" "strings" ) // ExecCmd Log and convert the result of exec.Command func ExecCmd(name string, arg ...string) (string, error) { log.Printf("Command: %s %s:\n", name, strings.Join(arg, " ")) info, err := exec.Command(name, arg...).CombinedOutput() return string(info), err } // GetFSType returns the File System Type of device func GetFSType(device string) (string, error) { log.Printf("GetFSType: %s\n", device) var fsType string blkidCmd := "blkid" out, err := ExecCmd("blkid", device) if err != nil { log.Printf("failed to GetFSType: %v cmd: %s output: %s\n", err, blkidCmd, string(out)) return fsType, nil } for _, v := range strings.Split(string(out), " ") { if strings.Contains(v, "TYPE=") { fsType = strings.Split(v, "=")[1] fsType = strings.Replace(fsType, "\"", "", -1) fsType = strings.Replace(fsType, "\n", "", -1) fsType = strings.Replace(fsType, "\r", "", -1) return fsType, nil } } return fsType, nil } // Format device by File System Type func Format(device string, fsType string) error { log.Printf("Format device: %s fstype: %s\n", device, fsType) mkfsCmd := fmt.Sprintf("mkfs.%s", fsType) _, err := exec.LookPath(mkfsCmd) if err != nil { if err == exec.ErrNotFound { return fmt.Errorf("%q executable not found in $PATH", mkfsCmd) } return err } mkfsArgs := []string{} mkfsArgs = append(mkfsArgs, device) if fsType == "ext4" || fsType == "ext3" { mkfsArgs = []string{"-F", device} } out, err := ExecCmd(mkfsCmd, mkfsArgs...) if err != nil { return fmt.Errorf("formatting disk failed: %v cmd: '%s %s' output: %q", err, mkfsCmd, strings.Join(mkfsArgs, " "), string(out)) } return nil } // Mount device into mount point func Mount(device, mountpoint, fsType string, mountFlags []string) error { log.Printf("Mount device: %s mountpoint: %s, fsType: %s, mountFlags: %v\n", device, mountpoint, fsType, mountFlags) _, err := ExecCmd("mkdir", "-p", mountpoint) if err != nil { log.Printf("failed to mkdir: %v\n", err) return err } mountArgs := []string{} mountArgs = append(mountArgs, "-t", fsType) if len(mountFlags) > 0 { mountArgs = append(mountArgs, "-o", strings.Join(mountFlags, ",")) } mountArgs = append(mountArgs, device) mountArgs = append(mountArgs, mountpoint) _, err = exec.Command("mount", mountArgs...).CombinedOutput() if err != nil { log.Printf("failed to mount: %v\n", err) return err } return nil } // Umount from mountpoint func Umount(mountpoint string) error { log.Printf("Umount mountpoint: %s\n", mountpoint) _, err := ExecCmd("umount", mountpoint) if err != nil { log.Printf("failed to Umount: %v\n", err) return err } return nil } // GetHostIP return Host IP func GetHostIP() string { addrs, err := net.InterfaceAddrs() if err != nil { return "127.0.0.1" } for _, address := range addrs { if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { return ipnet.IP.String() } } return "127.0.0.1" } // GetHostName ... func GetHostName() (string, error) { hostName, err := ExecCmd("hostname") if err != nil { log.Printf("failed to get host name: %v\n", err) return "", err } hostName = strings.Replace(hostName, "\n", "", -1) return hostName, nil } // IsMounted ... func IsMounted(target string) (bool, error) { findmntCmd := "findmnt" _, err := exec.LookPath(findmntCmd) if err != nil { if err == exec.ErrNotFound { msg := fmt.Sprintf("%s executable not found in $PATH, err: %v\n", findmntCmd, err) log.Printf(msg) return false, fmt.Errorf(msg) } log.Printf("failed to check IsMounted %v\n", err) return false, err } findmntArgs := []string{"--target", target} log.Printf("findmnt args is %s\n", findmntArgs) out, err := ExecCmd(findmntCmd, findmntArgs...) if err != nil { // findmnt exits with non zero exit status if it couldn't find anything if strings.TrimSpace(string(out)) == "" { return false, nil } errIsMounted := fmt.Errorf("checking mounted failed: %v cmd: %s output: %s", err, findmntCmd, string(out)) log.Printf("checking mounted failed: %v\n", errIsMounted) return false, errIsMounted } log.Printf("checking mounted result is %s\n", strings.TrimSpace(string(out))) if strings.TrimSpace(string(out)) == "" { return false, nil } line := strings.Split(string(out), "\n") if strings.Split(line[1], " ")[0] != target { return false, nil } return true, nil }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package flare import ( "context" "fmt" "github.com/pkg/errors" "github.com/diegobernardes/flare" "github.com/diegobernardes/flare/infra/config" memoryRepository "github.com/diegobernardes/flare/provider/memory/repository" "github.com/diegobernardes/flare/provider/mongodb" mongoDBRepository "github.com/diegobernardes/flare/provider/mongodb/repository" ) type repositorier interface { Resource() flare.ResourceRepositorier Subscription() flare.SubscriptionRepositorier Document() flare.DocumentRepositorier } type repository struct { cfg *config.Client base repositorier } func (r *repository) init() error { partition := r.cfg.GetInt("domain.resource.partition") provider := r.cfg.GetString("provider.repository") switch provider { case providerMemory: r.base = memoryRepository.NewClient( memoryRepository.ClientResourceOptions(memoryRepository.ResourcePartitionLimit(partition)), ) case providerMongoDB: repository, err := r.initMongoDB(partition) if err != nil { return errors.Wrap(err, "error during MongoDB initialization") } r.base = repository default: return fmt.Errorf("invalid provider.repository config '%s'", provider) } return nil } func (r *repository) initMongoDB(partition int) (repositorier, error) { options, err := r.initMongoDBOptions() if err != nil { return nil, err } client, err := mongodb.NewClient(options...) if err != nil { return nil, errors.Wrap(err, "error during client initialization") } repository, err := mongoDBRepository.NewClient( mongoDBRepository.ClientConnection(client), mongoDBRepository.ClientResourceOptions( mongoDBRepository.ResourcePartitionLimit(partition), ), ) if err != nil { return nil, errors.Wrap(err, "error during repository initialization") } return repository, nil } func (r *repository) initMongoDBOptions() ([]func(*mongodb.Client), error) { var options []func(*mongodb.Client) options = append(options, mongodb.ClientAddrs(r.cfg.GetStringSlice("provider.mongodb.addrs"))) options = append(options, mongodb.ClientDatabase(r.cfg.GetString("provider.mongodb.database"))) options = append(options, mongodb.ClientUsername(r.cfg.GetString("provider.mongodb.username"))) options = append(options, mongodb.ClientPassword(r.cfg.GetString("provider.mongodb.password"))) options = append(options, mongodb.ClientPoolLimit(r.cfg.GetInt("provider.mongodb.pool-limit"))) options = append(options, mongodb.ClientReplicaSet( r.cfg.GetString("provider.mongodb.replica-set")), ) timeout, err := r.cfg.GetDuration("provider.mongodb.timeout") if err != nil { return nil, errors.Wrap( err, fmt.Sprintf( "invalid provider.mongodb.timeout '%s' config, error during parse", r.cfg.GetString("provider.mongodb.timeout"), ), ) } options = append(options, mongodb.ClientTimeout(timeout)) return options, nil } func (r *repository) stop() error { type closer interface { Stop() error } group, ok := r.base.(closer) if !ok { return nil } return group.Stop() } func (r *repository) setup(ctx context.Context) error { type setup interface { Setup(context.Context) error } s, ok := r.base.(setup) if !ok { return nil } return s.Setup(ctx) }
package main import ( "fmt" "image" "image/color" "image/color/palette" "image/gif" "os" ) const ( wPriceData = 480 hPriceData = 160 ) // PriceData 价格 type PriceData struct { img *image.Paletted } // CreatePriceData ... func CreatePriceData() *PriceData { return &PriceData{img: image.NewPaletted(image.Rect(0, 0, wPriceData, hPriceData), palette.Plan9)} } //Make 价格的右上角坐标 func (p *PriceData) Make(m *image.Image, left, top int) { g := color.RGBA{0x0, 0xa8, 0x0, 0xff} r := color.RGBA{0xfc, 0x54, 0x54, 0xff} back := color.RGBA{0xff, 0xff, 0xff, 0} for x := 0; x < wPriceData; x++ { for y := 0; y < hPriceData; y++ { c := (*m).At(x+left, y+top) //p.img.Set(x, y, c) if c == g { p.img.Set(x, y, g) } else if c == r { p.img.Set(x, y, r) } else { p.img.Set(x, y, back) } } } } // Save ... func (p *PriceData) Save() { f, _ := os.Create(fmt.Sprintf("stockPriceData.gif")) defer f.Close() gif.Encode(f, p.img, nil) } func cutPriceData(m *image.Image) { p := CreatePriceData() p.Make(m, 50, 18) p.Save() }
package main import ( "fmt" "log" "net/http" ) func getHash() string { return "1234" } func handler(w http.ResponseWriter, r *http.Request) { hash := getHash() fmt.Fprintf(w, "{\"hash\": %s}", hash) log.Println("Request") }
package main import ( "flag" "fmt" "io" "log" "os" "path/filepath" "strings" ) var ( // searchPath 要找尋檔案的路徑 searchPath = flag.String("input", "", "search file dir EX: /User/xxx/ddd/....") // searchFileName 要找尋的檔案名稱 searchFileName = flag.String("file", "", "search file name") outputPath = flag.String("output", "", "output file dir") ) // 檔案路徑 var filelists []searchFile var findFile *searchFile // searchFile 搜尋的檔案結構 type searchFile struct { fileName string filePath string topPath string fileType string } func main() { flag.Parse() if flag.NFlag() != 3 { flag.PrintDefaults() } else { body() } } func body() { // 列出所輸入的參數 fmt.Println("Search Path : ", *searchPath) fmt.Println("Search File Name : ", *searchFileName) fmt.Println("Output File Path :", *outputPath) // 判斷路徑是否存在 if *searchFileName == "null" { log.Fatal("Please Input the file name") } if err := pathExist(*searchPath); err != nil { log.Fatal("Error:", err) } // 開始進入目錄路徑 if err := WalkDir(*searchPath); err != nil { fmt.Println("Not Find the Same File") } else { err := Copy(findFile) if err != nil { log.Println("Copy Failed") } else { log.Println("Copy Success") } } } // 拷貝資料到output之下 func Copy(fileinfo *searchFile) error { // 檢查Output目錄內是否存在相同目錄,如果存在則複製一份至該目錄 // 否則建立一個新目錄 outputDir := *outputPath + fileinfo.topPath if _, err := os.Stat(outputDir); err != nil { direrr := os.MkdirAll(outputDir, os.ModePerm) if direrr != nil { log.Fatal("Create Folder Failed ", direrr) } else { fmt.Println("Create Folder Success") } } // 複製檔案 srcFile, err := os.Open(fileinfo.filePath) if err != nil { fmt.Println(err) } defer srcFile.Close() outputFilePath := outputDir + fileinfo.fileName desFile, err := os.Create(outputFilePath) if err != nil { fmt.Println(err) } defer desFile.Close() _, err = io.Copy(desFile, srcFile) if err != nil { return err } return nil } // 查詢該目錄下所有的目錄與檔案 func WalkDir(path string) error { err := filepath.Walk(*searchPath, func(path string, f os.FileInfo, err error) error { // 如果取得檔案不是目錄,則紀錄 if !f.IsDir() { // 取得上層路徑 topPath := strings.TrimSuffix(strings.TrimPrefix(path, *searchPath), f.Name()) tmp := searchFile{ fileName: f.Name(), filePath: path, topPath: topPath, } filelists = append(filelists, tmp) // 如果遍歷的檔案是所要則顯示出來並且退出 if f.Name() == *searchFileName { findFile = &tmp return nil } } return nil }) return err } // 列出該目錄下所有的檔案 func CheckFile(path string) []string { return nil } // pathExist 檢查路徑是否存在 func pathExist(path string) error { _, err := os.Stat(path) if err != nil { return err } return nil }
package tools import ( "fmt" "io/ioutil" "os" ) //检查文件是否存在,输入路径返回布尔值 func CheckFileExist(path string) bool { _, err := os.Stat(path) //os.Stat获取文件信息 if err != nil { if os.IsExist(err) { return true } return false } return true } //读取文件,传入文件路径,返回文件内容 func ReadFile(path string) string { f, err := ioutil.ReadFile(path) if err != nil { fmt.Printf("%s\n", err) panic(err) } return string(f) } //写入文件,传入文件路径 func WriteFile(path string, content string) bool { err := ioutil.WriteFile(path, []byte(content), 0666) if err != nil { fmt.Printf("%s\n", err) panic(err) } return true }
package db import "sokol_proxy/models" func InsertData(tableName string, data []models.SokolM) error { for _, s := range data { err := db.Table(tableName).Where("time = ?", s.Time).FirstOrCreate(&s).Error if err != nil { return err } } return nil }
package epf import ( "reflect" "testing" "time" ) func TestRateContributionTotal0(t *testing.T) { rate := Rate{ContributionEmployer: 0.0, ContributionEmployee: 0.0} if rate.ContributionTotal() != 0.0+0.0 { t.Fail() } } func TestRateContributionTotal2400(t *testing.T) { rate := Rate{ContributionEmployer: 1300.0, ContributionEmployee: 1100.0} if rate.ContributionTotal() != 1300.0+1100.0 { t.Fail() } } func TestSectionByNameValid(t *testing.T) { name := "A" _, err := SectionByName(name) if err != nil { t.Fail() } } func TestSectionByNameInvalid(t *testing.T) { _, err := SectionByName("Invalid") if err == nil { t.Fail() } } func TestSectionARate(t *testing.T) { sec, err := SectionByName("A") if err != nil { t.Skip() } rate := sec.Rate(550.0) expected := 73.0 if rate.ContributionEmployer != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployer) } rate = sec.Rate(25000.0) expected = 3000.0 if rate.ContributionEmployer != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployer) } } func TestSectionBRate(t *testing.T) { sec, err := SectionByName("B") if err != nil { t.Skip() } rate := sec.Rate(720.0) expected := 58.0 if rate.ContributionEmployee != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployee) } } func TestSectionCRate(t *testing.T) { sec, err := SectionByName("C") if err != nil { t.Skip() } rate := sec.Rate(1050.0) expected := 43.0 if rate.ContributionEmployee != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployee) } } func TestSectionDRate(t *testing.T) { sec, err := SectionByName("D") if err != nil { t.Skip() } rate := sec.Rate(1150.0) expected := 47.0 if rate.ContributionEmployee != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployee) } } func TestEmployeeSectionJuniorMalaysian(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-30, 0, 0) emp := NewEmployeeMalaysian(age, wages) section := emp.Section() if section.Name != "A" { t.Errorf("Expecting: %v , Gotten: %v", "A", section.Name) } } func TestEmployerSectionSeniorMalaysian(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-70, 0, 0) emp := NewEmployeeMalaysian(age, wages) section := emp.Section() if section.Name != "C" { t.Errorf("Expecting: %v , Gotten: %v", "C", section.Name) } } func TestEmployerSectionJuniorNonMalaysian(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-30, 0, 0) emp := NewEmployeeNonMalaysian(false, age, wages) section := emp.Section() if section.Name != "B" { t.Errorf("Expecting: %v , Gotten: %v", "B", section.Name) } } func TestEmployerSectionSeniorNonMalaysian(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-70, 0, 0) emp := NewEmployeeNonMalaysian(false, age, wages) section := emp.Section() if section.Name != "D" { t.Errorf("Expecting: %v , Gotten: %v", "D", section.Name) } } func TestEmployeeSectionJuniorPR(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-30, 0, 0) emp := NewEmployeePermanentResident(age, wages) section := emp.Section() if section.Name != "A" { t.Errorf("Expecting: %v , Gotten: %v", "A", section.Name) } } func TestEmployeeSectionSeniorPR(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-70, 0, 0) emp := NewEmployeePermanentResident(age, wages) section := emp.Section() if section.Name != "C" { t.Errorf("Expecting: %v , Gotten: %v", "C", section.Name) } } func TestEmployeeSectionsMalaysian(t *testing.T) { emp := Employee{Citizenship: Malaysian} sections := emp.Sections() expected := []*Section{&Sections[0], &Sections[2]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeUnknown(t *testing.T) { emp := Employee{} sections := emp.Sections() expected := []*Section{&Sections[0], &Sections[1], &Sections[2], &Sections[3]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeSectionsPR(t *testing.T) { emp := Employee{Citizenship: PermanentResident} sections := emp.Sections() expected := []*Section{&Sections[0], &Sections[2]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeSectionsNonMalaysian(t *testing.T) { emp := Employee{Citizenship: NonMalaysian} sections := emp.Sections() expected := []*Section{&Sections[1], &Sections[3]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeSectionsJunior(t *testing.T) { age := time.Now().AddDate(-30, 0, 0) emp := Employee{DateOfBirth: age} sections := emp.Sections() expected := []*Section{&Sections[0], &Sections[1]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeSectionsSenior(t *testing.T) { age := time.Now().AddDate(-65, 0, 0) emp := Employee{DateOfBirth: age} sections := emp.Sections() expected := []*Section{&Sections[2], &Sections[3]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeSectionsJuniorMalaysian(t *testing.T) { wages := 1500.0 age := time.Now().AddDate(-30, 0, 0) emp := NewEmployeeMalaysian(age, wages) sections := emp.Sections() expected := []*Section{&Sections[0]} if !reflect.DeepEqual(sections, expected) { t.Logf("Expecting: %v", expected) t.Logf("Gotten: %v", sections) t.Fail() } } func TestEmployeeRate(t *testing.T) { empAge := time.Now().AddDate(-30, 0, 0) emp := NewEmployeeMalaysian(empAge, 1500.0) rate := emp.Rate() expected := 120.0 if rate.ContributionEmployee != expected { t.Errorf("Expecting: %v , Gotten: %v", expected, rate.ContributionEmployee) } }
// Created at 10/21/2021 1:25 AM // Developer: trungnq2710 (trungnq2710@gmail.com) package go_apns import ( "time" ) // TODO impl token type Notification struct { // authorization string pushType PushType apnsID string expiration time.Time priority Priority topic string collapseID string deviceToken string payload *Payload } func NewNotification() *Notification { return &Notification{ pushType: PushTypeAlert, } } // (Required for token-based authentication) The value of this header is bearer <provider_token>, // where <provider_token> is the encrypted token that authorizes you to send notifications for // the specified topic. APNs ignores this header if you use certificate-based authentication //func (n *Notification) Authorization(i string) *Notification { // n.authorization = i // return n //} // (Required for watchOS 6 and later; recommended for macOS, iOS, tvOS, and iPadOS) // The value of this header must accurately reflect the contents of your notification’s payload. // If there’s a mismatch, or if the header is missing on required systems, APNs may return an error, // delay the delivery of the notification, or drop it altogether. func (n *Notification) PushType(i PushType) *Notification { n.pushType = i return n } // A canonical UUID that is the unique ID for the notification. If an error occurs when sending // the notification, APNs includes this value when reporting the error to your server. Canonical // UUIDs are 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens in // the form 8-4-4-4-12. For example: 123e4567-e89b-12d3-a456-4266554400a0. If you omit this header, // APNs creates a UUID for you and returns it in its response. func (n *Notification) ApnsID(i string) *Notification { n.apnsID = i return n } // The date at which the notification is no longer valid. This value is a UNIX epoch expressed in // seconds (UTC). If the value is nonzero, APNs stores the notification and tries to deliver it at // least once, repeating the attempt as needed until the specified date. If the value is 0, APNs // attempts to deliver the notification only once and doesn’t store it. // // A single APNs attempt may involve retries over multiple network interfaces and connections of // the destination device. Often these retries span over some time period, depending on the network // characteristics. In addition, a push notification may take some time on the network after APNs // sends it to the device. APNs uses best efforts to honor the expiry date without any guarantee. // If the value is nonzero, the notification may be delivered after the mentioned date. If the value // is 0, the notification may be delivered with some delay. func (n *Notification) Expiration(i time.Time) *Notification { n.expiration = i return n } // The priority of the notification. If you omit this header, APNs sets the notification priority to 10. // Specify 10 to send the notification immediately. // Specify 5 to send the notification based on power considerations on the user’s device. func (n *Notification) Priority(i Priority) *Notification { n.priority = i return n } // The topic for the notification. In general, the topic is your app’s bundle ID/app ID. // It can have a suffix based on the type of push notification. If you’re using a certificate that // supports PushKit VoIP or watchOS complication notifications, you must include this header with // bundle ID of you app and if applicable, the proper suffix. If you’re using token-based authentication // with APNs, you must include this header with the correct bundle ID and suffix combination func (n *Notification) Topic(i string) *Notification { n.topic = i return n } // An identifier you use to coalesce multiple notifications into a single notification for the // user. Typically, each notification request causes a new notification to be displayed on the // user’s device. When sending the same notification more than once, use the same value in this // header to coalesce the requests. The value of this key must not exceed 64 bytes. func (n *Notification) CollapseID(i string) *Notification { n.collapseID = i return n } func (n *Notification) DeviceToken(i string) *Notification { n.deviceToken = i return n } func (n *Notification) Payload(i *Payload) *Notification { n.payload = i return n }
package integers import "fmt" func Add(x, y int) int { return x+y } func ExampleAdd() { sum := Add(1, 5) fmt.Println(sum) // Output: 6 }
package main import ( "container/list" "math" "strconv" "strings" "github.com/jraams/aoc-2020/helpers" "github.com/thoas/go-funk" ) var gameCounter = 1 func loadDecks(lines []string) (*list.List, *list.List) { d1, d2 := list.New(), list.New() loadingDeck1 := true for _, line := range lines { if strings.Contains(line, "Player") { continue } if len(line) == 0 { loadingDeck1 = false continue } intVal := helpers.MustAtoi(line) if loadingDeck1 { d1.PushBack(intVal) } else { d2.PushBack(intVal) } } return d1, d2 } // Once the game ends, you can calculate the winning player's score. The bottom card in their deck is worth the value of // the card multiplied by 1, the second-from-the-bottom card is worth the value of the card multiplied by 2, and so on. func calculateScore(deck *list.List) int { score := 0 for mult := deck.Len(); mult > 0; { val := deck.Front() score += mult * val.Value.(int) deck.Remove(val) mult-- } return score } func getDeckHash(deck *list.List) string { hash := "" for item := deck.Front(); item != nil; { hash += strconv.Itoa(item.Value.(int)) hash += "-" item = item.Next() } return hash } func copyDeck(deck *list.List) *list.List { return copyDeckUpTo(deck, math.MaxInt32) } func copyDeckUpTo(deck *list.List, maxItems int) *list.List { newDeck := new(list.List) count := 0 for item := deck.Front(); item != nil && count < maxItems; { newDeck.PushBack(item.Value) item = item.Next() count++ } return newDeck } func playSpaceCards(gameNr int, recursive bool, rounds map[int]*map[int][]string, d1 *list.List, d2 *list.List) (int, *list.List) { if !funk.Contains(rounds, gameNr) { rounds[gameNr] = &map[int][]string{} } roundNr := 1 // he game consists of a series of rounds for d1.Len() > 0 && d2.Len() > 0 { if recursive { // Before either player deals a card, if there was a previous round in this game that had exactly the same cards in // the same order in the same players' decks, the game instantly ends in a win for player 1. Previous rounds from // other games are not considered. (This prevents infinite games of Recursive Combat, which everyone agrees is a bad idea.) d1h := getDeckHash(d1) d2h := getDeckHash(d2) // Previous rounds from other games are not considered. roundMap := *rounds[gameNr] if funk.Contains(roundMap[1], d1h) || funk.Contains(roundMap[2], d2h) { return 1, d1 } } // both players draw their top card, p1e := d1.Front() p2e := d2.Front() p1i := p1e.Value.(int) p2i := p2e.Value.(int) roundMap := *rounds[gameNr] roundMap[1] = append(roundMap[1], getDeckHash(d1)) roundMap[2] = append(roundMap[2], getDeckHash(d2)) d1.Remove(p1e) d2.Remove(p2e) // the player with the higher-valued card wins the round. p1won := p1i > p2i if recursive { // If both players have at least as many cards remaining in their deck as the value of the card they just drew, // the winner of the round is determined by playing a new game of Recursive Combat if p1i <= d1.Len() && p2i <= d2.Len() { d1copy := copyDeckUpTo(d1, p1i) d2copy := copyDeckUpTo(d2, p2i) gameCounter++ winner, _ := playSpaceCards(gameCounter, true, rounds, d1copy, d2copy) p1won = winner == 1 } } // The winner keeps both cards, placing them on the bottom of their own deck so that the winner's card is above the // other card. If this causes a player to have all of the cards, they win, and the game ends. if p1won { d1.PushBack(p1i) d1.PushBack(p2i) } else { d2.PushBack(p2i) d2.PushBack(p1i) } roundNr++ } // Decide winner if d1.Len() > 0 { return 1, d1 } return 2, d2 }
package main import ( "fmt" "github.com/achakravarty/30daysofgo/day18" ) func main() { var input string fmt.Scanf("%s\n", &input) isPalindrome := day18.IsPalindrome(input) msg := fmt.Sprintf("The word, %s, is ", input) if isPalindrome { msg += "a palindrom" } else { msg += "not a palindrome" } fmt.Println(msg) }
/* If you express some positive integer in binary with no leading zeros and replace every 1 with a ( and every 0 with a ), then will all the parentheses match? In most cases they won't. For example, 9 is 1001 in binary, which becomes ())(, where only the first two parentheses match. But sometimes they will match. For example, 44 is 101100 in binary, which becomes ()(()), where all the left parentheses have a matching right parenthesis. Write a program or function that takes in a positive base ten integer and prints or returns a truthy value if the binary-parentheses version of the number has all matching parentheses. If it doesn't, print or return a falsy value. The shortest code in bytes wins. Related OEIS sequence. Truthy examples below 100: 2, 10, 12, 42, 44, 50, 52, 56 Falsy examples below 100: 1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 51, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 */ package main import "fmt" func main() { truthy := []uint{2, 10, 12, 42, 44, 50, 52, 56} falsy := []uint{1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 51, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99} for _, v := range truthy { assert(parenb(v) == true) } for _, v := range falsy { assert(parenb(v) == false) } } func assert(x bool) { if !x { panic("assertion failed") } } // https://oeis.org/A014486 func parenb(n uint) bool { s := fmt.Sprintf("%b", n) p := 0 for i := 0; i < len(s); i++ { switch { case s[i] == '1': p++ case p > 0: p-- default: return false } } return p == 0 }
package cmcpro import ( "encoding/json" "io/ioutil" "log" "net/http" "strings" "time" ) type GetLatestPricesBySymbolsResponse struct { Status struct { Timestamp time.Time `json:"timestamp,omitempty"` ErrorCode int `json:"error_code,omitempty"` ErrorMessage string `json:"error_message,omitempty"` Elapsed int `json:"elapsed,omitempty"` CreditCount int `json:"credit_count,omitempty"` Notice string `json:"notice,omitempty"` } Data map[string]struct { ID int `json:"id,omitempty"` Name string `json:"name,omitempty"` Symbol string `json:"symbol,omitempty"` Slug string `json:"slug,omitempty"` IsActive int `json:"is_active,omitempty"` IsFiat int `json:"is_fiat,omitempty"` CirculatingSupply float32 `json:"circulating_supply,omitempty"` TotalSupply float32 `json:"total_supply,omitempty"` MaxSupply float32 `json:"max_supply,omitempty"` DateAdded time.Time `json:"date_added,omitempty"` NumMarketPairs int `json:"num_market_pairs,omitempty"` CmcRank int `json:"cmc_rank,omitempty"` LastUpdated time.Time `json:"last_updated,omitempty"` Tags []string `json:"tags,omitempty"` Platform interface{} `json:"platform,omitempty"` Quote map[string]struct { Price float32 `json:"price,omitempty"` Volume24h float32 `json:"volume_24h,omitempty"` PercentChange1h float32 `json:"percent_change_1h,omitempty"` PercentChange24h float32 `json:"percent_change_24h,omitempty"` PercentChange7d float32 `json:"percent_change_7d,omitempty"` PercentChange30d float32 `json:"percent_change_30d,omitempty"` MarketCap float32 `json:"market_cap,omitempty"` LastUpdated time.Time `json:"last_updated,omitempty"` } `json:"quote"` } `json:"data"` } type GetLatestPricesBySymbolsRequest struct { Symbols []string } type Api struct { URL string Key string } func (api Api) GetLatestPricesBySymbols(request GetLatestPricesBySymbolsRequest) (GetLatestPricesBySymbolsResponse, error) { client := http.Client{ Timeout: time.Second * 10, // Timeout after 10 seconds } req, err := http.NewRequest(http.MethodGet, api.URL+"/v1/cryptocurrency/quotes/latest", nil) if err != nil { log.Fatal(err) } req.Header.Set("X-CMC_PRO_API_KEY", api.Key) q := req.URL.Query() q.Add("symbol", strings.Join(request.Symbols[:], ",")) req.URL.RawQuery = q.Encode() res, getErr := client.Do(req) if getErr != nil { log.Fatal(getErr) } body, readErr := ioutil.ReadAll(res.Body) if readErr != nil { log.Fatal(readErr) } getLatestPricesBySymbolsResponse := GetLatestPricesBySymbolsResponse{} jsonErr := json.Unmarshal(body, &getLatestPricesBySymbolsResponse) if jsonErr != nil { log.Fatal(jsonErr) } return getLatestPricesBySymbolsResponse, nil }
package main func setZeroes(matrix [][]int) { row := len(matrix) col := len(matrix[0]) firstRow := false firstCol := false for i := 0; i < row; i++ { for j := 0; j < col; j++ { item := matrix[i][j] if item == 0 { if i == 0 { firstRow = true } if j == 0 { firstCol = true } matrix[i][0] = 0 matrix[0][j] = 0 } } } for i := 1; i < row; i++ { for j := 1; j < col; j++ { if matrix[i][0] == 0 || matrix[0][j] == 0 { matrix[i][j] = 0 } } } if firstRow { for j := 0; j < col; j++ { matrix[0][j] = 0 } } if firstCol { for i := 0; i < row; i++ { matrix[i][0] = 0 } } }
package todo import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/mcaparna/GoCodingChallenge/todo" "gopkg.in/DATA-DOG/go-sqlmock.v1" ) func TestUpdateTodo(t *testing.T) { userJson := `{"status": "Closed", "title": "Clean Home"}` reader := strings.NewReader(userJson) //Convert string to reader request, err := http.NewRequest("PUT", "http://127.0.0.1:8080/todos/1", reader) //Create request with JSON body res := httptest.NewRecorder() if err != nil { t.Error(err) //Something is wrong while sending request } db, mock, err := sqlmock.New() if err != nil { t.Errorf("An error '%s' was not expected when opening a stub database connection", err) } defer db.Close() mock.ExpectBegin() mock.ExpectQuery("^SELECT (.+) FROM todo WHERE").WithArgs("id","title","status").WillReturnRows(sqlmock.NewRows([]string{"id","title", "status"}).AddRow("1","val1", "val2")) mock.ExpectPrepare("UPDATE todo SET title = $2, status = $3 WHERE id = $1").ExpectExec().WithArgs("id","title","status").WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectClose() todo.Update(res, request, nil) if err != nil { t.Errorf("Expected no error, but got %s instead", err) } // we make sure that all expectations were met if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } } func TestCreateTodo(t *testing.T) { userJson := `{"status": "Closed", "title": "Clean Home"}` reader := strings.NewReader(userJson) //Convert string to reader request, err := http.NewRequest("POST", "http://127.0.0.1:8080/todos", reader) //Create request with JSON body res := httptest.NewRecorder() if err != nil { t.Error(err) //Something is wrong while sending request } db, mock, err := sqlmock.New() if err != nil { t.Errorf("An error '%s' was not expected when opening a stub database connection", err) } defer db.Close() mock.ExpectBegin() mock.ExpectQuery("^SELECT (.+) FROM todo WHERE").WithArgs("id","title","status").WillReturnRows(sqlmock.NewRows([]string{"id","title", "status"}).AddRow("1","val1", "val2")) mock.ExpectPrepare("INSERT into todo").ExpectExec().WithArgs("id","title","status").WillReturnResult(sqlmock.NewResult(1, 1)) mock.ExpectClose() todo.Create(res, request, nil) if err != nil { t.Errorf("Expected no error, but got %s instead", err) } // we make sure that all expectations were met if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } } func TestListTodo(t *testing.T) { userJson := `{"status": "Closed", "title": "Clean Home"}` reader := strings.NewReader(userJson) //Convert string to reader request, err := http.NewRequest("GET", "http://127.0.0.1:8080/todos", reader) //Create request with JSON body res := httptest.NewRecorder() if err != nil { t.Error(err) //Something is wrong while sending request } db, mock, err := sqlmock.New() if err != nil { t.Errorf("An error '%s' was not expected when opening a stub database connection", err) } defer db.Close() mock.ExpectBegin() mock.ExpectQuery("^SELECT (.+) FROM todo WHERE").WithArgs("id","title","status").WillReturnRows(sqlmock.NewRows([]string{"id","title", "status"}).AddRow("1","val1", "val2")) mock.ExpectClose() todo.List(res, request, nil) if err != nil { t.Errorf("Expected no error, but got %s instead", err) } // we make sure that all expectations were met if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } }
package limit import ( "fmt" "log" "sync" ) // 限制管理 type SecLimitMgr struct { UserLimitMap *sync.Map IpLimitMap *sync.Map } var SecLimitMgrVars = &SecLimitMgr{ UserLimitMap: new(sync.Map), IpLimitMap: new(sync.Map), } var ( IPBlackMap = make(map[string]bool) IDBlackMap = make(map[string]bool) ) func CheckBlack(userId string, IP string, nowTime int64) (err error){ // 初始化 var secIdCount, secIpCount int //var limit *Limit var limit = new(Limit) // 用户黑名单 _, ok := IDBlackMap[userId] if ok { // TODO err = fmt.Errorf("invalid request") log.Printf("user[%v] is block by id black", userId) return } // IP黑名单 _, ok = IPBlackMap[IP] if ok { // TODO err = fmt.Errorf("invalid request") log.Printf("userId[%v] ip[%v] is block by ip black", userId, IP) return } // 用户ID频率控制 user, ok := SecLimitMgrVars.UserLimitMap.Load(userId) if !ok { limit = &Limit{ secLimit: &SecLimit{}, } SecLimitMgrVars.UserLimitMap.Store(userId, limit) } else { limit = user.(*Limit) } secIdCount = limit.secLimit.Count(nowTime) // 客户端Ip频率控制 ip, ok := SecLimitMgrVars.IpLimitMap.Load(IP) if !ok { limit = &Limit{ secLimit: &SecLimit{}, } SecLimitMgrVars.IpLimitMap.Store(IP,limit) } else { limit = ip.(*Limit) } secIpCount = limit.secLimit.Count(nowTime) // 设置频率 if secIdCount > 50000 { // TODO err = fmt.Errorf("invalid request") return } if secIpCount > 50000 { // TODO err = fmt.Errorf("invalid request") return } return }
package redisDB import ( "bytes" "encoding/gob" "fmt" "strconv" ) func (c *Client) processTask(task ReqTask) { if taskFunc := c.getTaskFunc(task.ID); taskFunc != nil { taskFunc(task) } else { fmt.Println("[processTask] invalid task id. ", task.ID) } } func (c *Client) processTaskReqLogin(reqTask ReqTask) { var req ReqTaskLogin buf := bytes.NewBuffer(reqTask.Data) if err := gob.NewDecoder(buf).Decode(&req); err != nil { fmt.Println("[processTaskReqLogin] err ", err) } var res ResTask res.UID = reqTask.UID res.ID = TaskID_ResLogin res.Result = TaskResult_Success key := redisKey_UserAuth(req.UserID) val, err := c._rc.Get(key).Result() if err != nil { res.Result = TaskResult_EmptyAuth } else { if auth, _ := strconv.ParseUint(val, 10, 64); auth != req.AuthCode { res.Result = TaskResult_FailAuth } } reqTask.ResChan <- res } /* package main import ( "bytes" "encoding/gob" "fmt" ) type Hoge struct { F1 string F2 int64 } func main() { encoded := encode() fmt.Printf("encoded: %d bytes\n", len(encoded)) decoded := decode(encoded) fmt.Printf("decoded: %+v\n", decoded) } func encode() []byte { h := Hoge{F1: "hoge", F2: 123} buf := bytes.NewBuffer(nil) _ = gob.NewEncoder(buf).Encode(&h) return buf.Bytes() } func decode(data []byte) *Hoge { var h Hoge buf := bytes.NewBuffer(data) _ = gob.NewDecoder(buf).Decode(&h) return &h } */
package leetcode import ( "testing" ) func TestFib(t *testing.T) { type args struct { n int } tests := []struct { name string args args want int }{ {"0 test", args{0}, 0}, {"n1", args{2}, 1}, {"n2", args{5}, 5}, {"n3", args{45}, 134903163}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Fib4(tt.args.n); got != tt.want { t.Errorf("Fib() = %v, want %v", got, tt.want) } }) } } func TestCoinChange(t *testing.T) { type args struct { coins []int amount int } tests := []struct { name string args args want int }{ {"n1", args{[]int{1, 2, 5}, 11}, 3}, {"no answer", args{[]int{2}, 3}, -1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := CoinChange(tt.args.coins, tt.args.amount); got != tt.want { t.Errorf("CoinChange() = %v, want %v", got, tt.want) } }) } } func Test_climbStairs(t *testing.T) { n := 3 t.Log(climbStairs(n)) } func Test_rob(t *testing.T) { nums := []int{2, 7, 9, 3, 1} t.Log(rob2(nums)) }
package main import ( "github.com/spf13/cobra" "github.com/openshift/installer/pkg/explain" ) func newExplainCmd() *cobra.Command { return explain.NewCmd() }
package main import ( "context" "encoding/json" "flag" "fmt" "log" "net/http" "os" "os/signal" "strconv" "strings" "syscall" "time" "github.com/machinebox/graphql" ) const ( owmAPIEndpoint = "https://api.openweathermap.org/data/2.5/weather?appid={api-key}&units=metric" githubAPIEndpoint = "https://api.github.com/graphql" githubClientID = "github/weather" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() sigc := make(chan os.Signal, 2) signal.Notify(sigc, os.Interrupt, syscall.SIGTERM) go func() { <-sigc cancel() }() if err := run(ctx, os.Args[1:]); err != nil { log.Fatal(err) } } func run(ctx context.Context, args []string) error { flags := flag.NewFlagSet("", flag.ExitOnError) var ( debug bool owmAPIKey string owmQuery string githubAPIToken string ) flags.BoolVar(&debug, "debug", false, "Enable debug logging") flags.StringVar(&owmAPIKey, "owm.api-key", "", "OpenWeather API key") flags.StringVar(&owmQuery, "owm.query", "Berlin,de", "OpenWeather API query, city name, state and country code divided by comma") flags.StringVar(&githubAPIToken, "github.token", "", "GitHub API token") if err := flags.Parse(args); err != nil { return err } if owmAPIKey == "" || githubAPIToken == "" { return fmt.Errorf("no API credentials passed: OpenWeather %q, GitHub %q", owmAPIKey, githubAPIToken) } owm := NewOWMClient(owmAPIEndpoint, owmAPIKey) gh := NewGitHubClient(githubAPIEndpoint, githubAPIToken) if debug { gh.client.Log = func(s string) { log.Println(s) } } wr, err := owm.Weather(ctx, owmQuery) if err != nil { return err } log.Printf("got owm response: %+v\n", wr) status := ChangeUserStatusInput{ ClientMutationID: githubClientID, Emoji: wr.Emoji(), Message: wr.ShortString(), ExpiresAt: time.Now().UTC().Add(30 * time.Minute), // XXX(narqo) status's expiration time is hardcoded } sr, err := gh.ChangeUserStatus(ctx, status) if err != nil { return err } log.Printf("set gh status: %+v\n", sr) return nil } type OWMClient struct { apiURL string client *http.Client } func NewOWMClient(apiURL, apiKey string) *OWMClient { return &OWMClient{ apiURL: strings.Replace(apiURL, "{api-key}", apiKey, 1), client: &http.Client{}, } } type WeatherResponse struct { Cod int `json:"cod"` ID int `json:"id"` Name string `json:"name"` Weather []struct { ID int `json:"id"` Main string `json:"main"` Description string `json:"description"` Icon string `json:"icon"` } `json:"weather"` Main struct { Temp float64 `json:"temp"` FeelsLike float64 `json:"feels_like"` } `json:"main"` } func (wr WeatherResponse) ShortString() string { var s strings.Builder s.WriteString(wr.Name) s.WriteByte(',') s.WriteByte(' ') if wr.Main.Temp > 0 { s.WriteByte('+') } s.WriteString(strconv.FormatFloat(wr.Main.Temp, 'f', 0, 64)) s.WriteString("°") // WriteString as "degree" is not from ASCII return s.String() } // Emoji maps OpenWeather weather status to emojis. // See https://openweathermap.org/weather-conditions func (wr WeatherResponse) Emoji() string { if len(wr.Weather) == 0 { return ":zap:" } w := wr.Weather[0] if w.ID == 800 { if w.Icon == "01n" { return ":full_moon:" } return ":sunny:" } if w.ID > 800 { switch w.ID { case 801: return "🌤️" case 802: return ":cloudy:" default: return ":partly_sunny:" } } else if w.ID >= 700 { return ":foggy:" } else if w.ID >= 600 { return ":snowflake:" } else if w.ID >= 500 { if w.ID == 500 { return "🌦️" } if w.ID >= 511 { return "🌨️" } return "☔" } else if w.ID >= 300 { return "🌦️" } else if w.ID >= 200 { return "⛈️" } return ":zap:" } func (c *OWMClient) Weather(ctx context.Context, query string) (WeatherResponse, error) { u := c.apiURL + "&q=" + query req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return WeatherResponse{}, err } resp, err := c.client.Do(req) if err != nil { return WeatherResponse{}, fmt.Errorf("weather API request failed, query %q: %w", query, err) } defer resp.Body.Close() var wr WeatherResponse if err := json.NewDecoder(resp.Body).Decode(&wr); err != nil { return WeatherResponse{}, err } if wr.Cod != 200 { return WeatherResponse{}, fmt.Errorf("wearther API bad response, for %q: %+v", query, wr) } return wr, nil } type GitHubClient struct { apiURL string token string client *graphql.Client } func NewGitHubClient(apiURL, token string, opts ...graphql.ClientOption) *GitHubClient { return &GitHubClient{ apiURL: apiURL, token: token, client: graphql.NewClient(apiURL, opts...), } } type ChangeUserStatusInput struct { ClientMutationID string `json:"clientMutationId,omitempty"` Emoji string `json:"emoji,omitempty"` ExpiresAt time.Time `json:"expiresAt,omitempty"` LimitedAvailability bool `json:"limitedAvailability,omitempty"` Message string `json:"message,omitempty"` OrganizationID string `json:"organizationId,omitempty"` } type ChangeUserStatusResponse struct { ID string `json:"id"` UpdatedAt time.Time `json:"updatedAt"` ExpiresAt time.Time `json:"expiresAt"` } const mutationChangeUserStatus = ` mutation ($status: ChangeUserStatusInput!) { changeUserStatus(input: $status) { status { id updatedAt expiresAt } } } ` func (c *GitHubClient) ChangeUserStatus(ctx context.Context, input ChangeUserStatusInput) (ChangeUserStatusResponse, error) { req := graphql.NewRequest(mutationChangeUserStatus) req.Var("status", input) resp := struct { ChangeUserStatus struct { Status ChangeUserStatusResponse `json:"status"` } `json:"changeUserStatus"` }{} if err := c.run(ctx, req, &resp); err != nil { return ChangeUserStatusResponse{}, fmt.Errorf("github API request failed: %w", err) } status := resp.ChangeUserStatus.Status if status.UpdatedAt.Before(time.Now().UTC().Add(-time.Minute)) { return ChangeUserStatusResponse{}, fmt.Errorf("status not updated, github API respose: %v", resp) } return status, nil } func (c *GitHubClient) run(ctx context.Context, req *graphql.Request, resp interface{}) error { if c.token != "" { req.Header.Add("Authorization", "bearer "+c.token) } return c.client.Run(ctx, req, resp) }
package types import ( "encoding/base64" "fmt" "strings" sdk "github.com/cosmos/cosmos-sdk/types" ) /* A Contract is a special structure encapsulating the context of a coordinated execution made by the Contract Execution Environment. This context represents a piece of code and a set of methods, data that are replicated between one or more parties then executed. The results of this execution as well as all of the input and output state is captured in a Contract object. Contract Type Overview - Recital - An identity performing a role, associated with identification information - RecordReference - A reference to a record on chain. This reference can be as generic as a scope or as specific as a particular execution context (record group) and hash output on a record. - Condition - Preconditions satisfied before the contract was invoked - Consideration - A set of outputs from the contract. These will be added as Records in a Scope - ExecutionResult - Results of an execution, associated with Conditions and Considerations. - ProposedRecord - A reference to existing data on chain or a simple hash to off chain data referenced */ // ValidateBasic runs stateless validation checks on the message. func (contract Contract) ValidateBasic() error { // Validate contract fields scopeID := strings.TrimSpace(contract.Spec.Reference.ScopeId) if scopeID == "" { return fmt.Errorf("contract spec data location scope ref is nil") } hash := strings.TrimSpace(contract.Spec.Reference.Hash) if hash == "" { return fmt.Errorf("contract spec data location ref hash is empty") } if _, err := base64.StdEncoding.DecodeString(hash); err != nil { return fmt.Errorf("ref hash is not base64 encoded: %w", err) } for _, p := range contract.Recitals.Parties { if _, err := sdk.AccAddressFromBech32(p.Address); err != nil { return err } } return nil } // GetSigners returns the required signers for a given contract func (contract Contract) GetSigners() (signers []sdk.AccAddress) { signers = make([]sdk.AccAddress, 0, len(contract.Recitals.Parties)) for i, p := range contract.Recitals.Parties { addr, err := sdk.AccAddressFromBech32(p.Address) if err != nil { panic(err) } signers[i] = addr } return }
package quotes import ( "errors" "math/rand" "strings" ) import "io/ioutil" type Quotes struct { list []*string } const ( defaultQuoteListBuffer = 1024 ) func NewQuotesFromFile(filename string) (q *Quotes, err error) { // TODO: Inefficient q = new(Quotes) if bytes, err := ioutil.ReadFile(filename); err != nil { return nil, err } else { quotes := strings.Split(string(bytes), "\n") for i := 0; i < len(quotes); i++ { q.add(&quotes[i]) } } return q, nil } func NewQuotes() (q *Quotes) { return new(Quotes) } func (q *Quotes) Random() *string { rnd_idx := rand.Intn(q.Len()) return q.list[rnd_idx] } func (q *Quotes) get(idx int) (quote *string) { return q.list[idx] } func (q *Quotes) Get(idx int) (quote *string, err error) { if idx > len(q.list) { return nil, errors.New("index is out of bounds") } return q.get(idx), nil } func (q *Quotes) add(quote *string) { q.list = append(q.list, quote) } func (q *Quotes) List() chan *string { c := make(chan *string, defaultQuoteListBuffer) go func() { for i := 0; i < q.Len(); i++ { c <- q.get(i) } close(c) }() return c } func (q *Quotes) Len() int { return len(q.list) }
package pdexv3 import ( "encoding/json" metadataCommon "incognito-chain/metadata/common" ) type UserMintNftRequest struct { metadataCommon.MetadataBase otaReceiver string amount uint64 } func NewUserMintNftRequest() *UserMintNftRequest { return &UserMintNftRequest{} } func NewUserMintNftRequestWithValue(otaReceiver string, amount uint64) *UserMintNftRequest { metadataBase := metadataCommon.MetadataBase{ Type: metadataCommon.Pdexv3UserMintNftRequestMeta, } return &UserMintNftRequest{ otaReceiver: otaReceiver, amount: amount, MetadataBase: metadataBase, } } func (request *UserMintNftRequest) MarshalJSON() ([]byte, error) { data, err := json.Marshal(struct { OtaReceiver string `json:"OtaReceiver"` Amount uint64 `json:"Amount"` metadataCommon.MetadataBase }{ Amount: request.amount, OtaReceiver: request.otaReceiver, MetadataBase: request.MetadataBase, }) if err != nil { return []byte{}, err } return data, nil } func (request *UserMintNftRequest) UnmarshalJSON(data []byte) error { temp := struct { OtaReceiver string `json:"OtaReceiver"` Amount metadataCommon.Uint64Reader `json:"Amount"` metadataCommon.MetadataBase }{} err := json.Unmarshal(data, &temp) if err != nil { return err } request.amount = uint64(temp.Amount) request.otaReceiver = temp.OtaReceiver request.MetadataBase = temp.MetadataBase return nil } func (request *UserMintNftRequest) OtaReceiver() string { return request.otaReceiver } func (request *UserMintNftRequest) Amount() uint64 { return request.amount }
package helpers import ( "encoding/json" "fmt" "io/ioutil" "os" ) func GenericReadFile(fileLoc string, el interface{}) { jsonFile, err := os.Open(fileLoc) byteValue, _ := ioutil.ReadAll(jsonFile) json.Unmarshal(byteValue, &el) if err != nil { fmt.Println(err) os.Exit(1) } jsonFile.Close() }
package services import ( "context" "fmt" metal "github.com/chutommy/metal-price/metal/service/protos/metal" ) // Metal handles the metal price services. type Metal struct { client metal.MetalClient } // NewMetal is a constructor for the Metal service. func NewMetal(mc metal.MetalClient) *Metal { return &Metal{ client: mc, } } // GetPrice call the service and returns the price of the metal. func (m *Metal) GetPrice(materialP string) (float64, error) { if mn, ok := PeriodicSymbols[materialP]; ok { materialP = mn } material, ok := metal.Materials_value[materialP] if !ok { return 0, fmt.Errorf("material %v not found", materialP) } // create request request := &metal.MetalRequest{Metal: metal.Materials(material)} // call the service response, err := m.client.GetPrice(context.Background(), request) if err != nil { return -1, fmt.Errorf("metal service: %w", err) } // success return response.GetPrice(), nil }
package main import ( "bytes" "io" "log" "os" "path/filepath" "syscall" ) const pipesDirectory string = "/tmp/ereminders_pipes" const commandPipeName string = "commands" const commandResultPipeName string = "recv" func getTemporaryDirectory() (string, error) { err := os.MkdirAll(pipesDirectory, 0755) if err != nil { log.Println("Error: Unable to create temporary directory") return "", err } return pipesDirectory, nil } func makeNamedPipe(name string) string { tempDir, _ := getTemporaryDirectory() namedPipeFilename := filepath.Join(tempDir, name) syscall.Mkfifo(namedPipeFilename, 0600) return namedPipeFilename } func openPipe(pipeName string, flags int) *os.File { filename := makeNamedPipe(pipeName) pipe, err := os.OpenFile(filename, flags, 0600) if err != nil { log.Print("Error opening pipe: ") log.Println(err) return nil } return pipe } // ReadCommand blocks on the command pipe until data is received func ReadCommand() string { commandPipe := openPipe(commandPipeName, os.O_RDONLY) var commandBuf bytes.Buffer io.Copy(&commandBuf, commandPipe) commandPipe.Close() return commandBuf.String() } // SendCommand sends a command string to the command named pipe func SendCommand(command string) { commandPipe := openPipe(commandPipeName, os.O_WRONLY) commandPipe.WriteString(command) commandPipe.Close() } // SendResponse sends the response to the tx/rx pipe func SendResponse(response string) { txPipe := openPipe(commandResultPipeName, os.O_WRONLY) txPipe.WriteString(response) txPipe.Close() } // ReadResponse blocks while it waits for a response on the tx/rx named pipe func ReadResponse() string { rxPipe := openPipe(commandResultPipeName, os.O_RDONLY) var rxBuf bytes.Buffer io.Copy(&rxBuf, rxPipe) rxPipe.Close() return rxBuf.String() } // TransmitCommand sends the command to the command pipe, then waits for a response from the // recv pipe func TransmitCommand(command string) string { SendCommand(command) return ReadResponse() }
package main import "testing" func TestRayPointAt(t *testing.T) { ray := Ray{Origin: Vector{0.0, 0.0, 0.0}, Direction: Vector{1.0, 0.0, 0.0}.MakeUnitVector()} v := ray.PointAt(1.0) e := Vector{1.0, 0.0, 0.0} if v != e { t.Errorf("expected %s but got %s", e, v) } }
package services import ( "io" "log" "mime/multipart" "os" ) type FileService struct { } var File = new(FileService) func (self *FileService) Upload(file *multipart.File, filename string, folder string) (fname string, err error) { os.MkdirAll("static/"+folder, os.ModePerm) out, err := os.Create("static/" + folder + "/" + filename) if err != nil { log.Fatal(err) return "", err } defer out.Close() _, err = io.Copy(out, *file) if err != nil { log.Fatal(err) return "", err } return filename, err } func (self *FileService) Clear(folder string) error { return os.RemoveAll("static/" + folder) }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package simpletest import ( "context" "strconv" "testing" "github.com/pingcap/errors" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/errno" "github.com/pingcap/tidb/parser/auth" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/planner/core" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/statistics/handle" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/util/dbterror/exeerrors" "github.com/stretchr/testify/require" "go.opencensus.io/stats/view" ) func TestFlushTables(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("FLUSH TABLES") err := tk.ExecToErr("FLUSH TABLES WITH READ LOCK") require.Error(t, err) } func TestUseDB(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("USE test") err := tk.ExecToErr("USE ``") require.Truef(t, terror.ErrorEqual(core.ErrNoDB, err), "err %v", err) } func TestStmtAutoNewTxn(t *testing.T) { store := testkit.CreateMockStore(t) // Some statements are like DDL, they commit the previous txn automically. tk := testkit.NewTestKit(t, store) tk.MustExec("use test") // Fix issue https://github.com/pingcap/tidb/issues/10705 tk.MustExec("begin") tk.MustExec("create user 'xxx'@'%';") tk.MustExec("grant all privileges on *.* to 'xxx'@'%';") tk.MustExec("create table auto_new (id int)") tk.MustExec("begin") tk.MustExec("insert into auto_new values (1)") tk.MustExec("revoke all privileges on *.* from 'xxx'@'%'") tk.MustExec("rollback") // insert statement has already committed tk.MustQuery("select * from auto_new").Check(testkit.Rows("1")) // Test the behavior when autocommit is false. tk.MustExec("set autocommit = 0") tk.MustExec("insert into auto_new values (2)") tk.MustExec("create user 'yyy'@'%'") tk.MustExec("rollback") tk.MustQuery("select * from auto_new").Check(testkit.Rows("1", "2")) tk.MustExec("drop user 'yyy'@'%'") tk.MustExec("insert into auto_new values (3)") tk.MustExec("rollback") tk.MustQuery("select * from auto_new").Check(testkit.Rows("1", "2")) } func TestIssue9111(t *testing.T) { store := testkit.CreateMockStore(t) // CREATE USER / DROP USER fails if admin doesn't have insert privilege on `mysql.user` table. tk := testkit.NewTestKit(t, store) tk.MustExec("create user 'user_admin'@'localhost';") tk.MustExec("grant create user on *.* to 'user_admin'@'localhost';") // Create a new session. se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "user_admin", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `create user test_create_user`) require.NoError(t, err) _, err = se.Execute(ctx, `drop user test_create_user`) require.NoError(t, err) tk.MustExec("revoke create user on *.* from 'user_admin'@'localhost';") tk.MustExec("grant insert, delete on mysql.user to 'user_admin'@'localhost';") _, err = se.Execute(ctx, `create user test_create_user`) require.NoError(t, err) _, err = se.Execute(ctx, `drop user test_create_user`) require.NoError(t, err) _, err = se.Execute(ctx, `create role test_create_user`) require.NoError(t, err) _, err = se.Execute(ctx, `drop role test_create_user`) require.NoError(t, err) tk.MustExec("drop user 'user_admin'@'localhost';") } func TestRoleAtomic(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("create role r2;") err := tk.ExecToErr("create role r1, r2, r3") require.Error(t, err) // Check atomic create role. result := tk.MustQuery(`SELECT user FROM mysql.User WHERE user in ('r1', 'r2', 'r3')`) result.Check(testkit.Rows("r2")) // Check atomic drop role. err = tk.ExecToErr("drop role r1, r2, r3") require.Error(t, err) result = tk.MustQuery(`SELECT user FROM mysql.User WHERE user in ('r1', 'r2', 'r3')`) result.Check(testkit.Rows("r2")) tk.MustExec("drop role r2;") } func TestExtendedStatsPrivileges(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int, b int)") tk.MustExec("create user 'u1'@'%'") se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "set session tidb_enable_extended_stats = on") require.NoError(t, err) _, err = se.Execute(ctx, "alter table test.t add stats_extended s1 correlation(a,b)") require.Error(t, err) require.Equal(t, "[planner:1142]ALTER command denied to user 'u1'@'%' for table 't'", err.Error()) tk.MustExec("grant alter on test.* to 'u1'@'%'") _, err = se.Execute(ctx, "alter table test.t add stats_extended s1 correlation(a,b)") require.Error(t, err) require.Equal(t, "[planner:1142]ADD STATS_EXTENDED command denied to user 'u1'@'%' for table 't'", err.Error()) tk.MustExec("grant select on test.* to 'u1'@'%'") _, err = se.Execute(ctx, "alter table test.t add stats_extended s1 correlation(a,b)") require.Error(t, err) require.Equal(t, "[planner:1142]ADD STATS_EXTENDED command denied to user 'u1'@'%' for table 'stats_extended'", err.Error()) tk.MustExec("grant insert on mysql.stats_extended to 'u1'@'%'") _, err = se.Execute(ctx, "alter table test.t add stats_extended s1 correlation(a,b)") require.NoError(t, err) _, err = se.Execute(ctx, "use test") require.NoError(t, err) _, err = se.Execute(ctx, "alter table t drop stats_extended s1") require.Error(t, err) require.Equal(t, "[planner:1142]DROP STATS_EXTENDED command denied to user 'u1'@'%' for table 'stats_extended'", err.Error()) tk.MustExec("grant update on mysql.stats_extended to 'u1'@'%'") _, err = se.Execute(ctx, "alter table t drop stats_extended s1") require.NoError(t, err) tk.MustExec("drop user 'u1'@'%'") } func TestIssue17247(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("create user 'issue17247'") tk.MustExec("grant CREATE USER on *.* to 'issue17247'") tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use test") require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "issue17247", Hostname: "%"}, nil, nil, nil)) tk1.MustExec("ALTER USER USER() IDENTIFIED BY 'xxx'") tk1.MustExec("ALTER USER CURRENT_USER() IDENTIFIED BY 'yyy'") tk1.MustExec("ALTER USER CURRENT_USER IDENTIFIED BY 'zzz'") tk.MustExec("ALTER USER 'issue17247'@'%' IDENTIFIED BY 'kkk'") tk.MustExec("ALTER USER 'issue17247'@'%' IDENTIFIED BY PASSWORD '*B50FBDB37F1256824274912F2A1CE648082C3F1F'") // Wrong grammar _, err := tk1.Exec("ALTER USER USER() IDENTIFIED BY PASSWORD '*B50FBDB37F1256824274912F2A1CE648082C3F1F'") require.Error(t, err) } // Close issue #23649. // See https://github.com/pingcap/tidb/issues/23649 func TestIssue23649(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("DROP USER IF EXISTS issue23649;") tk.MustExec("CREATE USER issue23649;") err := tk.ExecToErr("GRANT bogusrole to issue23649;") require.Equal(t, "[executor:3523]Unknown authorization ID `bogusrole`@`%`", err.Error()) err = tk.ExecToErr("GRANT bogusrole to nonexisting;") require.Equal(t, "[executor:3523]Unknown authorization ID `bogusrole`@`%`", err.Error()) } func TestSetCurrentUserPwd(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("CREATE USER issue28534;") defer func() { tk.MustExec("DROP USER IF EXISTS issue28534;") }() require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "issue28534", Hostname: "localhost", CurrentUser: true, AuthUsername: "issue28534", AuthHostname: "%"}, nil, nil, nil)) tk.MustExec(`SET PASSWORD FOR CURRENT_USER() = "43582eussi"`) require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil, nil)) result := tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="issue28534"`) result.Check(testkit.Rows(auth.EncodePassword("43582eussi"))) } func TestShowGrantsAfterDropRole(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("CREATE USER u29473") defer tk.MustExec("DROP USER IF EXISTS u29473") tk.MustExec("CREATE ROLE r29473") tk.MustExec("GRANT r29473 TO u29473") tk.MustExec("GRANT CREATE USER ON *.* TO u29473") tk.Session().Auth(&auth.UserIdentity{Username: "u29473", Hostname: "%"}, nil, nil, nil) tk.MustExec("SET ROLE r29473") tk.MustExec("DROP ROLE r29473") tk.MustQuery("SHOW GRANTS").Check(testkit.Rows("GRANT CREATE USER ON *.* TO 'u29473'@'%'")) } func TestPrivilegesAfterDropUser(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table t1(id int, v int)") defer tk.MustExec("drop table t1") tk.MustExec("CREATE USER u1 require ssl") defer tk.MustExec("DROP USER IF EXISTS u1") tk.MustExec("GRANT CREATE ON test.* TO u1") tk.MustExec("GRANT UPDATE ON test.t1 TO u1") tk.MustExec("GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO u1") tk.MustExec("GRANT SELECT(v), UPDATE(v) on test.t1 TO u1") tk.MustQuery("SELECT COUNT(1) FROM mysql.global_grants WHERE USER='u1' AND HOST='%'").Check(testkit.Rows("1")) tk.MustQuery("SELECT COUNT(1) FROM mysql.global_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows("1")) tk.MustQuery("SELECT COUNT(1) FROM mysql.tables_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows("1")) tk.MustQuery("SELECT COUNT(1) FROM mysql.columns_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows("1")) tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil, nil) tk.MustQuery("SHOW GRANTS FOR u1").Check(testkit.Rows( "GRANT USAGE ON *.* TO 'u1'@'%'", "GRANT CREATE ON test.* TO 'u1'@'%'", "GRANT UPDATE ON test.t1 TO 'u1'@'%'", "GRANT SELECT(v), UPDATE(v) ON test.t1 TO 'u1'@'%'", "GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO 'u1'@'%'", )) tk.MustExec("DROP USER u1") err := tk.QueryToErr("SHOW GRANTS FOR u1") require.Equal(t, "[privilege:1141]There is no such grant defined for user 'u1' on host '%'", err.Error()) tk.MustQuery("SELECT * FROM mysql.global_grants WHERE USER='u1' AND HOST='%'").Check(testkit.Rows()) tk.MustQuery("SELECT * FROM mysql.global_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows()) tk.MustQuery("SELECT * FROM mysql.tables_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows()) tk.MustQuery("SELECT * FROM mysql.columns_priv WHERE USER='u1' AND HOST='%'").Check(testkit.Rows()) } func TestDropRoleAfterRevoke(t *testing.T) { store := testkit.CreateMockStore(t) // issue 29781 tk := testkit.NewTestKit(t, store) tk.MustExec("use test;") tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil, nil) tk.MustExec("create role r1, r2, r3;") defer tk.MustExec("drop role if exists r1, r2, r3;") tk.MustExec("grant r1,r2,r3 to current_user();") tk.MustExec("set role all;") tk.MustExec("revoke r1, r3 from root;") tk.MustExec("drop role r1;") } func TestUserWithSetNames(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("use test;") tk.MustExec("set names gbk;") tk.MustExec("drop user if exists '\xd2\xbb'@'localhost';") tk.MustExec("create user '\xd2\xbb'@'localhost' IDENTIFIED BY '\xd2\xbb';") result := tk.MustQuery("SELECT authentication_string FROM mysql.User WHERE User='\xd2\xbb' and Host='localhost';") result.Check(testkit.Rows(auth.EncodePassword("一"))) tk.MustExec("ALTER USER '\xd2\xbb'@'localhost' IDENTIFIED BY '\xd2\xbb\xd2\xbb';") result = tk.MustQuery("SELECT authentication_string FROM mysql.User WHERE User='\xd2\xbb' and Host='localhost';") result.Check(testkit.Rows(auth.EncodePassword("一一"))) tk.MustExec("RENAME USER '\xd2\xbb'@'localhost' to '\xd2\xbb'") tk.MustExec("drop user '\xd2\xbb';") } func TestStatementsCauseImplicitCommit(t *testing.T) { // Test some of the implicit commit statements. // See https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("use test;") tk.MustExec("create table ic (id int primary key)") cases := []string{ "create table xx (id int)", "create user 'xx'@'127.0.0.1'", "grant SELECT on test.ic to 'xx'@'127.0.0.1'", "flush privileges", "analyze table ic", } for i, sql := range cases { tk.MustExec("begin") tk.MustExec("insert into ic values (?)", i) tk.MustExec(sql) tk.MustQuery("select * from ic where id = ?", i).Check(testkit.Rows(strconv.FormatInt(int64(i), 10))) // Clean up data tk.MustExec("delete from ic") } } func TestDo(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("do 1, @a:=1") tk.MustQuery("select @a").Check(testkit.Rows("1")) tk.MustExec("use test") tk.MustExec("create table t (i int)") tk.MustExec("insert into t values (1)") tk2 := testkit.NewTestKit(t, store) tk2.MustExec("use test") tk.MustQuery("select * from t").Check(testkit.Rows("1")) tk.MustExec("do @a := (select * from t where i = 1)") tk2.MustExec("insert into t values (2)") tk.MustQuery("select * from t").Check(testkit.Rows("1", "2")) } func TestDoWithAggFunc(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("DO sum(1)") tk.MustExec("DO avg(@e+@f)") tk.MustExec("DO GROUP_CONCAT(NULLIF(ELT(1, @e), 2.0) ORDER BY 1)") } func TestSetRoleAllCorner(t *testing.T) { store := testkit.CreateMockStore(t) // For user with no role, `SET ROLE ALL` should active // a empty slice, rather than nil. tk := testkit.NewTestKit(t, store) tk.MustExec("create user set_role_all") se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "set_role_all", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `set role all`) require.NoError(t, err) _, err = se.Execute(ctx, `select current_role`) require.NoError(t, err) } func TestCreateRole(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("create user testCreateRole;") tk.MustExec("grant CREATE USER on *.* to testCreateRole;") se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `create role test_create_role;`) require.NoError(t, err) tk.MustExec("revoke CREATE USER on *.* from testCreateRole;") tk.MustExec("drop role test_create_role;") tk.MustExec("grant CREATE ROLE on *.* to testCreateRole;") _, err = se.Execute(ctx, `create role test_create_role;`) require.NoError(t, err) tk.MustExec("drop role test_create_role;") _, err = se.Execute(ctx, `create user test_create_role;`) require.Error(t, err) tk.MustExec("drop user testCreateRole;") } func TestDropRole(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("create user testCreateRole;") tk.MustExec("create user test_create_role;") tk.MustExec("grant CREATE USER on *.* to testCreateRole;") se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `drop role test_create_role;`) require.NoError(t, err) tk.MustExec("revoke CREATE USER on *.* from testCreateRole;") tk.MustExec("create role test_create_role;") tk.MustExec("grant DROP ROLE on *.* to testCreateRole;") _, err = se.Execute(ctx, `drop role test_create_role;`) require.NoError(t, err) tk.MustExec("create user test_create_role;") _, err = se.Execute(ctx, `drop user test_create_role;`) require.Error(t, err) tk.MustExec("drop user testCreateRole;") tk.MustExec("drop user test_create_role;") } func TestTransaction(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("begin") ctx := tk.Session() require.True(t, inTxn(ctx)) tk.MustExec("commit") require.False(t, inTxn(ctx)) tk.MustExec("begin") require.True(t, inTxn(ctx)) tk.MustExec("rollback") require.False(t, inTxn(ctx)) // Test that begin implicitly commits previous transaction. tk.MustExec("use test") tk.MustExec("create table txn (a int)") tk.MustExec("begin") tk.MustExec("insert txn values (1)") tk.MustExec("begin") tk.MustExec("rollback") tk.MustQuery("select * from txn").Check(testkit.Rows("1")) // Test that DDL implicitly commits previous transaction. tk.MustExec("begin") tk.MustExec("insert txn values (2)") tk.MustExec("create table txn2 (a int)") tk.MustExec("rollback") tk.MustQuery("select * from txn").Check(testkit.Rows("1", "2")) } func inTxn(ctx sessionctx.Context) bool { return (ctx.GetSessionVars().Status & mysql.ServerStatusInTrans) > 0 } func TestIssue33144(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) //Create role tk.MustExec("create role 'r1' ;") sessionVars := tk.Session().GetSessionVars() sessionVars.User = &auth.UserIdentity{Username: "root", Hostname: "localhost", AuthUsername: "root", AuthHostname: "%"} //Grant role to current_user() tk.MustExec("grant 'r1' to current_user();") //Revoke role from current_user() tk.MustExec("revoke 'r1' from current_user();") //Grant role to current_user(),current_user() tk.MustExec("grant 'r1' to current_user(),current_user();") //Revoke role from current_user(),current_user() tk.MustExec("revoke 'r1' from current_user(),current_user();") //Drop role tk.MustExec("drop role 'r1' ;") } func TestRole(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) // Make sure user test not in mysql.User. result := tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test" and Host="localhost"`) result.Check(nil) // Test for DROP ROLE. createRoleSQL := `CREATE ROLE 'test'@'localhost';` tk.MustExec(createRoleSQL) // Make sure user test in mysql.User. result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword(""))) // Insert relation into mysql.role_edges tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('localhost','test','%','root')") tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('localhost','test1','localhost','test1')") // Insert relation into mysql.default_roles tk.MustExec("insert into mysql.default_roles (HOST,USER,DEFAULT_ROLE_HOST,DEFAULT_ROLE_USER) values ('%','root','localhost','test')") tk.MustExec("insert into mysql.default_roles (HOST,USER,DEFAULT_ROLE_HOST,DEFAULT_ROLE_USER) values ('localhost','test','%','test1')") dropUserSQL := `DROP ROLE IF EXISTS 'test'@'localhost' ;` err := tk.ExecToErr(dropUserSQL) require.NoError(t, err) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test" and Host="localhost"`) result.Check(nil) result = tk.MustQuery(`SELECT * FROM mysql.role_edges WHERE TO_USER="test" and TO_HOST="localhost"`) result.Check(nil) result = tk.MustQuery(`SELECT * FROM mysql.role_edges WHERE FROM_USER="test" and FROM_HOST="localhost"`) result.Check(nil) result = tk.MustQuery(`SELECT * FROM mysql.default_roles WHERE USER="test" and HOST="localhost"`) result.Check(nil) result = tk.MustQuery(`SELECT * FROM mysql.default_roles WHERE DEFAULT_ROLE_USER="test" and DEFAULT_ROLE_HOST="localhost"`) result.Check(nil) // Test for GRANT ROLE createRoleSQL = `CREATE ROLE 'r_1'@'localhost', 'r_2'@'localhost', 'r_3'@'localhost';` tk.MustExec(createRoleSQL) grantRoleSQL := `GRANT 'r_1'@'localhost' TO 'r_2'@'localhost';` tk.MustExec(grantRoleSQL) result = tk.MustQuery(`SELECT TO_USER FROM mysql.role_edges WHERE FROM_USER="r_1" and FROM_HOST="localhost"`) result.Check(testkit.Rows("r_2")) grantRoleSQL = `GRANT 'r_1'@'localhost' TO 'r_3'@'localhost', 'r_4'@'localhost';` err = tk.ExecToErr(grantRoleSQL) require.Error(t, err) // Test grant role for current_user(); sessionVars := tk.Session().GetSessionVars() originUser := sessionVars.User sessionVars.User = &auth.UserIdentity{Username: "root", Hostname: "localhost", AuthUsername: "root", AuthHostname: "%"} tk.MustExec("grant 'r_1'@'localhost' to current_user();") tk.MustExec("revoke 'r_1'@'localhost' from 'root'@'%';") sessionVars.User = originUser result = tk.MustQuery(`SELECT FROM_USER FROM mysql.role_edges WHERE TO_USER="r_3" and TO_HOST="localhost"`) result.Check(nil) dropRoleSQL := `DROP ROLE IF EXISTS 'r_1'@'localhost' ;` tk.MustExec(dropRoleSQL) dropRoleSQL = `DROP ROLE IF EXISTS 'r_2'@'localhost' ;` tk.MustExec(dropRoleSQL) dropRoleSQL = `DROP ROLE IF EXISTS 'r_3'@'localhost' ;` tk.MustExec(dropRoleSQL) // Test for revoke role createRoleSQL = `CREATE ROLE 'test'@'localhost', r_1, r_2;` tk.MustExec(createRoleSQL) tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('localhost','test','%','root')") tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('%','r_1','%','root')") tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('%','r_2','%','root')") tk.MustExec("flush privileges") tk.MustExec("SET DEFAULT ROLE r_1, r_2 TO root") err = tk.ExecToErr("revoke test@localhost, r_1 from root;") require.NoError(t, err) err = tk.ExecToErr("revoke `r_2`@`%` from root, u_2;") require.Error(t, err) err = tk.ExecToErr("revoke `r_2`@`%` from root;") require.NoError(t, err) err = tk.ExecToErr("revoke `r_1`@`%` from root;") require.NoError(t, err) result = tk.MustQuery(`SELECT * FROM mysql.default_roles WHERE DEFAULT_ROLE_USER="test" and DEFAULT_ROLE_HOST="localhost"`) result.Check(nil) result = tk.MustQuery(`SELECT * FROM mysql.default_roles WHERE USER="root" and HOST="%"`) result.Check(nil) dropRoleSQL = `DROP ROLE 'test'@'localhost', r_1, r_2;` tk.MustExec(dropRoleSQL) ctx := tk.Session().(sessionctx.Context) ctx.GetSessionVars().User = &auth.UserIdentity{Username: "test1", Hostname: "localhost"} require.NotNil(t, tk.ExecToErr("SET ROLE role1, role2")) tk.MustExec("SET ROLE ALL") tk.MustExec("SET ROLE ALL EXCEPT role1, role2") tk.MustExec("SET ROLE DEFAULT") tk.MustExec("SET ROLE NONE") } func TestRoleAdmin(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("CREATE USER 'testRoleAdmin';") tk.MustExec("CREATE ROLE 'targetRole';") // Create a new session. se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testRoleAdmin", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "GRANT `targetRole` TO `testRoleAdmin`;") require.Error(t, err) tk.MustExec("GRANT SUPER ON *.* TO `testRoleAdmin`;") _, err = se.Execute(ctx, "GRANT `targetRole` TO `testRoleAdmin`;") require.NoError(t, err) _, err = se.Execute(ctx, "REVOKE `targetRole` FROM `testRoleAdmin`;") require.NoError(t, err) tk.MustExec("DROP USER 'testRoleAdmin';") tk.MustExec("DROP ROLE 'targetRole';") } func TestDefaultRole(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) createRoleSQL := `CREATE ROLE r_1, r_2, r_3, u_1;` tk.MustExec(createRoleSQL) tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('%','r_1','%','u_1')") tk.MustExec("insert into mysql.role_edges (FROM_HOST,FROM_USER,TO_HOST,TO_USER) values ('%','r_2','%','u_1')") tk.MustExec("flush privileges;") setRoleSQL := `SET DEFAULT ROLE r_3 TO u_1;` err := tk.ExecToErr(setRoleSQL) require.Error(t, err) setRoleSQL = `SET DEFAULT ROLE r_1 TO u_1000;` err = tk.ExecToErr(setRoleSQL) require.Error(t, err) setRoleSQL = `SET DEFAULT ROLE r_1, r_3 TO u_1;` err = tk.ExecToErr(setRoleSQL) require.Error(t, err) setRoleSQL = `SET DEFAULT ROLE r_1 TO u_1;` err = tk.ExecToErr(setRoleSQL) require.NoError(t, err) result := tk.MustQuery(`SELECT DEFAULT_ROLE_USER FROM mysql.default_roles WHERE USER="u_1"`) result.Check(testkit.Rows("r_1")) setRoleSQL = `SET DEFAULT ROLE r_2 TO u_1;` err = tk.ExecToErr(setRoleSQL) require.NoError(t, err) result = tk.MustQuery(`SELECT DEFAULT_ROLE_USER FROM mysql.default_roles WHERE USER="u_1"`) result.Check(testkit.Rows("r_2")) setRoleSQL = `SET DEFAULT ROLE ALL TO u_1;` err = tk.ExecToErr(setRoleSQL) require.NoError(t, err) result = tk.MustQuery(`SELECT DEFAULT_ROLE_USER FROM mysql.default_roles WHERE USER="u_1"`) result.Check(testkit.Rows("r_1", "r_2")) setRoleSQL = `SET DEFAULT ROLE NONE TO u_1;` err = tk.ExecToErr(setRoleSQL) require.NoError(t, err) result = tk.MustQuery(`SELECT DEFAULT_ROLE_USER FROM mysql.default_roles WHERE USER="u_1"`) result.Check(nil) dropRoleSQL := `DROP USER r_1, r_2, r_3, u_1;` tk.MustExec(dropRoleSQL) } func TestSetDefaultRoleAll(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("create user test_all;") se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "test_all", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "set default role all to test_all;") require.NoError(t, err) } func TestUser(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) // Make sure user test not in mysql.User. result := tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test" and Host="localhost"`) result.Check(nil) // Create user test. createUserSQL := `CREATE USER 'test'@'localhost' IDENTIFIED BY '123';` tk.MustExec(createUserSQL) // Make sure user test in mysql.User. result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("123"))) // Create duplicate user with IfNotExists will be success. createUserSQL = `CREATE USER IF NOT EXISTS 'test'@'localhost' IDENTIFIED BY '123';` tk.MustExec(createUserSQL) // Create duplicate user without IfNotExists will cause error. createUserSQL = `CREATE USER 'test'@'localhost' IDENTIFIED BY '123';` tk.MustGetErrCode(createUserSQL, mysql.ErrCannotUser) createUserSQL = `CREATE USER IF NOT EXISTS 'test'@'localhost' IDENTIFIED BY '123';` tk.MustExec(createUserSQL) tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Note|3163|User 'test'@'localhost' already exists.")) dropUserSQL := `DROP USER IF EXISTS 'test'@'localhost' ;` tk.MustExec(dropUserSQL) // Create user test. createUserSQL = `CREATE USER 'test1'@'localhost';` tk.MustExec(createUserSQL) // Make sure user test in mysql.User. result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test1" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword(""))) dropUserSQL = `DROP USER IF EXISTS 'test1'@'localhost' ;` tk.MustExec(dropUserSQL) // Test create/alter user with `tidb_auth_token` tk.MustExec(`CREATE USER token_user IDENTIFIED WITH 'tidb_auth_token' REQUIRE token_issuer 'issuer-abc'`) tk.MustQuery(`SELECT plugin, token_issuer FROM mysql.user WHERE user = 'token_user'`).Check(testkit.Rows("tidb_auth_token issuer-abc")) tk.MustExec(`ALTER USER token_user REQUIRE token_issuer 'issuer-123'`) tk.MustQuery(`SELECT plugin, token_issuer FROM mysql.user WHERE user = 'token_user'`).Check(testkit.Rows("tidb_auth_token issuer-123")) tk.MustExec(`ALTER USER token_user IDENTIFIED WITH 'tidb_auth_token'`) tk.MustExec(`CREATE USER token_user1 IDENTIFIED WITH 'tidb_auth_token'`) tk.MustQuery(`show warnings`).Check(testkit.RowsWithSep("|", "Warning|1105|TOKEN_ISSUER is needed for 'tidb_auth_token' user, please use 'alter user' to declare it")) tk.MustExec(`CREATE USER temp_user IDENTIFIED WITH 'mysql_native_password' BY '1234' REQUIRE token_issuer 'issuer-abc'`) tk.MustQuery(`show warnings`).Check(testkit.RowsWithSep("|", "Warning|1105|TOKEN_ISSUER is not needed for 'mysql_native_password' user")) tk.MustExec(`ALTER USER temp_user IDENTIFIED WITH 'tidb_auth_token' REQUIRE token_issuer 'issuer-abc'`) tk.MustQuery(`show warnings`).Check(testkit.Rows()) tk.MustExec(`ALTER USER temp_user IDENTIFIED WITH 'mysql_native_password' REQUIRE token_issuer 'issuer-abc'`) tk.MustQuery(`show warnings`).Check(testkit.RowsWithSep("|", "Warning|1105|TOKEN_ISSUER is not needed for the auth plugin")) tk.MustExec(`ALTER USER temp_user IDENTIFIED WITH 'tidb_auth_token'`) tk.MustQuery(`show warnings`).Check(testkit.RowsWithSep("|", "Warning|1105|Auth plugin 'tidb_auth_plugin' needs TOKEN_ISSUER")) tk.MustExec(`ALTER USER token_user REQUIRE SSL`) tk.MustQuery(`show warnings`).Check(testkit.Rows()) tk.MustExec(`ALTER USER token_user IDENTIFIED WITH 'mysql_native_password' BY '1234'`) tk.MustQuery(`show warnings`).Check(testkit.Rows()) tk.MustExec(`ALTER USER token_user IDENTIFIED WITH 'tidb_auth_token' REQUIRE token_issuer 'issuer-abc'`) tk.MustQuery(`show warnings`).Check(testkit.Rows()) // Test alter user. createUserSQL = `CREATE USER 'test1'@'localhost' IDENTIFIED BY '123', 'test2'@'localhost' IDENTIFIED BY '123', 'test3'@'localhost' IDENTIFIED BY '123', 'test4'@'localhost' IDENTIFIED BY '123';` tk.MustExec(createUserSQL) alterUserSQL := `ALTER USER 'test1'@'localhost' IDENTIFIED BY '111';` tk.MustExec(alterUserSQL) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test1" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("111"))) alterUserSQL = `ALTER USER 'test_not_exist'@'localhost' IDENTIFIED BY '111';` tk.MustGetErrCode(alterUserSQL, mysql.ErrCannotUser) alterUserSQL = `ALTER USER 'test1'@'localhost' IDENTIFIED BY '222', 'test_not_exist'@'localhost' IDENTIFIED BY '111';` tk.MustGetErrCode(alterUserSQL, mysql.ErrCannotUser) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test1" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("111"))) alterUserSQL = `ALTER USER 'test4'@'localhost' IDENTIFIED WITH 'auth_socket';` tk.MustExec(alterUserSQL) result = tk.MustQuery(`SELECT plugin FROM mysql.User WHERE User="test4" and Host="localhost"`) result.Check(testkit.Rows("auth_socket")) alterUserSQL = `ALTER USER IF EXISTS 'test2'@'localhost' IDENTIFIED BY '222', 'test_not_exist'@'localhost' IDENTIFIED BY '1';` tk.MustExec(alterUserSQL) tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Note|3162|User 'test_not_exist'@'localhost' does not exist.")) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test2" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("222"))) alterUserSQL = `ALTER USER IF EXISTS'test_not_exist'@'localhost' IDENTIFIED BY '1', 'test3'@'localhost' IDENTIFIED BY '333';` tk.MustExec(alterUserSQL) tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Note|3162|User 'test_not_exist'@'localhost' does not exist.")) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test3" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("333"))) // Test alter user user(). alterUserSQL = `ALTER USER USER() IDENTIFIED BY '1';` err := tk.ExecToErr(alterUserSQL) require.Truef(t, terror.ErrorEqual(err, errors.New("Session user is empty")), "err %v", err) sess, err := session.CreateSession4Test(store) require.NoError(t, err) tk.SetSession(sess) ctx := tk.Session().(sessionctx.Context) ctx.GetSessionVars().User = &auth.UserIdentity{Username: "test1", Hostname: "localhost", AuthHostname: "localhost"} tk.MustExec(alterUserSQL) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="test1" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("1"))) dropUserSQL = `DROP USER 'test1'@'localhost', 'test2'@'localhost', 'test3'@'localhost';` tk.MustExec(dropUserSQL) // Test drop user if exists. createUserSQL = `CREATE USER 'test1'@'localhost', 'test3'@'localhost';` tk.MustExec(createUserSQL) dropUserSQL = `DROP USER IF EXISTS 'test1'@'localhost', 'test2'@'localhost', 'test3'@'localhost' ;` tk.MustExec(dropUserSQL) tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Note|3162|User test2@localhost does not exist.")) // Test negative cases without IF EXISTS. createUserSQL = `CREATE USER 'test1'@'localhost', 'test3'@'localhost';` tk.MustExec(createUserSQL) dropUserSQL = `DROP USER 'test1'@'localhost', 'test2'@'localhost', 'test3'@'localhost';` tk.MustGetErrCode(dropUserSQL, mysql.ErrCannotUser) dropUserSQL = `DROP USER 'test3'@'localhost';` tk.MustExec(dropUserSQL) dropUserSQL = `DROP USER 'test1'@'localhost';` tk.MustExec(dropUserSQL) // Test positive cases without IF EXISTS. createUserSQL = `CREATE USER 'test1'@'localhost', 'test3'@'localhost';` tk.MustExec(createUserSQL) dropUserSQL = `DROP USER 'test1'@'localhost', 'test3'@'localhost';` tk.MustExec(dropUserSQL) // Test 'identified by password' createUserSQL = `CREATE USER 'test1'@'localhost' identified by password 'xxx';` err = tk.ExecToErr(createUserSQL) require.Truef(t, terror.ErrorEqual(exeerrors.ErrPasswordFormat, err), "err %v", err) createUserSQL = `CREATE USER 'test1'@'localhost' identified by password '*3D56A309CD04FA2EEF181462E59011F075C89548';` tk.MustExec(createUserSQL) dropUserSQL = `DROP USER 'test1'@'localhost';` tk.MustExec(dropUserSQL) // Test drop user meet error err = tk.ExecToErr(dropUserSQL) require.Truef(t, terror.ErrorEqual(err, exeerrors.ErrCannotUser.GenWithStackByArgs("DROP USER", "")), "err %v", err) createUserSQL = `CREATE USER 'test1'@'localhost'` tk.MustExec(createUserSQL) createUserSQL = `CREATE USER 'test2'@'localhost'` tk.MustExec(createUserSQL) dropUserSQL = `DROP USER 'test1'@'localhost', 'test2'@'localhost', 'test3'@'localhost';` err = tk.ExecToErr(dropUserSQL) require.Truef(t, terror.ErrorEqual(err, exeerrors.ErrCannotUser.GenWithStackByArgs("DROP USER", "")), "err %v", err) // Close issue #17639 dropUserSQL = `DROP USER if exists test3@'%'` tk.MustExec(dropUserSQL) createUserSQL = `create user test3@'%' IDENTIFIED WITH 'mysql_native_password' AS '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';` tk.MustExec(createUserSQL) querySQL := `select authentication_string from mysql.user where user="test3" ;` tk.MustQuery(querySQL).Check(testkit.Rows("*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9")) alterUserSQL = `alter user test3@'%' IDENTIFIED WITH 'mysql_native_password' AS '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';` tk.MustExec(alterUserSQL) tk.MustQuery(querySQL).Check(testkit.Rows("*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9")) createUserSQL = `create user userA@LOCALHOST;` tk.MustExec(createUserSQL) querySQL = `select user,host from mysql.user where user = 'userA';` tk.MustQuery(querySQL).Check(testkit.Rows("userA localhost")) createUserSQL = `create user userB@DEMO.com;` tk.MustExec(createUserSQL) querySQL = `select user,host from mysql.user where user = 'userB';` tk.MustQuery(querySQL).Check(testkit.Rows("userB demo.com")) createUserSQL = `create user userC@localhost;` tk.MustExec(createUserSQL) renameUserSQL := `rename user 'userC'@'localhost' to 'userD'@'Demo.com';` tk.MustExec(renameUserSQL) querySQL = `select user,host from mysql.user where user = 'userD';` tk.MustQuery(querySQL).Check(testkit.Rows("userD demo.com")) createUserSQL = `create user foo@localhost identified with 'foobar';` err = tk.ExecToErr(createUserSQL) require.Truef(t, terror.ErrorEqual(err, exeerrors.ErrPluginIsNotLoaded), "err %v", err) tk.MustExec(`create user joan;`) tk.MustExec(`create user sally;`) tk.MustExec(`create role engineering;`) tk.MustExec(`create role consultants;`) tk.MustExec(`create role qa;`) tk.MustExec(`grant engineering to joan;`) tk.MustExec(`grant engineering to sally;`) tk.MustExec(`grant engineering, consultants to joan, sally;`) tk.MustExec(`grant qa to consultants;`) tk.MustExec("CREATE ROLE `engineering`@`US`;") tk.MustExec("create role `engineering`@`INDIA`;") tk.MustExec("grant `engineering`@`US` TO `engineering`@`INDIA`;") tk.MustQuery("select user,host from mysql.user where user='engineering' and host = 'india'"). Check(testkit.Rows("engineering india")) tk.MustQuery("select user,host from mysql.user where user='engineering' and host = 'us'"). Check(testkit.Rows("engineering us")) tk.MustExec("drop role engineering@INDIA;") tk.MustExec("drop role engineering@US;") tk.MustQuery("select user from mysql.user where user='engineering' and host = 'india'").Check(testkit.Rows()) tk.MustQuery("select user from mysql.user where user='engineering' and host = 'us'").Check(testkit.Rows()) } func TestSetPwd(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) createUserSQL := `CREATE USER 'testpwd'@'localhost' IDENTIFIED BY '';` tk.MustExec(createUserSQL) result := tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="testpwd" and Host="localhost"`) result.Check(testkit.Rows("")) // set password for tk.MustExec(`SET PASSWORD FOR 'testpwd'@'localhost' = 'password';`) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="testpwd" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("password"))) tk.MustExec(`CREATE USER 'testpwdsock'@'localhost' IDENTIFIED WITH 'auth_socket';`) tk.MustExec(`SET PASSWORD FOR 'testpwdsock'@'localhost' = 'password';`) result = tk.MustQuery("show warnings") result.Check(testkit.Rows("Note 1699 SET PASSWORD has no significance for user 'testpwdsock'@'localhost' as authentication plugin does not support it.")) // set password setPwdSQL := `SET PASSWORD = 'pwd'` // Session user is empty. err := tk.ExecToErr(setPwdSQL) require.Error(t, err) sess, err := session.CreateSession4Test(store) require.NoError(t, err) tk.SetSession(sess) ctx := tk.Session().(sessionctx.Context) ctx.GetSessionVars().User = &auth.UserIdentity{Username: "testpwd1", Hostname: "localhost", AuthUsername: "testpwd1", AuthHostname: "localhost"} // Session user doesn't exist. err = tk.ExecToErr(setPwdSQL) require.Truef(t, terror.ErrorEqual(err, exeerrors.ErrPasswordNoMatch), "err %v", err) // normal ctx.GetSessionVars().User = &auth.UserIdentity{Username: "testpwd", Hostname: "localhost", AuthUsername: "testpwd", AuthHostname: "localhost"} tk.MustExec(setPwdSQL) result = tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="testpwd" and Host="localhost"`) result.Check(testkit.Rows(auth.EncodePassword("pwd"))) } func TestFlushPrivileges(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec(`CREATE USER 'testflush'@'localhost' IDENTIFIED BY '';`) tk.MustExec(`UPDATE mysql.User SET Select_priv='Y' WHERE User="testflush" and Host="localhost"`) // Create a new session. se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testflush", Hostname: "localhost"}, nil, nil, nil)) ctx := context.Background() // Before flush. _, err = se.Execute(ctx, `SELECT authentication_string FROM mysql.User WHERE User="testflush" and Host="localhost"`) require.Error(t, err) tk.MustExec("FLUSH PRIVILEGES") // After flush. _, err = se.Execute(ctx, `SELECT authentication_string FROM mysql.User WHERE User="testflush" and Host="localhost"`) require.NoError(t, err) } func TestFlushPrivilegesPanic(t *testing.T) { defer view.Stop() // Run in a separate suite because this test need to set SkipGrantTable config. store, err := mockstore.NewMockStore() require.NoError(t, err) defer func() { err := store.Close() require.NoError(t, err) }() defer config.RestoreFunc()() config.UpdateGlobal(func(conf *config.Config) { conf.Security.SkipGrantTable = true }) dom, err := session.BootstrapSession(store) require.NoError(t, err) defer dom.Close() tk := testkit.NewTestKit(t, store) tk.MustExec("FLUSH PRIVILEGES") } func TestDropPartitionStats(t *testing.T) { store, dom := testkit.CreateMockStoreAndDomain(t) // Use the testSerialSuite to fix the unstable test tk := testkit.NewTestKit(t, store) tk.MustExec(`create database if not exists test_drop_gstats`) tk.MustExec("use test_drop_gstats") tk.MustExec("drop table if exists test_drop_gstats;") tk.MustExec(`create table test_drop_gstats ( a int, key(a) ) partition by range (a) ( partition p0 values less than (10), partition p1 values less than (20), partition global values less than (30) )`) tk.MustExec("set @@tidb_analyze_version = 2") tk.MustExec("set @@tidb_partition_prune_mode='dynamic'") tk.MustExec("insert into test_drop_gstats values (1), (5), (11), (15), (21), (25)") require.Nil(t, dom.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)) checkPartitionStats := func(names ...string) { rs := tk.MustQuery("show stats_meta").Rows() require.Equal(t, len(names), len(rs)) for i := range names { require.Equal(t, names[i], rs[i][2].(string)) } } tk.MustExec("analyze table test_drop_gstats") checkPartitionStats("global", "p0", "p1", "global") tk.MustExec("drop stats test_drop_gstats partition p0") tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Warning|1681|'DROP STATS ... PARTITION ...' is deprecated and will be removed in a future release.")) checkPartitionStats("global", "p1", "global") err := tk.ExecToErr("drop stats test_drop_gstats partition abcde") require.Error(t, err) require.Equal(t, "can not found the specified partition name abcde in the table definition", err.Error()) tk.MustExec("drop stats test_drop_gstats partition global") checkPartitionStats("global", "p1") tk.MustExec("drop stats test_drop_gstats global") tk.MustQuery("show warnings").Check(testkit.RowsWithSep("|", "Warning|1287|'DROP STATS ... GLOBAL' is deprecated and will be removed in a future release. Please use DROP STATS ... instead")) checkPartitionStats("p1") tk.MustExec("analyze table test_drop_gstats") checkPartitionStats("global", "p0", "p1", "global") tk.MustExec("drop stats test_drop_gstats partition p0, p1, global") checkPartitionStats("global") tk.MustExec("analyze table test_drop_gstats") checkPartitionStats("global", "p0", "p1", "global") tk.MustExec("drop stats test_drop_gstats") checkPartitionStats() } func TestDropStats(t *testing.T) { store, dom := testkit.CreateMockStoreAndDomain(t) testKit := testkit.NewTestKit(t, store) testKit.MustExec("use test") testKit.MustExec("create table t (c1 int, c2 int)") is := dom.InfoSchema() tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t")) require.NoError(t, err) tableInfo := tbl.Meta() h := dom.StatsHandle() h.Clear() testKit.MustExec("analyze table t") statsTbl := h.GetTableStats(tableInfo) require.False(t, statsTbl.Pseudo) testKit.MustExec("drop stats t") require.Nil(t, h.Update(is)) statsTbl = h.GetTableStats(tableInfo) require.True(t, statsTbl.Pseudo) testKit.MustExec("analyze table t") statsTbl = h.GetTableStats(tableInfo) require.False(t, statsTbl.Pseudo) h.SetLease(1) testKit.MustExec("drop stats t") require.Nil(t, h.Update(is)) statsTbl = h.GetTableStats(tableInfo) require.True(t, statsTbl.Pseudo) h.SetLease(0) } func TestDropStatsForMultipleTable(t *testing.T) { store, dom := testkit.CreateMockStoreAndDomain(t) testKit := testkit.NewTestKit(t, store) testKit.MustExec("use test") testKit.MustExec("create table t1 (c1 int, c2 int)") testKit.MustExec("create table t2 (c1 int, c2 int)") is := dom.InfoSchema() tbl1, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t1")) require.NoError(t, err) tableInfo1 := tbl1.Meta() tbl2, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t2")) require.NoError(t, err) tableInfo2 := tbl2.Meta() h := dom.StatsHandle() h.Clear() testKit.MustExec("analyze table t1, t2") statsTbl1 := h.GetTableStats(tableInfo1) require.False(t, statsTbl1.Pseudo) statsTbl2 := h.GetTableStats(tableInfo2) require.False(t, statsTbl2.Pseudo) testKit.MustExec("drop stats t1, t2") require.Nil(t, h.Update(is)) statsTbl1 = h.GetTableStats(tableInfo1) require.True(t, statsTbl1.Pseudo) statsTbl2 = h.GetTableStats(tableInfo2) require.True(t, statsTbl2.Pseudo) testKit.MustExec("analyze table t1, t2") statsTbl1 = h.GetTableStats(tableInfo1) require.False(t, statsTbl1.Pseudo) statsTbl2 = h.GetTableStats(tableInfo2) require.False(t, statsTbl2.Pseudo) h.SetLease(1) testKit.MustExec("drop stats t1, t2") require.Nil(t, h.Update(is)) statsTbl1 = h.GetTableStats(tableInfo1) require.True(t, statsTbl1.Pseudo) statsTbl2 = h.GetTableStats(tableInfo2) require.True(t, statsTbl2.Pseudo) h.SetLease(0) } func TestCreateUserWithLDAP(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("CREATE USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_simple AS 'uid=bob,ou=People,dc=example,dc=com'") tk.MustQuery("SELECT Host, User, authentication_string, plugin FROM mysql.User WHERE User = 'bob'").Check(testkit.Rows("localhost bob uid=bob,ou=People,dc=example,dc=com authentication_ldap_simple")) tk.MustExec("CREATE USER 'bob2'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob2,ou=People,dc=example,dc=com'") tk.MustQuery("SELECT Host, User, authentication_string, plugin FROM mysql.User WHERE User = 'bob2'").Check(testkit.Rows("localhost bob2 uid=bob2,ou=People,dc=example,dc=com authentication_ldap_sasl")) } func TestAlterUserWithLDAP(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) // case 1: alter from a LDAP user to LDAP user tk.MustExec("CREATE USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_simple AS 'uid=bob,ou=People,dc=example,dc=com'") tk.MustQuery("SELECT Host, User, authentication_string, plugin FROM mysql.User WHERE User = 'bob'").Check(testkit.Rows("localhost bob uid=bob,ou=People,dc=example,dc=com authentication_ldap_simple")) tk.MustExec("ALTER USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob,ou=Manager,dc=example,dc=com'") tk.MustQuery("SELECT Host, User, authentication_string, plugin FROM mysql.User WHERE User = 'bob'").Check(testkit.Rows("localhost bob uid=bob,ou=Manager,dc=example,dc=com authentication_ldap_sasl")) // case 2: should ignore the password history tk.MustExec("ALTER USER 'bob'@'localhost' PASSWORD HISTORY 5\n") tk.MustExec("ALTER USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob,ou=People,dc=example,dc=com'") tk.MustExec("ALTER USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob,ou=Manager,dc=example,dc=com'") tk.MustExec("ALTER USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob,ou=People,dc=example,dc=com'") tk.MustExec("ALTER USER 'bob'@'localhost' IDENTIFIED WITH authentication_ldap_sasl AS 'uid=bob,ou=Manager,dc=example,dc=com'") } func TestIssue44098(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("set global validate_password.enable = 1") tk.MustExec("create user u1 identified with 'tidb_auth_token'") tk.MustExec("create user u2 identified with 'auth_socket'") tk.MustExec("create user u3 identified with 'authentication_ldap_simple'") tk.MustExec("create user u4 identified with 'authentication_ldap_sasl'") tk.MustGetErrCode("create user u5 identified with 'mysql_native_password'", errno.ErrNotValidPassword) tk.MustGetErrCode("create user u5 identified with 'caching_sha2_password'", errno.ErrNotValidPassword) tk.MustGetErrCode("create user u5 identified with 'tidb_sm3_password'", errno.ErrNotValidPassword) tk.MustGetErrCode("create user u5 identified with 'mysql_clear_password'", errno.ErrPluginIsNotLoaded) tk.MustGetErrCode("create user u5 identified with 'tidb_session_token'", errno.ErrPluginIsNotLoaded) }
/* 函数版学生管理系统 写一个系统能够查看\新增\删除学生 */ package main import ( "fmt" "os" ) type student struct { id int name string } func newStudent(id int, name string) *student { return &student{ id: id, name: name, } } var allstudent map[int]*student func judge(id int) bool { for k := range allstudent { if k == id { return false } } return true } func findall() { fmt.Println("学生系统的全部资料如下:") for k, v := range allstudent { fmt.Printf("学号:%d,姓名:%s\n", k, (*v).name) } } func addnew(id int, name string) { news := newStudent(id, name) allstudent[id] = news } func delold(id int) { delete(allstudent, id) } func main() { allstudent = make(map[int]*student, 50) for true { fmt.Println("欢迎进入学生管理系统!") fmt.Println(` 1.查看所有学生 2.新增学生 3.删除学生 4.退出 `) var choice int fmt.Print("请输入对应的操作号码:") fmt.Scanln(&choice) //fmt.Printf("您选择的操作号码是:%d\n", choice) switch choice { case 1: findall() case 2: var id int var name string fmt.Println("您好,您选择的是添加新的学生。") fmt.Print("请输入学生的学号:") fmt.Scanln(&id) fmt.Print("请输入学生的姓名:") fmt.Scanln(&name) if judge(id) { addnew(id, name) fmt.Println("学生已经新增成功!") } else { fmt.Println("您输入的学生学号已存在,没有进行任何操作!退回主界面") } case 3: var id int fmt.Println("您好,您选择的是删除学生。") fmt.Print("请输入学生的学号:") fmt.Scanln(&id) if !judge(id) { delold(id) } else { fmt.Println("您输入的学生学号不存在,没有进行任何操作!退回主界面") } case 4: os.Exit(1) } } }
package shardmaster import "raft" import "labrpc" import "sync" import ( "labgob" "time" "log" ) const Debug = 0 const ( JOIN = "JOIN" LEAVE = "LEAVE" MOVE = "MOVE" QUERY = "QUERY" ) func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } type Op struct { // Your data here. Method string Id int64 SeqNo int Servers map[int][]string // for join GIDs []int // for leave Shard int // for move GID int // for move Num int // for query } type ShardMaster struct { mu sync.Mutex me int rf *raft.Raft applyCh chan raft.ApplyMsg // Your data here. Duplicate map[int64]int configs []Config // indexed by config num waitChs map[int]chan Op } func (sm *ShardMaster) AppendOp(op Op) bool { sm.mu.Lock() index, _, isLeader := sm.rf.Start(op) if !isLeader { sm.mu.Unlock() return false } waitCh := make(chan Op, 1) sm.waitChs[index] = waitCh sm.mu.Unlock() select { case returnedOp := <- waitCh: if returnedOp.Id == op.Id && returnedOp.SeqNo == op.SeqNo { DPrintf("server is sure leader") return true } else { return false } case <- time.After(1000 * time.Millisecond): sm.mu.Lock() delete(sm.waitChs, index) sm.mu.Unlock() return false } } func (sm *ShardMaster) Join(args *JoinArgs, reply *JoinReply) { // Your code here. reply.Err = OK sm.mu.Lock() if hasDup := sm.checkDup(args.Id, args.SeqNo); hasDup { sm.mu.Unlock() reply.WrongLeader = false return } sm.mu.Unlock() op := Op{ Method:JOIN, Servers:args.Servers, Id:args.Id, SeqNo:args.SeqNo, } ok := sm.AppendOp(op) if ok { reply.WrongLeader = false } else { reply.WrongLeader = true } } func (sm *ShardMaster) Leave(args *LeaveArgs, reply *LeaveReply) { // Your code here. reply.Err = OK sm.mu.Lock() if hasDup := sm.checkDup(args.Id, args.SeqNo); hasDup { sm.mu.Unlock() reply.WrongLeader = false return } sm.mu.Unlock() op := Op{ Method:LEAVE, GIDs:args.GIDs, Id:args.Id, SeqNo:args.SeqNo, } ok := sm.AppendOp(op) if ok { reply.WrongLeader = false } else { reply.WrongLeader = true } } func (sm *ShardMaster) Move(args *MoveArgs, reply *MoveReply) { // Your code here. reply.Err = OK sm.mu.Lock() if hasDup := sm.checkDup(args.Id, args.SeqNo); hasDup { sm.mu.Unlock() reply.WrongLeader = false return } sm.mu.Unlock() op := Op{ Method:MOVE, Shard:args.Shard, GID:args.GID, Id:args.Id, SeqNo:args.SeqNo, } ok := sm.AppendOp(op) if ok { reply.WrongLeader = false } else { reply.WrongLeader = true } } func (sm *ShardMaster) Query(args *QueryArgs, reply *QueryReply) { // Your code here. op := Op{ Method:QUERY, Num:args.Num, Id:args.Id, SeqNo:args.SeqNo, } ok := sm.AppendOp(op) sm.mu.Lock() defer sm.mu.Unlock() if ok { num := op.Num if op.Num < 0 || op.Num >= len(sm.configs) { num = len(sm.configs) - 1 } reply.Config = sm.configs[num] reply.Err = OK reply.WrongLeader = false } else { reply.WrongLeader = true } } func (sm *ShardMaster) copyConfig(config *Config) Config { res := Config{} res.Num = config.Num res.Shards = config.Shards res.Groups = make(map[int][]string) for k, v := range config.Groups { res.Groups[k] = make([]string, len(v)) copy(res.Groups[k], v) } return res } func (sm *ShardMaster) checkDup(id int64, seqNo int) bool { if v, ok := sm.Duplicate[id]; ok && v >= seqNo { return true } return false } func (sm *ShardMaster) rebalance(config *Config) { if len(config.Groups) == 0 { return } avgLen := NShards / len(config.Groups) left := NShards - avgLen * len(config.Groups) shardsPerGroup := make(map[int][]int) // initialize a shards list for every valid gids for k := range config.Groups { shardsPerGroup[k] = make([]int,0) } for i, gid := range config.Shards { if list, ok := shardsPerGroup[gid]; ok { shardsPerGroup[gid] = append(list, i) } } extraShards := make([]int, 0) // cut extra shards of valid group copyLeft := left for gid, list := range shardsPerGroup { if len(list) > avgLen + 1 && copyLeft > 0 { extraShards = append(extraShards, list[len(list) - (avgLen + 1):]...) shardsPerGroup[gid] = list[:len(list) - (avgLen + 1)] copyLeft-- } else if len(list) > avgLen { extraShards = append(extraShards, list[len(list) - avgLen:]...) shardsPerGroup[gid] = list[:len(list) - avgLen] } } // collect shards of invalid group for s, gid := range config.Shards { if _, ok := config.Groups[gid]; !ok { extraShards = append(extraShards, s) } } //log.Printf("me %v, ave %v, left %v, nOfGroup %v, shardsPerGroup %v, extras %v", sm.me, avgLen, left, len(config.Groups), shardsPerGroup, extraShards) // fill to shardsPerGroup average for gid, list := range shardsPerGroup { //log.Printf("me %v, gid %v, length %v", sm.me, gid, len(list)) if len(list) < avgLen { shardsPerGroup[gid] = append(list, extraShards[len(extraShards) - (avgLen - len(list)):]...) extraShards = extraShards[:len(extraShards) - (avgLen - len(list))] } if len(shardsPerGroup[gid]) >= avgLen + 1 { left-- } //log.Printf("me %v, gid %v, shardsPerGroup %v", sm.me, gid, shardsPerGroup[gid]) } // fill shardsPerGroup left for gid, list := range shardsPerGroup { if left < 1 { break } if len(list) < avgLen + 1 { shardsPerGroup[gid] = append(list, extraShards[len(extraShards) - (avgLen + 1 - len(list)):]...) extraShards = extraShards[:len(extraShards) - (avgLen + 1 - len(list))] left-- } } // convert to Shard for gid, list := range shardsPerGroup { for _, s := range list { config.Shards[s] = gid } } } func (sm *ShardMaster) applyJoin(Servers map[int][]string) { newConfig := sm.copyConfig(&sm.configs[len(sm.configs) - 1]) newConfig.Num++ for k, v := range Servers { newConfig.Groups[k] = make([]string, len(v)) copy(newConfig.Groups[k], v) } sm.rebalance(&newConfig) sm.configs = append(sm.configs, newConfig) } func (sm *ShardMaster) applyLeave(GIDs []int) { newConfig := sm.copyConfig(&sm.configs[len(sm.configs) - 1]) newConfig.Num++ for _, gid := range GIDs { delete(newConfig.Groups, gid) } sm.rebalance(&newConfig) sm.configs = append(sm.configs, newConfig) } func (sm *ShardMaster) applyMove(Shard int, GID int) { newConfig := sm.copyConfig(&sm.configs[len(sm.configs) - 1]) newConfig.Num++ newConfig.Shards[Shard] = GID sm.configs = append(sm.configs, newConfig) } func (sm *ShardMaster) applyDaemon() { for { msg := <- sm.applyCh sm.mu.Lock() op := msg.Command.(Op) switch op.Method { case QUERY: case JOIN: if hasDup := sm.checkDup(op.Id, op.SeqNo); !hasDup { sm.applyJoin(op.Servers) } case MOVE: if hasDup := sm.checkDup(op.Id, op.SeqNo); !hasDup { sm.applyMove(op.Shard, op.GID) } case LEAVE: if hasDup := sm.checkDup(op.Id, op.SeqNo); !hasDup { sm.applyLeave(op.GIDs) } } if ch, ok := sm.waitChs[msg.CommandIndex]; ok{ select { case <-ch: default: } ch <- op delete(sm.waitChs, msg.CommandIndex) } sm.mu.Unlock() } } // // the tester calls Kill() when a ShardMaster instance won't // be needed again. you are not required to do anything // in Kill(), but it might be convenient to (for example) // turn off debug output from this instance. // func (sm *ShardMaster) Kill() { sm.rf.Kill() // Your code here, if desired. } // needed by shardkv tester func (sm *ShardMaster) Raft() *raft.Raft { return sm.rf } // // servers[] contains the ports of the set of // servers that will cooperate via Raft to // form the fault-tolerant shardmaster service. // me is the index of the current server in servers[]. // func StartServer(servers []*labrpc.ClientEnd, me int, persister *raft.Persister) *ShardMaster { sm := new(ShardMaster) sm.me = me sm.configs = make([]Config, 1) sm.configs[0].Groups = map[int][]string{} labgob.Register(Op{}) sm.applyCh = make(chan raft.ApplyMsg) sm.rf = raft.Make(servers, me, persister, sm.applyCh) // You may need initialization code here. sm.Duplicate = make(map[int64]int) sm.waitChs = make(map[int]chan Op) go sm.applyDaemon() return sm }
package main import ( "flag" "log" ) func main() { var ipAddress string var ports string var output string var wrkrs int flag.StringVar(&ipAddress, "ip", "127.0.0.1", "Specify IP Address to scan.") flag.StringVar(&ports, "ports", "1-1024", "Specify port range to perform scan. Allowed formats: 80 or 1-1024") flag.StringVar(&output, "output", "stdout", "Output format, available: stdout, csv, json") flag.IntVar(&wrkrs, "w", 8, "Amount of concurrent process scanning ports") flag.Parse() scanPorts, err := parsePorts(ports) if err != nil { log.Fatal(err) } pChann := make(chan int, wrkrs) openPorts := make(chan int) defer close(pChann) defer close(openPorts) for w := 0; w < cap(pChann); w++ { go scan(ipAddress, output, pChann, openPorts) // pass output param to store also closed ports } go populateChann(scanPorts, pChann) // start to populate pChann so scan method start for i := 0; i < len(scanPorts); i++ { if p := <-openPorts; p != 0 { writeOutput(output, ipAddress, "open", p) } } }
package onelogin // Object representing a single App description type OneLoginApp struct { Id int `json:"id"` Name string `json:"name"` Icon string `json:"icon"` Provisioned string `json:"provisioned"` Extension bool `json:"extension"` Login_id int32 `json:"login_id"` Personal bool `json:"personal"` } // Object representing an HTTP request body for verifying an OTP token. type VerifyTokenRequest struct { Device_id string `json:"device_id"` State_token string `json:"state_token"` Otp_token string `json:"otp_token"` } // Object representing an HTTP request body for verifying user credentials. type AuthenticationRequest struct { Username_or_email string `json:"username_or_email"` Password string `json:"password"` Subdomain string `json:"subdomain"` } type SetCustomAttributeRequest struct { Custom_Attributes map[string]string `json:"custom_attributes"` } // Object representing the pagination data for a request. type ResponsePagination struct { Before_cursor string `json:"before_cursor"` After_cursor string `json:"after_cursor"` Previous_link string `json:"previous_link"` Next_link string `json:"next_link"` } // Object representing the JSON response for a user authentication // request. type AuthResponse struct { Status ResponseStatus `json:"status"` Data []struct { State_token string `json:"state_token"` Devices []struct { Device_type string `json:"device_type"` Device_id int `json:"device_id"` } `json:devices` User struct { Lastname string `json:"lastname"` Username string `json:"username"` Email string `json:"email"` Id int `json:"id"` Firstname string `json:"firstname"` } `json:user` Callback_url string `json:"callback_url"` } `json:data` } // Object representing user data. type OneLoginUser struct { Activated_at string `json:"activated_at"` Created_at string `json:"created_at"` Email string `json:"email"` Username string `json:"username"` Firstname string `json:"firstname"` Group_id int `json:"group_id"` Id int `json:"id"` Invalid_login_attempts int `json:"invalid_login_attempts"` Invitation_sent_at string `json:"invitation_sent_at"` Last_login string `json:"last_login"` Lastname string `json:"lastname"` Locked_until string `json:"locked_until"` Notes string `json:"notes"` Openid_name string `json:"openid_name"` Locale_code string `json:"locale_code"` Password_changed_at string `json:"password_changed_at"` Phone string `json:"phone"` Status int `json:"status"` Updated_at string `json:"updated_at"` Distinguished_name string `json:"distinguished_name"` External_id int `json:'external_id'` Directory_id int `json:"directory_id"` Member_of []string `json:"member_of"` Samaccountname string `json:"samaccountname"` Userprincipalname string `json:"userprincipalname"` Manager_ad_id int `json:"manager_ad_id"` Role_id []int `json:"role_id"` Custom_attributes map[string]string `json:"custom_attributes"` } type OneLoginRole struct { Id int `json:"id"` Name string `json:"name,omitempty"` } // Object representing the result of a get user request. type GetUserResponse struct { Status ResponseStatus `json:"status"` Pagination ResponsePagination `json:"pagination"` Data []OneLoginUser `json:"data"` } // Object representing the result of a get user apps request. type GetUserAppsResponse struct { Status ResponseStatus `json:"status"` Pagination ResponsePagination `json:"pagination"` Data []OneLoginApp `json:"data"` } // Object representing the result of a get user roles request. type GetUserRolesResponse struct { Status ResponseStatus `json:"status"` Pagination ResponsePagination `json:"pagination"` Data []int `json:"data"` } // Object representing the result of a get user request. type GetRoleResponse struct { Status ResponseStatus `json:"status"` Pagination ResponsePagination `json:"pagination"` Data []OneLoginRole `json:"data"` }
package yandex import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "sync" "time" "strings" "gitgud.io/softashell/comfy-translator/config" "gitgud.io/softashell/comfy-translator/translator" log "github.com/sirupsen/logrus" ) const ( apiURL = "https://translate.yandex.net/api/v1.5/tr.json/translate" delay = time.Second ) type Translate struct { enabled bool client *http.Client lastRequest time.Time mutex *sync.Mutex apiKey string } type yandexResponse struct { Code int `json:"code"` Lang string `json:"lang"` Text []string `json:"text"` } func New() *Translate { return &Translate{ client: &http.Client{Timeout: (10 * time.Second)}, lastRequest: time.Now(), mutex: &sync.Mutex{}, } } func (t *Translate) Name() string { return "Yandex" } func (t *Translate) Start(c config.TranslatorConfig) error { t.apiKey = c.Key if len(t.apiKey) < 1 || !strings.HasPrefix(t.apiKey, "trnsl.") { return fmt.Errorf("%s: Invalid api key provided, edit comfy-translator.toml to disable or change key", t.Name()) } t.enabled = true return nil } func (t *Translate) Enabled() bool { return t.enabled } func (t *Translate) Translate(req *translator.Request) (string, error) { start := time.Now() t.mutex.Lock() translator.CheckThrottle(t.lastRequest, delay) defer t.mutex.Unlock() var URL *url.URL URL, err := url.Parse(apiURL) if err != nil { return "", err } parameters := url.Values{} parameters.Add("key", t.apiKey) parameters.Add("text", req.Text) parameters.Add("lang", req.From+"-"+req.To) parameters.Add("format", "plain") // https://tech.yandex.com/translate/doc/dg/reference/translate-docpage URL.RawQuery = parameters.Encode() r, err := http.NewRequest("POST", URL.String(), nil) if err != nil { log.Errorln("Failed to create request", err) return "", err } t.lastRequest = time.Now() resp, err := t.client.Do(r) if err != nil { log.Errorln("Failed to do request", err) return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("%s", resp.Status) } contents, err := ioutil.ReadAll(resp.Body) if err != nil { log.Error("Failed to read response body", err) return "", err } var response yandexResponse if err := json.Unmarshal(contents, &response); err != nil { log.Errorln("Failed to unmarshal JSON API response", err) return "", err } if len(response.Text) < 1 { return "", fmt.Errorf("Empty response") } else if len(response.Text) > 1 { log.Warningf("More than one item in response: %s", string(contents)) } var out string for i := range response.Text { out += response.Text[i] } log.WithFields(log.Fields{ "time": time.Since(start), }).Debugf("Yandex: %q", out) return out, nil }
package encryption_test import ( "github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models" "github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption" "gorm.io/driver/sqlite" "gorm.io/gorm" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ParseConfiguration()", func() { var db *gorm.DB BeforeEach(func() { var err error db, err = gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) Expect(err).NotTo(HaveOccurred()) Expect(db.Migrator().CreateTable(&models.PasswordMetadata{})).NotTo(HaveOccurred()) }) When("new primary password is different", func() { BeforeEach(func() { Expect(db.Create(&models.PasswordMetadata{ Label: "previous-primary", Salt: []byte("random-salt"), Canary: "test-value", Primary: true, }).Error).NotTo(HaveOccurred()) Expect(db.Create(&models.PasswordMetadata{ Label: "new-primary", Salt: []byte("other-random-salt"), Canary: "other-test-value", Primary: false, }).Error).NotTo(HaveOccurred()) }) It("swaps the primary flag", func() { err := encryption.UpdatePasswordMetadata(db, "new-primary") Expect(err).NotTo(HaveOccurred()) var oldPrimary models.PasswordMetadata Expect(db.Where("label = ?", "previous-primary").First(&oldPrimary).Error).NotTo(HaveOccurred()) Expect(oldPrimary.Primary).To(BeFalse()) var newPrimary models.PasswordMetadata Expect(db.Where("label = ?", "new-primary").First(&newPrimary).Error).NotTo(HaveOccurred()) Expect(newPrimary.Primary).To(BeTrue()) }) }) When("new primary password is the same as existing password", func() { BeforeEach(func() { Expect(db.Create(&models.PasswordMetadata{ Label: "primary", Salt: []byte("random-salt"), Canary: "test-value", Primary: true, }).Error).NotTo(HaveOccurred()) }) It("does not change the primary flag", func() { var beforePrimary models.PasswordMetadata Expect(db.Where("label = ?", "primary").First(&beforePrimary).Error).NotTo(HaveOccurred()) updateTime := beforePrimary.UpdatedAt err := encryption.UpdatePasswordMetadata(db, "primary") Expect(err).NotTo(HaveOccurred()) var primary models.PasswordMetadata Expect(db.Where("label = ?", "primary").First(&primary).Error).NotTo(HaveOccurred()) Expect(primary.Primary).To(BeTrue()) Expect(primary.UpdatedAt).To(Equal(updateTime)) }) }) When("there is no new primary password", func() { BeforeEach(func() { Expect(db.Create(&models.PasswordMetadata{ Label: "primary", Salt: []byte("random-salt"), Canary: "test-value", Primary: true, }).Error).NotTo(HaveOccurred()) }) When("new primary label is empty", func() { It("sets all existing primaries flags to false", func() { err := encryption.UpdatePasswordMetadata(db, "") Expect(err).NotTo(HaveOccurred()) var primary models.PasswordMetadata Expect(db.Where("label = ?", "primary").First(&primary).Error).NotTo(HaveOccurred()) Expect(primary.Primary).To(BeFalse()) }) }) }) When("new primary password cannot be found", func() { It("returns an error", func() { err := encryption.UpdatePasswordMetadata(db, "some-pass") Expect(err).To(MatchError("cannot find metadata for password labelled \"some-pass\"")) }) }) })
package main import ( "encoding/json" "fmt" "log" "net/http" "strings" "github.com/gorilla/mux" ) func booksCheckedIn(w http.ResponseWriter, r *http.Request) { type booksIn struct { Name string Book string } booksin := &booksIn{ Name: "Frank, Bob", Book: " Fault in Our Stars, The Hobbit", } b, _ := json.Marshal(booksin) s := string(b) open := strings.Replace(s, "{", "", -1) close := strings.Replace(open, "}", "", -1) fmt.Fprintln(w, string(close)) } func booksCheckedOut(w http.ResponseWriter, r *http.Request) { type booksOut struct { Name string Book string } booksOUT := &booksOut{ Name: "Betty Joe, Adam Sandler", Book: " To Kill a Mocking Bird, Who's Who?", } bo, _ := json.Marshal(booksOUT) s := string(bo) open := strings.Replace(s, "{", "", -1) close := strings.Replace(open, "}", "", -1) fmt.Fprintln(w, string(close)) } func booksAvailable(w http.ResponseWriter, r *http.Request) { type available struct { Author string Book string } booksav := &available{ Author: "J.K Rowling, Sandra Cisneros", Book: " Harry Potter, House on Mango Street", } av, _ := json.Marshal(booksav) s := string(av) open := strings.Replace(s, "{", "", -1) close := strings.Replace(open, "}", "", -1) fmt.Fprintln(w, string(close)) } func popularBooks(w http.ResponseWriter, r *http.Request) { type available struct { Author string Book string } pop := &available{ Author: "Suzanne Collins, Stephenie Meyer ", Book: " The Hunger Games, Twighlight", } bp, _ := json.Marshal(pop) s := string(bp) open := strings.Replace(s, "{", "", -1) close := strings.Replace(open, "}", "", -1) fmt.Fprintln(w, string(close)) } func message(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Welcome to Library by Brandon Jakobson. At the end of the URL, type /av for availability, /in for books checked in, /out for books checked out, or /pop for popular books!") } func Execute() { booksout := mux.NewRouter().StrictSlash(true) booksout.HandleFunc("/out", booksCheckedOut) booksout.HandleFunc("/in", booksCheckedIn) booksout.HandleFunc("/av", booksAvailable) booksout.HandleFunc("/pop", popularBooks) booksout.HandleFunc("/", message) log.Fatal(http.ListenAndServe(":8080", booksout)) } func main() { Execute() }
package goil import "testing" const studentListMinimumLength int = 0 func Test_GetStudentList(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } skipIfNoSession(t) studentList, err := session.GetStudentList() if err != nil { t.Fatal(err) } if len(studentList) <= studentListMinimumLength { t.Errorf("studentList length should at least be of %d but it is of %d", studentListMinimumLength, len(studentList)) } }
package saucenao import ( "fmt" "io/ioutil" "net/http" "net/url" "github.com/tidwall/gjson" ) type Result struct { Similarity float64 Thumbnail string PixivID int64 Title string ImageURL string MemberName string MemberID int64 } // SauceNaoSearch SauceNao 以图搜图 // 传入图片链接,返回P站结果 func SauceNAO(image string) (*Result, error) { var ( api = "https://saucenao.com/search.php" apiKey = "2cc2772ca550dbacb4c35731a79d341d1a143cb5" minSimilarity = 70.0 // 返回图片结果的最小相似度 ) // 包装请求参数 link, _ := url.Parse(api) link.RawQuery = url.Values{ "url": []string{image}, "api_key": []string{apiKey}, "db": []string{"5"}, "numres": []string{"1"}, "output_type": []string{"2"}, }.Encode() // 网络请求 client := &http.Client{} req, err := http.NewRequest("GET", link.String(), nil) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0") resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { // 如果返回不是200则立刻抛出错误 return nil, fmt.Errorf("SauceNAO not found, code %d", resp.StatusCode) } content := gjson.ParseBytes(body) if status := content.Get("header.status").Int(); status != 0 { // 如果json信息返回status不为0则立刻抛出错误 return nil, fmt.Errorf("SauceNAO not found, status %d", status) } if content.Get("results.0.header.similarity").Float() < minSimilarity { return nil, fmt.Errorf("SauceNAO not found") } temp := content.Get("results.0") result := &Result{ Similarity: temp.Get("header.similarity").Float(), Thumbnail: temp.Get("header.thumbnail").Str, PixivID: temp.Get("data.pixiv_id").Int(), Title: temp.Get("data.title").Str, ImageURL: temp.Get("data.ext_urls.0").Str, MemberName: temp.Get("data.member_name").Str, MemberID: temp.Get("data.member_id").Int(), } return result, nil }
package models import ( "time" "strconv" "encoding/json" "github.com/bitly/go-simplejson" "github.com/jetlwx/comm" "github.com/jetlwx/comm/httplib" ) //AppRes is 获取单个项目运行情况 func AppRes(app Applications) (a Alert) { body, err := info(app) if err != nil { comm.JetLog("E", err) return } js, err := simplejson.NewJson(body) if err != nil { comm.JetLog("E", err) return } linkData, err := js.Get("applicationMapData").Get("linkDataArray").Array() if err != nil { comm.JetLog("E", err) return } var tOne, tThree, tFive, tSlow, tError int64 for _, v := range linkData { v1, _ := json.Marshal(v) js2, err := simplejson.NewJson(v1) if err != nil { comm.JetLog("E", err) continue } r, err := js2.Get("histogram").Map() if err != nil { continue } if one, ok := r["1s"].(json.Number); ok { if o, err := one.Int64(); err == nil { tOne += o } } if three, ok := r["3s"].(json.Number); ok { if t, err := three.Int64(); err == nil { tThree += t } } if five, ok := r["5s"].(json.Number); ok { if f, err := five.Int64(); err == nil { tFive += f } } if slow, ok := r["Slow"].(json.Number); ok { if s, err := slow.Int64(); err == nil { tSlow += s } } if errn, ok := r["Error"].(json.Number); ok { if e, err := errn.Int64(); err == nil { tError += e } } } a.ApplicationName = app.ApplicationName a.TotalError = tError a.TotalFive = tFive a.TotalOne = tOne a.TotalSlow = tSlow a.TotalThree = tThree return a } ////http://192.168.107.60:28080/getServerMapData.pinpoint?applicationName=coa-im-message&from=1541757493000&to=1541757793000&callerRange=1&calleeRange=1&bidirectional=false&wasOnly=false&serviceTypeName=TOMCAT&_=1541758151830 //info is get an applicaton infomation body func info(app Applications) (body []byte, err error) { tnow := time.Now().Unix() * 1000 t5mago := tnow - int64(Minutes*60*1000) comm.JetLog("D", "Now=", tnow, Minutes, "ago=", t5mago) url := ServerURL + "/getServerMapData.pinpoint?applicationName=" + app.ApplicationName + "&" url += "from=" + strconv.FormatInt(t5mago, 10) + "&" url += "to=" + strconv.FormatInt(tnow, 10) + "&" url += "callerRange=1&calleeRange=1&bidirectional=false&wasOnly=false&" url += "serviceTypeName=" + app.ServiceType comm.JetLog("D", "url=", url) res := httplib.Get(url) resp, err := res.Response() if err != nil { comm.JetLog("E", err) return nil, err } if resp.StatusCode != 200 { comm.JetLog("E", "返回值;", resp.StatusCode) } body, err = res.Bytes() if err != nil { comm.JetLog("E", err) return nil, err } return }
package Oppg4 import ( "fmt" ) func main() { tekst := "tom" ExtendedASCIIText(tekst) const hexString = "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F" + "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF" + "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF" + "\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" IterateOverASCIIStringLiteral(hexString) } func IterateOverASCIIStringLiteral(hexString string) { for j := 0; j < len(hexString); j++ { fmt.Printf("%X\t %c\t %b\t \n", hexString[j], hexString[j], hexString[j]) } } func ExtendedASCIIText(s string) string { utskrift := []byte{0x22, 0x20, 0x80, 0x20, 0xF7, 0x20, 0xBE, 0x20, 0x64, 0x6F, 0x6C, 0x6C, 0x61, 0x72, 0x20, 0x22} print(utskrift) var nystring string for i:= 0; i < len(utskrift); i++ { if (utskrift[i] >= 128) && (utskrift[i] <= 255) { n := string(utskrift[i]) n = nystring + n } } return nystring } func print(utskrift []byte) { fmt.Printf("%c\n", utskrift) }
package main import ( "fmt" "learngo/interferce/mock" real2 "learngo/interferce/real" ) type Retiever interface { Get(url string) string } func download(r Retiever) string { return r.Get("http://www.imooc.com") } func main() { var r Retiever r = mock.Retiever{"this is a fake imooc.com"} r = real2.Retiever{} fmt.Println(download(r)) }
package nzgo // this is version of nzgo driver const nzgo_client_version = "11.0.0.0"
package util import ( "bytes" "io/ioutil" "os" ) func WriteIfChanged(filename string, data []byte, perm os.FileMode) (bool, error) { modified := false content, err := ioutil.ReadFile(filename) if !os.IsNotExist(err) && err != nil { // file existed, but could not be read return modified, err } if os.IsNotExist(err) || bytes.Compare(content, data) != 0 { openPerm := perm if perm == 0 { // if the file gets created with perm=0, then all the permission // bits will be turned off // a more sensible default is to use 0666 (and then umask gets // applied) openPerm = 0666 } modified = true err = ioutil.WriteFile(filename, data, openPerm) if err != nil { return modified, err } } if perm != 0 { info, err := os.Stat(filename) if err != nil { return modified, err } if info.Mode() != perm { modified = true err = os.Chmod(filename, perm) } } return modified, err }
package bootfromvolume func createURL(c *gophercloud.ServiceClient) string { return c.ServiceURL("os-volumes_boot") }
package banner /* 2020年10月29日完善 */ import ( "wx-gin-master/models" "wx-gin-master/pkg/logging" ) type Banner struct { models.Model Name string `json:"name"` // Banner名称 ImageUrl string `json:"image_url"` // 轮播图地址 RelateId int `json:"relate_id"` // 执行关键字,根据不同的type含义不同 JumpType int `json:"jump_type"` // 跳转类型 0,无导向;1:导向商品;2:导向专题 } func (Banner) TableName() string { return "banner" } // Create 创建新轮播 func CreateBanner(banner *Banner) bool { if models.DB.NewRecord(banner) { models.DB.Create(banner) if !models.DB.NewRecord(banner) { return true } } return false } // UpDate 更新轮播图 func UpdateBanner(date *Banner) bool { if date.ID == 0 { return false } banner := Banner{} models.DB.Where("id = ?", date.ID).First(&banner) if err := models.DB.Debug().Model(banner).Update(date).Error; err != nil { logging.Info(err) return false } return true } /* func UpdateRadio(newradio *Radio) bool { if newradio.ID == 0 { return false } radio := Radio{} models.DB.Where("id = ?", newradio.ID).First(&radio) if err := models.DB.Debug().Model(radio).Update(newradio); err != nil { logging.Info(err) return true } return false } */ // Destroy 根据id 删除轮播图 func DeleteBanner(id int) bool { models.DB.Model(&Banner{}).Where("id = ?", id).Update("del", 1) if err := models.DB.Debug().Delete(Banner{}, "id = ?", id).Error; err != nil { logging.Info(err) return false } return true } // List 返回num个轮播图 func ListBanner(num int) (banner []Banner, err error) { if err = models.DB.Debug().Order("modified_on DESC").Limit(num).Find(&banner).Error; err != nil { logging.Info(err) return } return }
package main const matrixRows = 16 const matrixCols = 10 func main() { // pf := NewPlayfield(matrixRows, matrixCols) } func loop() { }
/* * Copyright (C) 2017 Vikram Fugro * * * This software may be modified and distributed under the terms * of the MIT license. */ package main /* #cgo CFLAGS: -I../gst -I/usr/include/gstreamer-1.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/libsoup-2.4 -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/uuid -I/usr/include/gupnp-1.0 -I/usr/include/gssdp-1.0 -I/usr/include/libsoup-2.4 -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/uuid -I/usr/include/gupnp-av-1.0 -I/usr/include/gupnp-1.0 -I/usr/include/gssdp-1.0 -pthread -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gssdp-1.0 -I/usr/include/libxml2 -I/usr/lib/x86_64-linux-gnu/gstreamer-1.0/include/ #cgo LDFLAGS: -L/home/vikram/go/src/vfstream/gst/ -L/usr/lib/x86_64-linux-gnu -ltarget -lgstbase-1.0 -lgstreamer-1.0 -lgobject-2.0 -lglib-2.0 -lgupnp-1.0 -lgupnp-av-1.0 -lgssdp-1.0 -lxml2 -lpthread -lm -lz -licui18n -licuuc -licudata -llzma #include <GstSource.h> #include <Upnp.h> #include <stdlib.h> */ import "C" import ( "bufio" "encoding/json" "errors" "fmt" "net" "net/http" "net/textproto" "os" "strconv" "strings" "sync" "time" "unsafe" ) type state int const ( DOWN state = 0 + iota READY INIT RUN ) func (s state) toString() string { switch s { case DOWN: return "down" case READY: return "ready" case INIT: return "init" case RUN: return "run" } return "" } type dmr struct { Name string `json:"name"` Usn string `json:"usn"` } type dmrs struct { Len int `json:"len"` Dmrs []dmr `json:"dmrs"` } type storeS struct { status state device string pipeline *C.struct_GstSource then time.Time } func (f *storeS) Read(p []byte) (int, error) { read := int(C.getData(f.pipeline, (*C.char)(unsafe.Pointer(&p[0])), C.int(len(p)))) return read, nil } func (f *storeS) Seek(offset int64, whence int) (int64, error) { var crazyValue int64 crazyValue = (1 << 31) if whence == 2 { return crazyValue, nil } else if whence == 1 { return 0, nil } else { return 0, nil } } type db map[string]*storeS var mutex sync.Mutex func (s *db) lock() { mutex.Lock() } func (s *db) unlock() { mutex.Unlock() } var vid int var store db var devices map[string]state var hostIP string func getDMRs(w http.ResponseWriter, r *http.Request) { var ds dmrs var count C.int var cds *C.struct_Renderer var cdx C.struct_Renderer dms := make(map[string]bool) cds = C.up_scan(&count) store.lock() for i := 0; i < int(count); i++ { cdx = *(*C.struct_Renderer)(unsafe.Pointer((uintptr(unsafe.Pointer(cds)) + uintptr(i)*unsafe.Sizeof(cdx)))) ds.Dmrs = append(ds.Dmrs, dmr{C.GoString(&cdx.Name[0]), C.GoString(&cdx.Udn[0])}) dms[C.GoString(&cdx.Udn[0])] = true if devices[C.GoString(&cdx.Udn[0])] == DOWN { devices[C.GoString(&cdx.Udn[0])] = READY } } for key := range devices { if dms[key] != true { devices[key] = DOWN } } ds.Len = int(count) store.unlock() C.free(unsafe.Pointer(cds)) if w != nil { w.WriteHeader(200) w.Header().Add("Server", "A Go based HttpLiveMediaServer") w.Header().Set("Content-Type", "application/json") jData, _ := json.Marshal(ds) w.Write(jData) } } func getStatus(id string) state { store.lock() defer store.unlock() if store[id] == nil { return DOWN } return store[id].status } func setInit(device string, endpoint string) string { var ret C.int store.lock() defer store.unlock() vid++ id := strconv.Itoa(vid) if store[id] != nil { return "" } devices[device] = INIT store[id] = &storeS{ INIT, device, nil, time.Now(), } http.HandleFunc("/"+endpoint+id+".mp4", func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { w.Header().Set("Pragma", "no-cache") w.Header().Set("Cache-control", "no-cache") w.Header().Set("Accept-Ranges", "none") w.Header().Add("contentFeatures.dlna.org", "DLNA.ORG_PN=AVC_MP4_BL_CIF15_AAC_520;DLNA.ORG_OP=00;DLNA.ORG_CI=1;DLNA.ORG_FLAGS=05700000000000000000000000000000") w.Header().Add("transferMode.dlna.org", "Streaming") w.Header().Set("Content-Type", "video/mp4") //TESTVV fmt.Println("GOT HEAD!!!!!!") //w.Header().Add("EXT", "") //w.Header().Set("User-Agent", "HttpMediaServer/1.0") w.WriteHeader(200) } else if r.Method == "GET" { go func(c <-chan bool) { <-c setInactive(id) }(w.(http.CloseNotifier).CloseNotify()) go func() { dur := time.Since(store[id].then) if dur > 10*time.Second { fmt.Println("no health monitoring, closing ", id) setInactive(id) } }() w.Header().Set("Pragma", "no-cache") w.Header().Set("Cache-control", "no-cache") w.Header().Set("Accept-Ranges", "none") w.Header().Add("contentFeatures.dlna.org", "DLNA.ORG_PN=AVC_MP4_BL_CIF15_AAC_520;DLNA.ORG_OP=00;DLNA.ORG_CI=1;DLNA.ORG_FLAGS=05700000000000000000000000000000") w.Header().Add("transferMode.dlna.org", "Streaming") w.Header().Set("Content-Type", "video/mp4") //TESTVV fmt.Println("Got GETTT") //w.Header().Add("EXT", "") //w.Header().Set("User-Agent", "HttpMediaServer/1.0") http.ServeContent(w, r, id+"_"+endpoint+"_"+device, time.Now(), store[id]) } }) store[id].pipeline = C.startPipeline(C.int(vid), C.CString(device), C.CString(endpoint), C.CString("http://"+hostIP+":7070/"+endpoint+id+".mp4"), &ret) if ret == -1 { fmt.Println("ERROR: failed to setup the pipeline") C.destroyPipeline(store[id].pipeline) return "" } return id } func setActive(id string) bool { store.lock() defer store.unlock() if store[id] == nil { return false } devices[store[id].device] = RUN store[id].status = RUN return true } func setInactive(id string) bool { store.lock() defer store.unlock() if store[id] == nil { return false } C.destroyPipeline(store[id].pipeline) devices[store[id].device] = READY store[id] = nil return true } func isDeviceAvailable(device string) bool { store.lock() defer store.unlock() return !(devices[device] == DOWN || devices[device] > READY) } func stream(w http.ResponseWriter, r *http.Request) { var code = 400 var device, idv, action, endpoint string params := r.URL.Query() if params["device"] != nil { device = params["device"][0] } if params["endpoint"] != nil { endpoint = params["endpoint"][0] } if params["id"] != nil { idv = params["id"][0] } if params["action"] != nil { action = params["action"][0] } if r.Method != "POST" { code = 501 goto end } if action == "stop" { if idv != "" { setInactive(idv) } } else if action == "play" { if device == "" || (endpoint != "camera") { goto end } if !isDeviceAvailable(device) { code = 503 } else { if id := setInit(device, endpoint); id == "" { setInactive(id) code = 503 } else { w.Header().Add("Identifier", id) w.Header().Add("Healthport", "3221") code = 200 } } } end: w.WriteHeader(code) } func monitorStreams(ln net.Listener) { for { conn, err := ln.Accept() if err != nil { //TODO } else { tConn := conn.(*net.TCPConn) tConn.SetKeepAlive(true) go func(cn net.Conn) { for { st := DOWN reader := bufio.NewReader(cn) rp := textproto.NewReader(reader) line, err := rp.ReadLine() if err != nil { break } s := strings.Split(line, ":") if len(s) == 2 && s[0] == "status" { st = getStatus(s[1]) store[s[1]].then = time.Now() } tConn.Write([]byte(st.toString() + "\r\n")) } }(conn) } } } func checkNetworkInterface(str string) error { ifaces, err := net.Interfaces() if err != nil { return err } for _, iface := range ifaces { if iface.Name != str { continue } addrs, err := iface.Addrs() if err != nil { continue } for _, addr := range addrs { switch t := addr.(type) { case *net.IPNet: if t.IP.To4() != nil { hostIP = t.IP.String() return nil } } } } return errors.New("Interface " + str + " not found or does not have an IPv4 address") } func main() { vid = 9235 store = make(db) devices = make(map[string]state) if err := checkNetworkInterface(os.Args[1]); err != nil { fmt.Println(err) os.Exit(-1) } fmt.Println("Stream IP: " + hostIP) http.HandleFunc("/dmrs", getDMRs) http.HandleFunc("/stream", stream) if ln, err := net.Listen("tcp", ":3221"); err != nil { fmt.Println(err) os.Exit(-1) } else { go monitorStreams(ln) } C.start_upnp() getDMRs(nil, nil) if err := http.ListenAndServe(":7070", nil); err != nil { fmt.Println(err) os.Exit(-1) } }
package controller import ( "encoding/json" "io" "net/http" "github.com/rbonnat/blockchain-in-go/service" ) // Message contains data of Blockchain type Message struct { Value int } // HandleGetBlockchain returns handler for GetBlockchain func HandleGetBlockchain(s *service.Service) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { bytes, err := json.MarshalIndent(s.Blocks(r.Context()), "", " ") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } io.WriteString(w, string(bytes)) } } // HandleWriteBlock returns handler for WriteBlock Route func HandleWriteBlock(s *service.Service) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { var m Message decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&m); err != nil { respondWithJSON(w, r, http.StatusBadRequest, r.Body) return } defer r.Body.Close() newBlock, err := s.InsertNewBlock(r.Context(), m.Value) if err != nil { respondWithJSON(w, r, http.StatusInternalServerError, m) return } respondWithJSON(w, r, http.StatusCreated, *newBlock) } } func respondWithJSON(w http.ResponseWriter, r *http.Request, code int, payload interface{}) { response, err := json.MarshalIndent(payload, "", " ") if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("HTTP 500: Internal Server Error")) return } w.WriteHeader(code) w.Write(response) }
package response import ( "github.com/gin-gonic/gin" "net/http" "visitor/pkg/ierr" ) func ResponseOk(c *gin.Context, data interface{}) { var ret = map[string]interface{}{ "code": ierr.Success, "data": data, "error": "", "message": ierr.ErrorMessage[ierr.Success], } c.JSON(http.StatusOK, ret) } func ResponseErr(c *gin.Context, code int, err error) { var ret = map[string]interface{}{ "code": code, "data": nil, "error": "", "message": "", } if err != nil { ret["error"] = err.Error() } if message, ok := ierr.ErrorMessage[code]; ok { ret["message"] = message } c.JSON(http.StatusBadRequest, ret) }
/* Copyright 2015 Google Inc. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd */ // Package oid implements SNMP OID and related data structures. package oid import ( "fmt" "sort" "strings" ) // OID reprents a numeric object ID. type OID []uint // AsString formats the OID as a string. func (o OID) AsString() string { q := make([]string, len(o)) for i := range o { q[i] = fmt.Sprintf("%d", o[i]) } return strings.Join(q, ".") } // HasPrefix answers the question "does this OID have this prefix?" func (a OID) HasPrefix(b OID) bool { if len(a) < len(b) { return false } for i := 0; i < len(b); i++ { if a[i] != b[i] { return false } } return true } // IsEqualTo checks whether this OID == that OID. func (a OID) IsEqualTo(b OID) bool { if len(a) != len(b) { return false } for i := 0; i < len(a); i++ { if a[i] != b[i] { return false } } return true } // ComesBefore answers the question "does this OID sort before that OID?" func (a OID) ComesBefore(b OID) bool { var size int if len(a) < len(b) { size = len(a) } else { size = len(b) } for i := 0; i < size; i++ { if a[i] < b[i] { return true } if a[i] > b[i] { return false } } if len(a) < len(b) { return true } return false } // Variable represents an OID name:value pair. type Variable struct { Name OID Value string } // NameAsString formats OID.Name as a string. func (v *Variable) NameAsString() string { return v.Name.AsString() } // VariableSet represents an ordered set of OID variables. type VariableSet struct { vars []Variable } // Size gets the current size of this set. func (vs *VariableSet) Size() int { return len(vs.vars) } // Returns the variables in this set. func (vs *VariableSet) Variables() []Variable { return vs.vars } // AddVariable adds a variable to this set. func (vs *VariableSet) AddVariable(name OID, value string) { if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") { value = value[1 : len(value)-1] } vs.vars = append(vs.vars, Variable{name, value}) } // GetSubtree gets the subtree of variables whose OID name has prefix. func (vs *VariableSet) GetSubtree(prefix OID) *VariableSet { head := sort.Search(len(vs.vars), func(i int) bool { return !vs.vars[i].Name.ComesBefore(prefix) }) tail := head for tail < len(vs.vars) && vs.vars[tail].Name.HasPrefix(prefix) { tail++ } return &VariableSet{vs.vars[head:tail]} } // GetValues gets all values in this set. func (vs *VariableSet) GetValues() []string { values := make([]string, len(vs.vars)) for i := range vs.vars { values[i] = vs.vars[i].Value } return values } // GetVariable gets a single variable, by OID. func (vs *VariableSet) GetVariable(o OID) (*Variable, bool) { subtree := vs.GetSubtree(o) if len(subtree.vars) > 0 && subtree.vars[0].Name.IsEqualTo(o) { return &subtree.vars[0], true } return nil, false } // GetValue gets the value of a single variable, by OID. func (vs *VariableSet) GetValue(o OID) (string, bool) { if v, exists := vs.GetVariable(o); exists { return v.Value, true } return "", false }
package pie import ( "reflect" "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_insertOmitemptyTag(t *testing.T) { type Person struct { ID string `bson:"_id,omitempty"` Name string `bson:"name"` Age int `bson:"age"` } Convey("test insertOmitemptyTag", t, func() { u := Person{ID: "12345678"} ru := insertOmitemptyTag(&u) ruType := reflect.TypeOf(ru).Elem() for i := 0; i < ruType.NumField(); i++ { field := ruType.Field(i) switch field.Name { case "ID": So(field.Tag.Get("bson"), ShouldEqual, "_id,omitempty") case "Name": So(field.Tag.Get("bson"), ShouldEqual, "name,omitempty") case "Age": So(field.Tag.Get("bson"), ShouldEqual, "age,omitempty") } } }) }
package main import ( "fmt" "strconv" "sync" "time" ) func main() { sendToClosedChannel() recvFromClosedChannel() } func sendToClosedChannel() { var wg sync.WaitGroup wg.Add(2) ch := make(chan string, 10) go func() { v := <-ch fmt.Println(v) wg.Done() }() // 注意,往一个close掉的channel(无论是buffered还是unbuffered)中发送数据会造成 panic: send on closed channel go func() { ch <- "ahahahaha" wg.Done() }() close(ch) wg.Wait() } func recvFromClosedChannel() { var wg sync.WaitGroup wg.Add(2) // 存在缓冲区的channel,发送数据后马上close,在接收端也可以接收到数据。 ch := make(chan string, 10) go func() { for i := 0; i < 10; i++ { msg := "msg" + strconv.Itoa(i) ch <- msg } wg.Done() fmt.Println("Finish sending") close(ch) }() go func() { // 等待5s,让数据发送到channel中 time.Sleep(5 * time.Second) for i := 0; i < 15; i++ { // 接收两个值,第二个值为bool类型,当能够从channel中接收到数据时,此值为true, // 当 ** channel关闭并且channel中没有数据了 **,此值为false v, ok := <-ch fmt.Printf("[value %s, ok %t]\n", v, ok) } wg.Done() }() wg.Wait() }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/5/26 10:01 上午 # @File : reverse-linked-list-ii_test.go.go # @Description : # @Attention : */ package v2 import ( "fmt" "testing" ) func Test_Rever2(t *testing.T) { node := CreateListNode(5) between := reverseBetween(node, 1, 3) fmt.Println(between.String()) }
package config import ( "fmt" "github.com/jinzhu/gorm" ) //DB ... var DB *gorm.DB //DBConfig ... type DBConfig struct { User string Password string DBname string SSLmode string } //BuildDBConfig ... func BuildDBConfig() *DBConfig { dbConfig := DBConfig{ User: "postgres", Password: "1", DBname: "userproject", SSLmode: "disable", } return &dbConfig } //DbURI ... func DbURI(dbConfig *DBConfig) string { return fmt.Sprintf("user=%v password=%v dbname=%v sslmode=%v", dbConfig.User, dbConfig.Password, dbConfig.DBname, dbConfig.SSLmode) }