text
stringlengths
11
4.05M
package transport import ( sa "github.com/atymkiv/sa/model" ) // Shops feed model response // swagger:response shopsResp type swaggShopsResponse struct { //in:body Body struct{ Shops []sa.Shop } } // swagger:response addressResp type swaggAddressResponse struct { //in:body Body struct{ City string Number string Street string } }
package stories import ( G "github.com/ionous/sashimi/game" . "github.com/ionous/sashimi/script" ) // func The_Lab(s *Script) { s.The("story", Called("testing"), Has("author", "me"), Has("headline", "extra extra"), When("commencing").Always(func(g G.Play) { g.Say("Welcome to the lab.") })) s.The("room", Called("the lab"), Has("description", "an empty room")) s.The("actor", Called("player"), Exists(), In("the lab"), ) s.The("supporter", In("the lab"), Called("the table"), Is("fixed in place"), Supports("the glass jar")) s.The("prop", Called("the axe"), Has("brief", "a very nice guitar.")) s.The("player", Possesses("the axe")) s.The("actor", Called("lab assistant"), Has("description", "That's Darcy. Your pretty, capable lab assistant. Although, there is a question of commas."), Exists(), In("the lab")) s.The("container", Called("the glass jar"), Is("transparent", "closed").And("hinged"), Has("brief", "beaker with a lid."), Contains("the eye dropper")) s.The("props", Called("droppers"), Have("drops", "num")) s.The("dropper", Called("eye dropper"), Exists(), Has("drops", 5)) } func init() { stories.Register("lab", The_Lab) }
package main import ( "github.com/gin-gonic/gin" "gopetstore_v2/src/config" "gopetstore_v2/src/global" "gopetstore_v2/src/route" "gopetstore_v2/src/util" "html/template" "log" "path/filepath" ) func main() { r := gin.Default() setFrontConfig(r) // 注册路由 route.RegisterRoute(r) err := r.Run(":" + global.ServerSetting.Port) if err != nil { panic(err) } } func init() { err := setupSetting() if err != nil { log.Fatal(err) } } func setFrontConfig(r *gin.Engine) { // 注册自定义函数 r.SetFuncMap(template.FuncMap{ "unEscape": util.UnEscape, }) // 设置静态文件加载 for k, v := range global.StaticConfig { r.Static(k, v) } r.LoadHTMLGlob(filepath.Join("front", "web", "**", "*")) } func setupSetting() error { newSetting, err := config.NewSetting() if err != nil { return err } if err := newSetting.ReadSection("Database", &global.DatabaseSetting); err != nil { return err } global.DatabaseSetting.DataSourceName = global.DatabaseSetting.UserName + ":" + global.DatabaseSetting.Password + "@tcp(" + global.DatabaseSetting.Domain + ":" + global.DatabaseSetting.Port + ")/" + global.DatabaseSetting.DBName + "?" + "charset=" + global.DatabaseSetting.Charset + "&" + "loc=" + global.DatabaseSetting.Local + "&" + "parseTime=" + global.DatabaseSetting.ParseTime if err := newSetting.ReadSection("Server", &global.ServerSetting); err != nil { return err } return nil }
// Copyright 2019 Yunion // // 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 ssh import ( "context" ssh_util "yunion.io/x/onecloud/pkg/util/ssh" ) type epClientSet struct { cc ssh_util.ClientConfig clients []*Client mark bool } func (epcs *epClientSet) clearMark() { epcs.mark = false } func (epcs *epClientSet) setMark() { epcs.mark = true } func (epcs *epClientSet) getMark() bool { return epcs.mark } func (epcs *epClientSet) stop(ctx context.Context) { for _, client := range epcs.clients { client.Stop(ctx) } } type epClients map[string]*epClientSet // key: epKey type ClientSet struct { epClients epClients } func NewClientSet() *ClientSet { cs := &ClientSet{ epClients: epClients{}, } return cs } func (cs *ClientSet) ClearAllMark() { for _, epcs := range cs.epClients { epcs.clearMark() } } func (cs *ClientSet) ResetIfChanged(ctx context.Context, epKey string, cc ssh_util.ClientConfig) bool { epcs, ok := cs.epClients[epKey] if ok { if epcs.cc != cc { epcs.stop(ctx) delete(cs.epClients, epKey) cs.AddIfNotExist(ctx, epKey, cc) return true } epcs.setMark() } return false } func (cs *ClientSet) AddIfNotExist(ctx context.Context, epKey string, cc ssh_util.ClientConfig) bool { epcs, ok := cs.epClients[epKey] if !ok { epcs := &epClientSet{ cc: cc, } epcs.setMark() cs.epClients[epKey] = epcs return true } epcs.setMark() return false } func (cs *ClientSet) ResetUnmarked(ctx context.Context) { for epKey, epcs := range cs.epClients { if !epcs.getMark() { epcs.stop(ctx) delete(cs.epClients, epKey) } } } func (cs *ClientSet) ForwardKeySet() ForwardKeySet { fks := ForwardKeySet{} for epKey, epcs := range cs.epClients { for _, client := range epcs.clients { fks.addByPortMap(epKey, ForwardKeyTypeL, client.localForwards) fks.addByPortMap(epKey, ForwardKeyTypeR, client.remoteForwards) } } return fks } func (cs *ClientSet) LocalForward(ctx context.Context, epKey string, req LocalForwardReq) { client, created := cs.getOrCreateClient(epKey, ForwardKeyTypeL) if created { go client.Start(ctx) } client.LocalForward(ctx, req) } func (cs *ClientSet) RemoteForward(ctx context.Context, epKey string, req RemoteForwardReq) { client, created := cs.getOrCreateClient(epKey, ForwardKeyTypeR) if created { go client.Start(ctx) } client.RemoteForward(ctx, req) } func (cs *ClientSet) CloseForward(ctx context.Context, fk ForwardKey) { client := cs.getClient(fk.EpKey, fk.Type) if client == nil { return } switch fk.Type { case ForwardKeyTypeL: client.LocalForwardClose(ctx, LocalForwardReq{ LocalAddr: fk.KeyAddr, LocalPort: fk.KeyPort, }) case ForwardKeyTypeR: client.RemoteForwardClose(ctx, RemoteForwardReq{ RemoteAddr: fk.KeyAddr, RemotePort: fk.KeyPort, }) } } /* func (cs *ClientSet) LocalForwardClose(ctx context.Context, epKey string, req LocalForwardReq) { client := cs.getClient(epKey, ForwardKeyTypeL) client.LocalForwardClose(ctx, req) } func (cs *ClientSet) RemoteForwardClose(ctx context.Context, epKey string, req RemoteForwardReq) { client := cs.getClient(epKey, ForwardKeyTypeR) client.RemoteForwardClose(ctx, req) } */ func (cs *ClientSet) getOrCreateClient(epKey string, typ string) (*Client, bool) { return cs.getClient_(epKey, typ, true) } func (cs *ClientSet) getClient(epKey string, typ string) *Client { client, _ := cs.getClient_(epKey, typ, false) return client } func (cs *ClientSet) getClient_(epKey string, typ string, create bool) (*Client, bool) { var client *Client clients, ok := cs.epClients[epKey] if !ok || len(clients.clients) == 0 { if !ok || !create { return nil, false } client = NewClient(&clients.cc) clients.clients = append(clients.clients, client) cs.epClients[epKey] = clients return client, true } else { client = clients.clients[0] return client, false } }
package session import ( "testing" "github.com/stretchr/testify/assert" "golang.org/x/text/language" "golang.org/x/text/message" ) func TestFormatValue(t *testing.T) { mp := message.NewPrinter(language.Make("en")) f := 1.2345 assert.Equal(t, "1.234", formatValue(mp, f, 3)) assert.Equal(t, "1.234", formatValue(mp, &f, 3)) }
package main type session struct { username string userdn string password string }
package config import ( "github.com/wu-xing/wood-serve/common" "github.com/wu-xing/wood-serve/database" ) func Migration(db *database.DB) { var count int err := common.GetDB().Connection.DB().QueryRow("select count(*) from app_config").Scan(&count) if err != nil { panic(err) } if count >= 1 { return } var appConfig = AppConfig{ AppConfigData: &AppConfigData{ NoteTypeConfigs: []NoteTypeProp{ { Name: "Markdown", CanExportPdf: false, }, }, }, } err = common.GetDB().Connection.Create(appConfig).Error if err != nil { panic(err) } }
package cmd import ( "fmt" "log" "os/exec" "path" "strings" "github.com/BurntSushi/toml" "github.com/spf13/cobra" ) // process_yaml_queueCmd respresents the process_yaml_queue command var process_yaml_queueCmd = &cobra.Command{ Use: "process_yaml_queue", Short: "Process images specified in toml queue", Long: `Process images specified in toml queue. See examples/toml_queue for example toml file`, Run: func(cmd *cobra.Command, args []string) { if len(args) < 1 { log.Panicf("Missing required arg: path to config.toml file") } var config tomlConfig if _, err := toml.DecodeFile(args[0], &config); err != nil { fmt.Println(err) return } for _, itemToProcess := range config.Items { log.Printf( "Painting: %v, Photo: %v, Output: %v", itemToProcess.Painting, itemToProcess.Photo, itemToProcess.OutputImagePath(config.OutputPath), ) out, err := exec.Command( "th", "neural_style.lua", "-style_image", itemToProcess.Painting, "-content_image", itemToProcess.Photo, "-output_image", itemToProcess.OutputImagePath(config.OutputPath), ).CombinedOutput() log.Printf("Command output: %v Command err: %v", string(out), err) } }, } type tomlConfig struct { Items []item OutputPath string } type item struct { Painting string Photo string } func (i item) OutputImagePath(outputPath string) string { _, paintingFileName := path.Split(i.Painting) _, photoFileName := path.Split(i.Photo) log.Printf("painting: %v, photo: %v", paintingFileName, photoFileName) paintingNoExt := strings.Split(paintingFileName, ".")[0] photoNoExt := strings.Split(photoFileName, ".")[0] extension := path.Ext(paintingFileName) outputFilename := fmt.Sprintf("%v--%v%v", paintingNoExt, photoNoExt, extension) return path.Join(outputPath, outputFilename) } func init() { RootCmd.AddCommand(process_yaml_queueCmd) // Here you will define your flags and configuration settings // Cobra supports Persistent Flags which will work for this command and all subcommands // process_yaml_queueCmd.PersistentFlags().String("config", "", "Path to config toml file") // process_yaml_queueCmd.MarkPersistentFlagRequired("config") // Cobra supports local flags which will only run when this command is called directly // process_yaml_queueCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle" ) }
/* Copyright 2020 The Skaffold 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 manifest import ( "testing" "k8s.io/apimachinery/pkg/runtime/schema" "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/latest" "github.com/GoogleContainerTools/skaffold/v2/testutil" ) func TestSetLabels(t *testing.T) { manifests := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} expected := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: labels: key1: value1 key2: value2 name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} resultManifest, err := manifests.SetLabels(map[string]string{ "key1": "value1", "key2": "value2", }, NewResourceSelectorLabels(TransformAllowlist, TransformDenylist)) testutil.CheckErrorAndDeepEqual(t, false, err, expected.String(), resultManifest.String(), testutil.YamlObj(t)) } func TestAddLabels(t *testing.T) { manifests := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: labels: key0: value0 name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} expected := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: labels: key0: value0 key1: value1 key2: value2 name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} resultManifest, err := manifests.SetLabels(map[string]string{ "key0": "should-be-ignored", "key1": "value1", "key2": "value2", }, NewResourceSelectorLabels(TransformAllowlist, TransformDenylist)) testutil.CheckErrorAndDeepEqual(t, false, err, expected.String(), resultManifest.String(), testutil.YamlObj(t)) } func TestSetNoLabel(t *testing.T) { manifests := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} expected := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} resultManifest, err := manifests.SetLabels(nil, NewResourceSelectorLabels(TransformAllowlist, TransformDenylist)) testutil.CheckErrorAndDeepEqual(t, false, err, expected.String(), resultManifest.String()) } func TestSetNoLabelWhenTypeUnexpected(t *testing.T) { manifests := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: 3 `), []byte(` apiVersion: v1 kind: Pod metadata: labels: 3 name: getting-started `)} resultManifest, err := manifests.SetLabels(map[string]string{"key0": "value0"}, NewResourceSelectorLabels(TransformAllowlist, TransformDenylist)) testutil.CheckErrorAndDeepEqual(t, false, err, manifests.String(), resultManifest.String()) } func TestSetLabelInCRDSchema(t *testing.T) { manifests := ManifestList{[]byte(`apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: name: mykind.mygroup.org spec: group: mygroup.org names: kind: MyKind validation: openAPIV3Schema: properties: apiVersion: type: string kind: type: string metadata: type: object`)} expected := ManifestList{[]byte(`apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: labels: key0: value0 key1: value1 name: mykind.mygroup.org spec: group: mygroup.org names: kind: MyKind validation: openAPIV3Schema: properties: apiVersion: type: string kind: type: string metadata: type: object`)} resultManifest, err := manifests.SetLabels(map[string]string{ "key0": "value0", "key1": "value1", }, NewResourceSelectorLabels(map[schema.GroupKind]latest.ResourceFilter{ {Group: "apiextensions.k8s.io", Kind: "CustomResourceDefinition"}: { GroupKind: "CustomResourceDefinition.apiextensions.k8s.io", Image: []string{".*"}, Labels: []string{".metadata.labels"}, }, }, nil)) testutil.CheckErrorAndDeepEqual(t, false, err, expected.String(), resultManifest.String()) } func TestAlwaysSetRunIDLabel(t *testing.T) { manifests := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: labels: skaffold.dev/run-id: foo name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} expected := ManifestList{[]byte(` apiVersion: v1 kind: Pod metadata: labels: skaffold.dev/run-id: bar name: getting-started spec: containers: - image: gcr.io/k8s-skaffold/example name: example `)} resultManifest, err := manifests.SetLabels(map[string]string{ "skaffold.dev/run-id": "bar", }, NewResourceSelectorLabels(TransformAllowlist, TransformDenylist)) testutil.CheckErrorAndDeepEqual(t, false, err, expected.String(), resultManifest.String(), testutil.YamlObj(t)) }
package twitter import ( "fmt" "regexp" "strings" logger "github.com/sirupsen/logrus" "golang.org/x/net/context" "strconv" "github.com/namsral/flag" vision "cloud.google.com/go/vision/apiv1" "github.com/ChimeraCoder/anaconda" "github.com/amcleodca/pretty-pinboard/pin-enricher/enricher" "github.com/amcleodca/pretty-pinboard/pin-enricher/pin" ) var twConsumerKey string var twConsumerSec string var twAPIKey string var twAPISec string func init() { flag.StringVar(&twConsumerKey, "twConsumerKey", "", "Twitter Consumer Key") flag.StringVar(&twConsumerSec, "twConsumerSec", "", "Twitter Consumer Secret") flag.StringVar(&twAPIKey, "twAPIKey", "", "Twitter API Key") flag.StringVar(&twAPISec, "twAPISec", "", "Twitter API Sec") enricher.Register(NewTwitterEnricher) } type TwitterEnricher struct { log logger.FieldLogger twitter *anaconda.TwitterApi cloudvision *vision.ImageAnnotatorClient context context.Context } func (tw *TwitterEnricher) GetCloudVisionAnnotations(file string) (string, error) { image := vision.NewImageFromURI(file) annotations, err := tw.cloudvision.DetectTexts(tw.context, image, nil, 10) if err != nil { return "", err } if len(annotations) == 0 { return "", nil } else { return annotations[0].Description, nil } return "", nil } func NewTwitterEnricher() (enricher.Enricher, error) { log := logger.WithFields(logger.Fields{"module": "twitter"}) if "" == twConsumerKey { log.Fatal("A mandatory field(twConsumerKey) is unspecified or empty.") } if "" == twConsumerSec { log.Fatal("A mandatory field(twConsumerSec) is unspecified or empty.") } if "" == twAPIKey { log.Fatal("A mandatory field(twAPIKey) is unspecified or empty.") } if "" == twAPISec { log.Fatal("A mandatory field(twAPISec) is unspecified or empty.") } anaconda.SetConsumerKey(twConsumerKey) // app key anaconda.SetConsumerSecret(twConsumerSec) // app secret twitterApi := anaconda.NewTwitterApi(twAPIKey, twAPISec) // account access token secrets ctx := context.Background() cvApi, err := vision.NewImageAnnotatorClient(ctx) if err != nil { log.WithError(err).Error("Failed to init cloud vision") return nil, err } return &TwitterEnricher{ twitter: twitterApi, cloudvision: cvApi, context: ctx, log: log}, nil } func (tw *TwitterEnricher) Enrich(pin *pin.Pin) error { log := tw.log.WithFields(logger.Fields{"module": tw.GetName(), "url": pin.Post.URL}) if pin.HasTag(tw.GetName()) { log.Info("Already enriched.") return nil } matches, _ := regexp.MatchString("https?://twitter.com/.*", pin.Post.URL) if !matches { log.Debug("skipping") return nil } tweet, err := tw.GetTweetByURL(pin.Post.URL) if err != nil { return err } if pin.Post.Title == "" || pin.Post.Title == pin.Post.URL { pin.Post.Title = fmt.Sprintf("@%s: %s", tweet.User.ScreenName, tweet.Text) log.Infof("Updated title: %s", pin.Post.Title) pin.Modified = true pin.AddTag(tw.GetName()) } // Get media URLs from Tweet var mediaUrls []string for _, media := range tweet.ExtendedEntities.Media { mediaUrls = append(mediaUrls, media.Media_url) } log.Debugf("URLs in tweet", strings.Join(mediaUrls, " ")) // Build annotation string var annotations []string for _, url := range mediaUrls { text, err := tw.GetCloudVisionAnnotations(url) if err != nil { log.WithError(err).Errorf("Failed to get annotation data for %s", url) } if text == "" { continue } annotations = append(annotations, text) } if len(annotations) > 0 { log.Infof("updating description: %s", annotations) pin.Post.Description = strings.Join(annotations, "\n") pin.Modified = true pin.AddTag(tw.GetName()) } return nil } func (tw *TwitterEnricher) GetTweetByURL(url string) (*anaconda.Tweet, error) { log := logger.WithFields(logger.Fields{"module": tw.GetName(), "action": "GetTweetByURL"}) // Get Tweet ID from URL urlparams := strings.Split(url, "/") id := urlparams[len(urlparams)-1] tweetId, err := strconv.ParseInt(id, 10, 64) if err != nil { log.WithError(err).Error("Failed to parse ID") return nil, err } // Get tweet from Twitter tweet, err := tw.twitter.GetTweet(tweetId, nil) if err != nil { log.WithError(err).Error("Failed to get tweet") return nil, err } log.Info("Got tweet") return &tweet, nil } func (tw *TwitterEnricher) GetName() string { return "twitter" } func (tw *TwitterEnricher) GetPriority() int { return 42 }
// Copyright 2019 Yunion // // 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 azure import ( "context" "database/sql" "fmt" "strings" "yunion.io/x/pkg/errors" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudid/models" "yunion.io/x/onecloud/pkg/httperrors" "yunion.io/x/onecloud/pkg/mcclient" "yunion.io/x/onecloud/pkg/util/samlutils" "yunion.io/x/onecloud/pkg/util/samlutils/idp" ) func (d *SAzureSAMLDriver) GetIdpInitiatedLoginData(ctx context.Context, userCred mcclient.TokenCredential, cloudAccountId string, sp *idp.SSAMLServiceProvider) (samlutils.SSAMLIdpInitiatedLoginData, error) { data := samlutils.SSAMLIdpInitiatedLoginData{} _account, err := models.CloudaccountManager.FetchById(cloudAccountId) if err != nil { if errors.Cause(err) == sql.ErrNoRows { return data, httperrors.NewResourceNotFoundError2("cloudaccount", cloudAccountId) } return data, httperrors.NewGeneralError(err) } account := _account.(*models.SCloudaccount) if account.Provider != api.CLOUD_PROVIDER_AZURE { return data, httperrors.NewClientError("cloudaccount %s is %s not %s", account.Id, account.Provider, api.CLOUD_PROVIDER_AWS) } if account.SAMLAuth.IsFalse() { return data, httperrors.NewNotSupportedError("cloudaccount %s not open saml auth", account.Id) } samlProvider, valid := account.IsSAMLProviderValid() if !valid { return data, httperrors.NewResourceNotReadyError("SAMLProvider for account %s not ready", account.Id) } inviteUrl, err := account.InviteAzureUser(ctx, userCred, samlProvider.ExternalId) if err != nil { return data, httperrors.NewGeneralError(errors.Wrapf(err, "InviteAzureUser")) } data.Form = fmt.Sprintf(`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=%s"> <title>waiting...</title> </head> <body> waiting... </body> </html>`, inviteUrl) return data, nil } func (d *SAzureSAMLDriver) GetSpInitiatedLoginData(ctx context.Context, userCred mcclient.TokenCredential, cloudAccountId string, sp *idp.SSAMLServiceProvider) (samlutils.SSAMLSpInitiatedLoginData, error) { data := samlutils.SSAMLSpInitiatedLoginData{} _account, err := models.CloudaccountManager.FetchById(cloudAccountId) if err != nil { if errors.Cause(err) == sql.ErrNoRows { return data, httperrors.NewResourceNotFoundError2("cloudaccount", cloudAccountId) } return data, httperrors.NewGeneralError(err) } account := _account.(*models.SCloudaccount) if account.Provider != api.CLOUD_PROVIDER_AZURE { return data, httperrors.NewClientError("cloudaccount %s is %s not %s", account.Id, account.Provider, api.CLOUD_PROVIDER_AWS) } if account.SAMLAuth.IsFalse() { return data, httperrors.NewNotSupportedError("cloudaccount %s not open saml auth", account.Id) } samlUsers, err := account.GetSamlusers() if err != nil { return data, httperrors.NewGeneralError(errors.Wrapf(err, "GetSamlusers")) } for i := range samlUsers { if samlUsers[i].OwnerId == userCred.GetUserId() && strings.ToLower(samlUsers[i].Email) == strings.ToLower(sp.Username) { err := samlUsers[i].SyncAzureGroup() if err != nil { return data, errors.Wrapf(err, "SyncAzureGroup") } data.NameId = sp.Username data.NameIdFormat = samlutils.NAME_ID_FORMAT_PERSISTENT data.AudienceRestriction = sp.GetEntityId() for _, v := range []struct { name string friendlyName string value string }{ { name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", value: data.NameId, }, } { data.Attributes = append(data.Attributes, samlutils.SSAMLResponseAttribute{ Name: v.name, FriendlyName: v.friendlyName, Values: []string{v.value}, }) } return data, nil } } return data, httperrors.NewResourceNotFoundError("not found any saml user for %s -> %s", userCred.GetUserName(), sp.Username) }
package runtime // Tail calls are handled by a trampoline type Call struct { *NilObj // The function that was invoked Fn Callable // The arguments it was invoked in Args Sequence // The environment it was invoked in Env Env } func (c *Call) Eval(env Env) (Value, error) { return c, nil } // These should never actually be seen func (c *Call) String() string { return "#<invalid>" } // Resolve the trampoline down to a final return value func (c *Call) Return() (acc Value, err error) { var ok bool for { acc, err = c.Fn.Call(c.Env, c.Args) c, ok = acc.(*Call) if ok == false { break } } return }
package main import ( //"fmt" //"time" //"flag" "strings" "github.com/SophisticaSean/gitlab-bot/gitlab" "github.com/davecgh/go-spew/spew" "github.com/SophisticaSean/gitlab-bot/model" ) var job_count int var app_id string var job_name string var owner_name string func main() { gl := gitlab.New() name := "juno" whitelisted_namespaces := []string{"backend", "platform", "frontend"} results := gl.SearchProjects(name) filtered := []model.Project{} for _, proj := range results { if proj.Name == name { for _, namespace := range whitelisted_namespaces { if strings.Contains(proj.PathWithNamespace, namespace) { filtered = append(filtered, proj) } } } } spew.Dump(filtered) }
package udwCmd_test import ( "github.com/tachyon-protocol/udw/udwCmd" "github.com/tachyon-protocol/udw/udwFile" "github.com/tachyon-protocol/udw/udwRand" "github.com/tachyon-protocol/udw/udwTest" "testing" ) func TestBashEscape(ot *testing.T) { udwTest.Equal(len(udwCmd.BashEscape("'")), 6) udwTest.Equal(len(udwCmd.BashEscape(udwCmd.BashEscape("'"))), 23) udwTest.Equal(len(udwCmd.BashEscape(udwCmd.BashEscape(udwCmd.BashEscape("'")))), 76) udwFile.MustDelete("/tmp/testFile") defer udwFile.MustDelete("/tmp/testFile") udwFile.MustMkdirForFile("/tmp/testFile/1.txt") for _, cas := range []string{ " '", `abc 'abc'`, `abc '中文'`, `"!@#$%^&*()`, `\"'\'`, "\n\b\r\t", "\x01", "'", udwCmd.BashEscape("'"), udwCmd.BashEscape(udwCmd.BashEscape("'")), } { mustRunTestBashEscapeContent(cas) } } func RunTestBashEscapeFull() { for i := 1; i < 256; i++ { mustRunTestBashEscapeContent(string([]byte{byte(i)})) } for i := 0; i < 1000; i++ { bl := make([]byte, 3) for j := 0; j < 3; j++ { bl[j] = byte(udwRand.IntBetween(1, 255)) } mustRunTestBashEscapeContent(string(bl)) } } func mustRunTestBashEscapeContent(cas string) { cmd := `echo -n ` + udwCmd.BashEscape(cas) + ` > /tmp/testFile/1.txt` udwCmd.CmdBash(cmd).MustCombinedOutput() udwTest.Equal(string(udwFile.MustReadFile("/tmp/testFile/1.txt")), cas) }
package main import ( "log" "strings" ) /** 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 示例: 输入: "Hello World" 输出: 5 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/length-of-last-word 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ func lengthOfLastWord(s string) int { if len(s) == 0 { return 0 } s = strings.TrimSpace(s) array := strings.Split(s, " ") return len(array[len(array) - 1]) } func main() { result := lengthOfLastWord("a ") if result != 1 { log.Printf("error: %v", result) return } log.Printf("success") }
package main import ( "encoding/csv" "fmt" "log" "os" "strings" "sync" "time" "github.com/gocolly/colly" ) const ( prefix = "https://www.gumtree.pl" ) func main() { fName := "cryptocoinmarketcap.csv" file, err := os.Create(fName) if err != nil { log.Fatalf("Cannot create file %q: %s\n", fName, err) return } defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() // Write CSV header // writer.Write([]string{"Name", "Symbol", "Price (USD)", "Volume (USD)", "Market capacity (USD)", "Change (1h)", "Change (24h)", "Change (7d)"}) // Instantiate default collector // c := colly.NewCollector() toBeParsed := make(chan string, 1000) listingsReader := newListingReader(file) urlFilter := NewUrlFilter(toBeParsed) // get listing details listingsReader.OnHTML(".vip-header-and-details ", func(e *colly.HTMLElement) { fmt.Println(strings.TrimRight(e.ChildText(".vip-content-header .price .value"), " zł")) description := e.ChildText(".vip-details .description span") district := getDistrictFor(description) writer.Write([]string{ strings.TrimSpace(strings.TrimRight(e.ChildText(".vip-content-header .price .value"), " zł")), // e.ChildText(".vip-details .description span"), district, }) // data dodania // fmt.Println(strings.TrimSpace(e.ChildText(".selMenu li .attribute .value"))) }) // get listing detail pages listingsReader.OnHTML(".result-link .container .title", func(e *colly.HTMLElement) { urlFilter.Add(e.ChildAttr("a", "href")) }) // get listing pages listingsReader.OnHTML(".pagination .after", func(e *colly.HTMLElement) { urlFilter.Add(e.ChildAttr("a", "href")) }) listingsReader.Visit(prefix + "/s-mieszkania-i-domy-sprzedam-i-kupie/wroclaw/v1c9073l3200114p1?df=ownr&nr=10") log.Printf("Scraping finished, check file %q for results\n", fName) var waitTime = 0 loop: for { select { case url := <-toBeParsed: fmt.Println("url: ", prefix+url) listingsReader.Visit(prefix + url) default: time.Sleep(1000 * time.Millisecond) waitTime++ if waitTime > 4 { break loop } } } fmt.Println("done waiting") log.Printf("number of urls %d", urlFilter.GetUrlsNumber()) } type listingsReader struct { *colly.Collector file *os.File } func newListingReader(file *os.File) *listingsReader { return &listingsReader{colly.NewCollector(), file} } type urlFilter struct { urlMap map[string]struct{} processingChan chan string mx sync.RWMutex } func NewUrlFilter(processingChan chan string) *urlFilter { return &urlFilter{ urlMap: make(map[string]struct{}), processingChan: processingChan, } } func (filter *urlFilter) Add(url string) { if url == "" { return } filter.mx.Lock() defer filter.mx.Unlock() if _, ok := filter.urlMap[url]; !ok { filter.urlMap[url] = struct{}{} filter.processingChan <- url } } func (filter *urlFilter) GetUrlsNumber() int { filter.mx.RLock() defer filter.mx.RUnlock() return len(filter.urlMap) } func getDistrictFor(text string) string { for key, value := range districtsMap { if strings.Contains(strings.ToLower(text), key) { return value } } fmt.Printf("no matching districts in '%s'", text) return "-" } var districtsMap = map[string]string{ "stare miasto": "stare miasto", "starym mieście": "stare miasto", "przedmieście świdnickie": "przedmieście świdnickie", "przedmieściu świdnickim": "przedmieście świdnickie", "szczepin": "szczepin", "szczepinie": "szczepin", "śródmieście": "śródmieście", "śródmieściu": "śródmieście", "bartoszowice": "bartoszowice", "bartoszowicach": "bartoszowice", "biskupin": "biskupin", "biskupine": "biskupin", "dąbie": "dąbie", "dąbiu": "dąbie", "nadodrze": "nadodrze", "nadodrzu": "nadodrze", "ołbin": "ołbin", "ołbinie": "ołbin", "plac grunwaldzki": "plac grunwaldzki", "placu grunwaldzkim": "plac grunwaldzki", "sępolno": "sępolno", "sępolnie": "sępolno", "zacisze": "zacisze", "zaciszu": "zacisze", "zalesie": "zalesie", "zalesiu": "zalesie", "szczytniki": "szczytniki", "szczytnikach": "szczytniki", "krzyki": "krzyki", "krzykach": "krzyki", "bieńkowice": "bieńkowice", "bieńkowicach": "bieńkowice", "bierdzany": "bierdzany", "bierdzanach": "bierdzany", "borek": "borek", "borku": "borek", "brochów": "brochów", "brochowie": "brochów", "dworek": "dworek", "dworku": "dworek", "gaj": "gaj", "gaju": "gaj", "glinianki": "glinianki", "gliniankach": "glinianki", "huby": "huby", "hubach": "huby", "jagodno": "jagodno", "jagodnie": "jagodno", "klecina": "klecina", "klecinie": "klecina", "księże małe": "księże małe", "księżu małym": "księże małe", "księże wielkie": "księże wielkie", "księżu wielkim": "księże wielkie", "lamowice stare": "lamowice stare", "lamowicach starych": "lamowice stare", "nowy dom": "nowy dom", "nowym domu": "nowy dom", "ołtaszyn": "ołtaszyn", "ołtaszynie": "ołtaszyn", "opatowice": "opatowice", "opatowicach": "opatowice", "partynice": "partynice", "partynicach": "partynice", "południe": "południe", "południu": "południe", "przedmieście oławskie": "przedmieście oławskie", "przedmieściu oławskim": "przedmieście oławskie", "rakowiec": "rakowiec", "rakowcu": "rakowiec", "siedlec": "siedlec", "siedlcach": "siedlec", "świątniki": "świątniki", "świątnikach": "świątniki", "tarnogaj": "tarnogaj", "tarnogaju": "tarnogaj", "wilczy kąt": "wilczy kąt", "wilczym kącie": "wilczy kąt", "wojszyce": "wojszyce", "wojszycach": "wojszyce", "psie pole": "psie pole", "psim polu": "psie pole", "karłowice": "karłowice", "karłowicach": "karłowice", "kleczków": "kleczków", "kleczkowie": "kleczków", "kłokoczyce": "kłokoczyce", "kłokoczycach": "kłokoczyce", "kowale": "kowale", "kowalach": "kowale", "lesica": "lesica", "lesicy": "lesica", "ligota": "ligota", "ligocie": "ligota", "lipa piotrowska": "lipa piotrowska", "lipie piotrowskiej": "lipa piotrowska", "mirowiec": "mirowiec", "mirowcu": "mirowiec", "osobowice": "osobowice", "osobowicach": "osobowice", "pawłowice": "pawłowice", "pawłowicach": "pawłowice", "polanka": "polanka", "polance": "polanka", "polanowicach": "polanowicach", "poświętne": "polanowicach", "poświętnach": "poświętnach", "pracze widawskie": "pracze widawskie", "praczach widawskich": "pracze widawskie", "rędzin": "rędzin", "rędzinie": "rędzin", "różanka": "różanka", "różance": "różanka", "sołtysowice": "sołtysowice", "sołtysowicach": "sołtysowice", "strachocin": "strachocin", "strachocinie": "strachocin", "swojczyce": "swojczyce", "swojczycach": "swojczyce", "świniary": "świniary", "świniarach": "świniary", "widawa": "widawa", "widawach": "widawach", "wojnów": "wojnów", "wojnowie": "wojnów", "zakrzów": "zakrzów", "zakrzowie": "zakrzów", "zgorzelisko": "zgorzelisko", "zgorzelisku": "zgorzelisko", "fabryczna": "fabryczna", "fabrycznej": "fabryczna", "gajowice": "gajowice", "gajowicach": "gajowice", "gądów mały": "gądów mały", "gądowie małym": "gądów mały", "grabiszyn": "grabiszyn", "grabiszynie": "grabiszyn", "grabiszynek": "grabiszynek", "grabiszynku": "grabiszynek", "janówek": "janówek", "janówku": "janówek", "jarnołtów": "jarnołtów", "jarnołtowie": "jarnołtów", "jerzmanowo": "jerzmanowo", "jerzmanowie": "jerzmanowo", "kozanów": "kozanów", "kozanowie": "kozanów", "kuźniki": "kuźniki", "kuźnikiach": "kuźniki", "leśnica": "leśnica", "leśnicy": "leśnica", "marszowice": "marszowice", "marszowicach": "marszowicach", "maślice": "maślice", "maślicach": "maślice", "mokra": "mokra", "mokrej": "mokra", "muchobór mały": "muchobór mały", "muchoborze małym": "muchobór mały", "muchobór wielki": "muchobór wielki", "muchoborze wielkim": "muchobór wielki", "nowa karczma": "nowa karczma", "nowej karczmie": "nowa karczma", "nowe domy": "nowe domy", "nowych domach": "nowe domy", "nowy dwór": "nowy dwór", "nowym dworze": "nowy dwór", "oporów": "oporów", "oporowie": "oporów", "pilczyce": "pilczyce", "pilczycach": "pilczyce", "popowice": "popowice", "popowicach": "popowice", "pracze odrzańskie": "pracze odrzańskie", "praczach odrzańskich": "pracze odrzańskie", "pustki": "pustki", "pustkach": "pustki", "ratyń": "ratyń", "ratyniu": "ratyń", "stabłowice": "stabłowice", "stabłowicach": "stabłowice", "stabłowice nowe": "stabłowice nowe", "stabłowicach nowych": "stabłowice nowe", "strachowice": "strachowice", "strachowicach": "strachowice", "osiniec": "osiniec", "osiniecu": "osiniec", "złotniki": "złotniki", "złotnikiach": "złotniki", "żar": "żar", "żarach": "żar", "żerniki": "żerniki", "kosmonautów": "kosmonautów", }
package divine_test import ( "fmt" "reflect" "github.com/onsi/gomega/types" "github.com/shamus/divine" ) type ( providerMatcher struct { executed bool err error dependent, required, yielded interface{} } ) func Provide(required interface{}) *providerMatcher { return &providerMatcher{required: required} } func (p *providerMatcher) To(dependent interface{}) types.GomegaMatcher { p.dependent = dependent return p } func (p *providerMatcher) Match(actual interface{}) (success bool, err error) { dependent := reflect.ValueOf(p.dependent).Elem() v := reflect.MakeFunc(dependent.Type(), func(in []reflect.Value) []reflect.Value { p.executed = true p.yielded = in[0].Interface() return []reflect.Value{} }) dependent.Set(v) p.err = divine.Inject(actual.(divine.Container), dependent.Interface()) return p.err == nil && p.executed && p.yielded == p.required, nil } func (p *providerMatcher) FailureMessage(actual interface{}) (message string) { if p.err != nil { return fmt.Sprintf("Expected container to yield %v, but received an error %v", p.required, p.err) } return fmt.Sprintf("Expected container to yield %v, but instead received %v", p.required, p.yielded) } func (p *providerMatcher) NegatedFailureMessage(actual interface{}) (message string) { return "" }
package main import ( "encoding/base64" "fmt" ) func main() { decoded, err := base64.StdEncoding.DecodeString("AAcAAAgA9QEBZAD//w==") if err != nil { fmt.Println("decode error:", err) return } fmt.Printf("%#v\n", decoded) // []byte{0x0, 0x7, 0x0, 0x0, 0x8, 0x0, 0xf5, 0x1, 0x1, 0x64, 0x0, 0xff, 0xff} }
package main const ( pgConnHost = "localhost" pgConnPort = 5432 pgConnUser = "mbadmin" pgConnPassword = "kalra" pgConnDBName = "message_board" ) //DBInterface defined what DB module must offer for users type DBInterface interface { NewDB() error InsertNewUser(email, firstname, lastname string) (userID int64, token string, e error) UpdateUserByEmail(email, status, password, firstname, lastname, location, phone, token, preference string) (e error) SearchUserByEmail(email string) (id int64, status, firstname, lastname, location, phone string, e error) RegenerateUserTokenByEmail(email string) (token string, e error) Post(userID int64, title, msg string) (msgID int64, e error) Delete(userEmail, title string) (e error) List(pageIndex int) (m []Message, e error) DestroyDB() }
package main import ( "database/sql" "sync" ) // Server represents the state of a single server, and is the endpoint for RPC calls. type Server struct { sync.Mutex DB *sql.DB // the current state: one of "follower", "leader", or "candidate" State string // all servers persistent state CurrentTerm int VotedFor string // all servers volatile state CommitIndex int LastApplied int CurrentLeader string // leader-only volatile state NextIndex map[string]int MatchIndex map[string]int // the state machine Data map[string]string // cache of most recent completed requests, one per client // maps client ID to (non-redirect) response MostRecent map[string]*ClientResponse } type ClientRequest struct { ClientID string ClientSerial int // "get", "put", or "delete" Operation string Key string Value string } type ClientResponse struct { // if non-empty, repeat the request at the given address and ignore other fields RedirectTo string ClientSerial int Successful bool Result string } type LogEntry struct { ID int Term int ClientRequest } func (l *LogEntry) IsNull() bool { return l.ClientRequest.ClientID == "" } type AppendEntriesRequest struct { Term int LeaderID string PrevLogIndex int PrevLogTerm int Entries []*LogEntry LeaderCommit int } type AppendEntriesResponse struct { Term int Success bool } type RequestVoteRequest struct { Term int CandidateID string LastLogIndex int LastLogTerm int } type RequestVoteResponse struct { Term int VoteGranted bool }
package k8s_api_bybass_test import ( "github.com/kumahq/kuma/test/e2e/k8s_api_bybass" . "github.com/onsi/ginkgo" ) var _ = Describe("Test Kubernetes API Bypass", k8s_api_bybass.K8sApiBypass)
package utils import ( "fmt" "github.com/google/uuid" ) const ( queryKeyDelim = "#" ) func NewID() string { return uuid.New().String() } // Forms a new document's "query ID", which is the ID used for "queries", which // are retrieval operations that retrieve multiple documents by query ID // prefix. func DocQueryID(docQueryKeys map[string]string) string { ID := "" for keyName, keyValue := range docQueryKeys { ID = fmt.Sprintf("%s%s%s=%s", ID, queryKeyDelim, keyName, keyValue) } return ID }
package main import ( "fmt" ) func main() { var s1 interface{} = "123" var s2 []byte = []byte{'4', '5', '6'} fmt.Println(fmt.Sprintf("%s%s", s1, s2)) }
package altrudos import ( "database/sql/driver" "encoding/json" "errors" "fmt" "os" "reflect" "strings" "github.com/lib/pq" ) var ( ErrInvalidCurrency = errors.New("invalid currency") ) var ValidCurrencies = map[string]string{ "USD": "USD", "CAD": "CAD", "EUR": "EUR", "GBP": "GBP", "AUD": "AUD", } type M map[string]interface{} type FlatMap map[string]interface{} func (p FlatMap) Equal(b FlatMap) bool { for k, v := range p { e, ok := b[k] if !ok { return false } if !reflect.DeepEqual(e, v) { return false } } return true } func (p FlatMap) Value() (driver.Value, error) { j, err := json.Marshal(p) return j, err } func (p *FlatMap) Scan(src interface{}) error { if src == nil { return nil } source, ok := src.([]byte) if !ok { return errors.New("Type assertion .([]byte) failed.") } var i interface{} err := json.Unmarshal(source, &i) if err != nil { return err } // Nothing to do if nil if i == nil { return nil } *p, ok = i.(map[string]interface{}) if !ok { return errors.New("Type assertion .(map[string]interface{}) failed.") } return nil } var ( ErrAlreadyInserted = errors.New("That item has already been inserted into the db") ErrNotFound = errors.New("Couldn't find that") ErrTooManyFound = errors.New("Found too many of that") ) const PqSuffixId = "RETURNING \"id\"" type SortDirection string var ( SortDesc = SortDirection("DESC") SortAsc = SortDirection("ASC") ) type QueryOperator interface { GetSort() string GetLimit() int } type BaseOperator struct { SortField string SortDir SortDirection Limit int } func (qo *BaseOperator) GetLimit() int { if qo.Limit == 0 { return 50 } return qo.Limit } func (qo *BaseOperator) GetSort() string { if qo.SortField == "" { return "" } direction := qo.SortDir if direction == "" { direction = SortAsc } return fmt.Sprintf("%s %s", qo.SortField, direction) } func StatusesPQStringArray(things []DonationStatus) pq.StringArray { strs := make([]string, len(things)) for i, thing := range things { strs[i] = fmt.Sprintf("%s", thing) } return pq.StringArray(strs) } func GetEnv(name, defaultValue string) string { if v := os.Getenv(name); v != "" { return v } return defaultValue } func AmountToString(amount int) string { str := fmt.Sprintf("%.2f", float64(amount)/100.0) return str } func ErrIsPqConstraint(err error, constraint string) bool { if err, ok := err.(*pq.Error); ok { if err.Constraint == constraint { return true } } return false } func ParseCurrency(curr string) (string, error) { curr = strings.ToUpper(curr) if val, ok := ValidCurrencies[curr]; !ok { return "", ErrInvalidCurrency } else { return val, nil } }
package configs import ( "fmt" "time" "github.com/go-kit/kit/log" "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/rulefmt" "github.com/prometheus/prometheus/promql" "github.com/prometheus/prometheus/rules" "github.com/weaveworks/cortex/pkg/util" ) // An ID is the ID of a single users's Cortex configuration. When a // configuration changes, it gets a new ID. type ID int // RuleFormatVersion indicates which Prometheus rule format (v1 vs. v2) to use in parsing. type RuleFormatVersion int const ( // RuleFormatV1 is the Prometheus 1.x rule format. RuleFormatV1 RuleFormatVersion = iota // RuleFormatV2 is the Prometheus 2.x rule format. RuleFormatV2 RuleFormatVersion = iota ) // String implements flag.Value. func (v RuleFormatVersion) String() string { switch v { case RuleFormatV1: return "1" case RuleFormatV2: return "2" default: return "<unknown>" } } // Set implements flag.Value. func (v *RuleFormatVersion) Set(s string) error { switch s { case "1": *v = RuleFormatV1 case "2": *v = RuleFormatV2 default: return fmt.Errorf("invalid rule format version %q", s) } return nil } // A Config is a Cortex configuration for a single user. type Config struct { // RulesFiles maps from a rules filename to file contents. RulesFiles RulesConfig `json:"rules_files"` AlertmanagerConfig string `json:"alertmanager_config"` } // View is what's returned from the Weave Cloud configs service // when we ask for all Cortex configurations. // // The configs service is essentially a JSON blob store that gives each // _version_ of a configuration a unique ID and guarantees that later versions // have greater IDs. type View struct { ID ID `json:"id"` Config Config `json:"config"` DeletedAt time.Time `json:"deleted_at"` } // GetVersionedRulesConfig specializes the view to just the rules config. func (v View) GetVersionedRulesConfig() *VersionedRulesConfig { if v.Config.RulesFiles == nil { return nil } return &VersionedRulesConfig{ ID: v.ID, Config: v.Config.RulesFiles, DeletedAt: v.DeletedAt, } } // RulesConfig are the set of rules files for a particular organization. type RulesConfig map[string]string // Equal compares two RulesConfigs for equality. // // instance Eq RulesConfig func (c RulesConfig) Equal(o RulesConfig) bool { if len(o) != len(c) { return false } for k, v1 := range c { v2, ok := o[k] if !ok || v1 != v2 { return false } } return true } // Parse parses and validates the content of the rule files in a RulesConfig // according to the passed rule format version. func (c RulesConfig) Parse(v RuleFormatVersion) (map[string][]rules.Rule, error) { switch v { case RuleFormatV1: return c.ParseV1() case RuleFormatV2: return c.ParseV2() default: panic("unknown rule format") } } // ParseV2 parses and validates the content of the rule files in a RulesConfig // according to the Prometheus 2.x rule format. // // NOTE: On one hand, we cannot return fully-fledged lists of rules.Group // here yet, as creating a rules.Group requires already // passing in rules.ManagerOptions options (which in turn require a // notifier, appender, etc.), which we do not want to create simply // for parsing. On the other hand, we should not return barebones // rulefmt.RuleGroup sets here either, as only a fully-converted rules.Rule // is able to track alert states over multiple rule evaluations. The caller // would otherwise have to ensure to convert the rulefmt.RuleGroup only exactly // once, not for every evaluation (or risk losing alert pending states). So // it's probably better to just return a set of rules.Rule here. func (c RulesConfig) ParseV2() (map[string][]rules.Rule, error) { groups := map[string][]rules.Rule{} for fn, content := range c { rgs, errs := rulefmt.Parse([]byte(content)) if len(errs) > 0 { return nil, fmt.Errorf("error parsing %s: %v", fn, errs[0]) } for _, rg := range rgs.Groups { rls := make([]rules.Rule, 0, len(rg.Rules)) for _, rl := range rg.Rules { expr, err := promql.ParseExpr(rl.Expr) if err != nil { return nil, err } if rl.Alert != "" { rls = append(rls, rules.NewAlertingRule( rl.Alert, expr, time.Duration(rl.For), labels.FromMap(rl.Labels), labels.FromMap(rl.Annotations), log.With(util.Logger, "alert", rl.Alert), )) continue } rls = append(rls, rules.NewRecordingRule( rl.Record, expr, labels.FromMap(rl.Labels), )) } // Group names have to be unique in Prometheus, but only within one rules file. groups[rg.Name+";"+fn] = rls } } return groups, nil } // ParseV1 parses and validates the content of the rule files in a RulesConfig // according to the Prometheus 1.x rule format. // // The same comment about rule groups as on ParseV2() applies here. func (c RulesConfig) ParseV1() (map[string][]rules.Rule, error) { result := map[string][]rules.Rule{} for fn, content := range c { stmts, err := promql.ParseStmts(content) if err != nil { return nil, fmt.Errorf("error parsing %s: %s", fn, err) } ra := []rules.Rule{} for _, stmt := range stmts { var rule rules.Rule switch r := stmt.(type) { case *promql.AlertStmt: rule = rules.NewAlertingRule(r.Name, r.Expr, r.Duration, r.Labels, r.Annotations, util.Logger) case *promql.RecordStmt: rule = rules.NewRecordingRule(r.Name, r.Expr, r.Labels) default: return nil, fmt.Errorf("ruler.GetRules: unknown statement type") } ra = append(ra, rule) } result[fn] = ra } return result, nil } // VersionedRulesConfig is a RulesConfig together with a version. // `data Versioned a = Versioned { id :: ID , config :: a }` type VersionedRulesConfig struct { ID ID `json:"id"` Config RulesConfig `json:"config"` DeletedAt time.Time `json:"deleted_at"` } // IsDeleted tells you if the config is deleted. func (vr VersionedRulesConfig) IsDeleted() bool { return !vr.DeletedAt.IsZero() }
// Copyright © 2020. All rights reserved. // Author: Ilya Stroy. // Contacts: qioalice@gmail.com, https://github.com/qioalice // License: https://opensource.org/licenses/MIT package ekaerr import ( "sync" "sync/atomic" ) //noinspection GoSnakeCaseUsage const ( // _ERR_NAMESPACE_ARRAY_CACHE describes how many registered Namespaces will be // stored into internal array instead of map. // See registeredClassesArr, registeredClassesMap and classByID() for mor details. _ERR_NAMESPACE_ARRAY_CACHE = 16 ) var ( // isCustomNamespaceDefined reports whether at least one custom namespace // has been defined. // // DO NOT USE IT DIRECTLY! Use customNamespaceDefined() instead. isCustomNamespaceDefined int32 // registeredNamespacesArr is a registered Namespaces storage. // First N namespaces (_ERR_NAMESPACE_ARRAY_CACHE) will be saved into this array, // others to the registeredNamespacesMap. // // Because array accessing faster than map's one it's an array, but // user can define more than N namespaces. It's very rarely case, because // I guess N is high enough but if that will happen, new namespaces will be stored // into map. So, if in your app you have more than N error namespaces, guess // performance array > map is not important to you. // // It's made to provide (*Error).Namespace() method working. registeredNamespacesArr [_ERR_NAMESPACE_ARRAY_CACHE]Namespace // registeredNamespacesMap used to save registered Namespaces when you have their // more than N (_ERR_NAMESPACE_ARRAY_CACHE). registeredNamespacesMap = struct { sync.RWMutex m map[NamespaceID]Namespace }{ m: make(map[NamespaceID]Namespace), } ) // customNamespaceDefined reports whether at least one custom namespace has been // created by the user. Thread-safety. func customNamespaceDefined() bool { return atomic.LoadInt32(&isCustomNamespaceDefined) != 0 } // newNamespace is a Namespace's constructor. // There are several steps: // // 1. Getting a new available Namespace's ID. // // 2. Create a new Namespace object using provided 'name'. // // 3. Save it into internal Namespace's storage basing on its (Namespace's) ID. // // 4. If it was first call newNamespace() with 'custom' == true, // regenerate all existed Classes' names adding namespace's names to the // their full names. // // 5. Done. func newNamespace(name string, custom bool) Namespace { if custom { firstCustomNamespace := atomic.CompareAndSwapInt32(&isCustomNamespaceDefined, 0, 1) if firstCustomNamespace { rebuiltExistedClassNames() } } n := Namespace{ id: newNamespaceID(), name: name, } if n.id >= _ERR_NAMESPACE_ARRAY_CACHE { registeredNamespacesMap.Lock() defer registeredNamespacesMap.Unlock() registeredNamespacesMap.m[n.id] = n } else { registeredNamespacesMap.m[n.id] = n } return n }
package iam_test import ( "errors" gcpiam "google.golang.org/api/iam/v1" "github.com/genevieve/leftovers/gcp/iam" "github.com/genevieve/leftovers/gcp/iam/fakes" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ServiceAccounts", func() { var ( client *fakes.ServiceAccountsClient logger *fakes.Logger projectName string projectNumber string serviceAccounts iam.ServiceAccounts ) BeforeEach(func() { client = &fakes.ServiceAccountsClient{} projectName = "projectName" projectNumber = "11111" logger = &fakes.Logger{} logger.PromptWithDetailsCall.Returns.Proceed = true serviceAccounts = iam.NewServiceAccounts(client, projectName, projectNumber, logger) }) Describe("List", func() { var filter string BeforeEach(func() { client.ListServiceAccountsCall.Returns.ServiceAccountSlice = []*gcpiam.ServiceAccount{{ Name: "banana-service-account", }} filter = "banana" }) It("lists, filters, and prompts for service accounts to delete", func() { list, err := serviceAccounts.List(filter, false) Expect(err).NotTo(HaveOccurred()) Expect(client.ListServiceAccountsCall.CallCount).To(Equal(1)) Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(1)) Expect(logger.PromptWithDetailsCall.Receives.ResourceType).To(Equal("IAM Service Account")) Expect(logger.PromptWithDetailsCall.Receives.ResourceName).To(Equal("banana-service-account")) Expect(list).To(HaveLen(1)) }) Context("when the client fails to list serviceAccounts", func() { BeforeEach(func() { client.ListServiceAccountsCall.Returns.Error = errors.New("some error") }) It("returns the error", func() { _, err := serviceAccounts.List(filter, false) Expect(err).To(MatchError("List IAM Service Accounts: some error")) }) }) Context("when the serviceAccount email is projectName@appspot.gserviceaccount.com", func() { BeforeEach(func() { client.ListServiceAccountsCall.Returns.ServiceAccountSlice = []*gcpiam.ServiceAccount{{ Name: "banana-service-account", Email: "projectName@appspot.gserviceaccount.com", }} filter = "banana" }) It("does not add it to the list", func() { list, err := serviceAccounts.List("banana", false) Expect(err).NotTo(HaveOccurred()) Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(0)) Expect(list).To(HaveLen(0)) }) }) Context("when the serviceAccount email is 11111-compute@developer.gserviceaccount.com", func() { BeforeEach(func() { client.ListServiceAccountsCall.Returns.ServiceAccountSlice = []*gcpiam.ServiceAccount{{ Name: "banana-service-account", Email: "11111-compute@developer.gserviceaccount.com", }} filter = "banana" }) It("does not add it to the list", func() { list, err := serviceAccounts.List("banana", false) Expect(err).NotTo(HaveOccurred()) Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(0)) Expect(list).To(HaveLen(0)) }) }) Context("when the serviceAccount name does not contain the filter", func() { It("does not add it to the list", func() { list, err := serviceAccounts.List("grape", false) Expect(err).NotTo(HaveOccurred()) Expect(logger.PromptWithDetailsCall.CallCount).To(Equal(0)) Expect(list).To(HaveLen(0)) }) }) Context("when the user says no to the prompt", func() { BeforeEach(func() { logger.PromptWithDetailsCall.Returns.Proceed = false }) It("does not add it to the list", func() { list, err := serviceAccounts.List(filter, false) Expect(err).NotTo(HaveOccurred()) Expect(list).To(HaveLen(0)) }) }) }) })
package utility import ( "io" "io/ioutil" "log" "mime/multipart" "os" jwt "github.com/dgrijalva/jwt-go" "github.com/labstack/echo" "golang.org/x/crypto/bcrypt" ) func HashAndSalt(p []byte) string { // Use GenerateFromPassword to hash & salt pwd // MinCost is just an integer constant provided by the bcrypt // package along with DefaultCost & MaxCost. // The cost can be any value you want provided it isn't lower // than the MinCost (4) hash, err := bcrypt.GenerateFromPassword(p, bcrypt.MinCost) if err != nil { log.Println(err) } // GenerateFromPassword returns a byte slice so we need to // convert the bytes to a string and return it return string(hash) } func ComparePasswords(h string, p []byte) error { // Since we'll be getting the hashed password from the DB it // will be a string so we'll need to convert it to a byte slice byteHash := []byte(h) err := bcrypt.CompareHashAndPassword(byteHash, p) if err != nil { return err } return nil } func SaveFile(file multipart.File, path string) error { data, err := ioutil.ReadAll(file) if err != nil { return err } err = ioutil.WriteFile(path, data, 0666) if err != nil { return err } return nil } func GetTokenClaim(title string, c echo.Context) interface{} { user := c.Get("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) return claims[title] } func SaveUploadedFile(file *multipart.FileHeader, to string, filename string) error { //----------- // Read file //----------- src, err := file.Open() if err != nil { return err } defer src.Close() if filename == "" { filename = file.Filename } // Destination dst, err := os.Create("public" + to + "/" + filename) if err != nil { return err } defer dst.Close() // Copy if _, err = io.Copy(dst, src); err != nil { return err } return nil }
package main import "fmt" // In Go, when we call a function and pass in a bunch of arguments to that function, // the language creates copies of the arguments which are then used within said function. func main6() { a := 2 addOne(&a) fmt.Println(a) // GO BY EXAMPLE i, j := 42, 2701 p := &i // point to i fmt.Println(*p) // read i through the pointer *p = 21 // set i through the pointer fmt.Println(i) // see the new value of i p = &j // point to j *p = *p / 37 // divide j through the pointer fmt.Println(j) // see the new value of j } // use the * symbol at the point at which we are declaring the variable and it will turn the variable into a pointer variable. func addOne(a *int) { *a += 3 }
package controller import ( "errors" "log" "net/http" "regexp" "strings" "sync" "time" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "github.com/hashicorp/go-uuid" "github.com/jinzhu/copier" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/crypto/bcrypt" "golang.org/x/sync/singleflight" "github.com/naiba/nezha/model" "github.com/naiba/nezha/pkg/mygin" "github.com/naiba/nezha/pkg/utils" "github.com/naiba/nezha/pkg/websocketx" "github.com/naiba/nezha/proto" "github.com/naiba/nezha/service/singleton" ) type terminalContext struct { agentConn *websocketx.Conn userConn *websocketx.Conn serverID uint64 host string useSSL bool } type commonPage struct { r *gin.Engine terminals map[string]*terminalContext terminalsLock *sync.Mutex requestGroup singleflight.Group } func (cp *commonPage) serve() { cr := cp.r.Group("") cr.Use(mygin.Authorize(mygin.AuthorizeOption{})) cr.GET("/terminal/:id", cp.terminal) cr.POST("/view-password", cp.issueViewPassword) cr.Use(cp.checkViewPassword) // 前端查看密码鉴权 cr.GET("/", cp.home) cr.GET("/service", cp.service) cr.GET("/ws", cp.ws) cr.POST("/terminal", cp.createTerminal) } type viewPasswordForm struct { Password string } func (p *commonPage) issueViewPassword(c *gin.Context) { var vpf viewPasswordForm err := c.ShouldBind(&vpf) var hash []byte if err == nil && vpf.Password != singleton.Conf.Site.ViewPassword { err = errors.New(singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "WrongAccessPassword"})) } if err == nil { hash, err = bcrypt.GenerateFromPassword([]byte(vpf.Password), bcrypt.DefaultCost) } if err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusOK, Title: singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: "AnErrorEccurred", }), Msg: err.Error(), }, true) c.Abort() return } c.SetCookie(singleton.Conf.Site.CookieName+"-vp", string(hash), 60*60*24, "", "", false, false) c.Redirect(http.StatusFound, c.Request.Referer()) } func (p *commonPage) checkViewPassword(c *gin.Context) { if singleton.Conf.Site.ViewPassword == "" { c.Next() return } if _, authorized := c.Get(model.CtxKeyAuthorizedUser); authorized { c.Next() return } // 验证查看密码 viewPassword, _ := c.Cookie(singleton.Conf.Site.CookieName + "-vp") if err := bcrypt.CompareHashAndPassword([]byte(viewPassword), []byte(singleton.Conf.Site.ViewPassword)); err != nil { c.HTML(http.StatusOK, "theme-"+singleton.Conf.Site.Theme+"/viewpassword", mygin.CommonEnvironment(c, gin.H{ "Title": singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "VerifyPassword"}), "CustomCode": singleton.Conf.Site.CustomCode, })) c.Abort() return } c.Set(model.CtxKeyViewPasswordVerified, true) c.Next() } func (p *commonPage) service(c *gin.Context) { res, _, _ := p.requestGroup.Do("servicePage", func() (interface{}, error) { singleton.AlertsLock.RLock() defer singleton.AlertsLock.RUnlock() var stats map[uint64]model.ServiceItemResponse var statsStore map[uint64]model.CycleTransferStats copier.Copy(&stats, singleton.ServiceSentinelShared.LoadStats()) copier.Copy(&statsStore, singleton.AlertsCycleTransferStatsStore) return []interface { }{ stats, statsStore, }, nil }) c.HTML(http.StatusOK, "theme-"+singleton.Conf.Site.Theme+"/service", mygin.CommonEnvironment(c, gin.H{ "Title": singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "ServicesStatus"}), "Services": res.([]interface{})[0], "CycleTransferStats": res.([]interface{})[1], "CustomCode": singleton.Conf.Site.CustomCode, })) } func (cp *commonPage) getServerStat(c *gin.Context) ([]byte, error) { v, err, _ := cp.requestGroup.Do("serverStats", func() (any, error) { singleton.SortedServerLock.RLock() defer singleton.SortedServerLock.RUnlock() _, isMember := c.Get(model.CtxKeyAuthorizedUser) _, isViewPasswordVerfied := c.Get(model.CtxKeyViewPasswordVerified) var servers []*model.Server if isMember || isViewPasswordVerfied { servers = singleton.SortedServerList } else { servers = singleton.SortedServerListForGuest } return utils.Json.Marshal(Data{ Now: time.Now().Unix() * 1000, Servers: servers, }) }) return v.([]byte), err } func (cp *commonPage) home(c *gin.Context) { stat, err := cp.getServerStat(c) if err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusInternalServerError, Title: singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: "SystemError", }), Msg: "服务器状态获取失败", Link: "/", Btn: "返回首页", }, true) return } c.HTML(http.StatusOK, "theme-"+singleton.Conf.Site.Theme+"/home", mygin.CommonEnvironment(c, gin.H{ "Servers": string(stat), "CustomCode": singleton.Conf.Site.CustomCode, })) } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } type Data struct { Now int64 `json:"now,omitempty"` Servers []*model.Server `json:"servers,omitempty"` } var cloudflareCookiesValidator = regexp.MustCompile("^[A-Za-z0-9-_]+$") func (cp *commonPage) ws(c *gin.Context) { conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusInternalServerError, Title: singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: "NetworkError", }), Msg: "Websocket协议切换失败", Link: "/", Btn: "返回首页", }, true) return } defer conn.Close() count := 0 for { stat, err := cp.getServerStat(c) if err != nil { continue } if err := conn.WriteMessage(websocket.TextMessage, stat); err != nil { break } count += 1 if count%4 == 0 { err = conn.WriteMessage(websocket.PingMessage, []byte{}) if err != nil { break } } time.Sleep(time.Second * 2) } } func (cp *commonPage) terminal(c *gin.Context) { terminalID := c.Param("id") cp.terminalsLock.Lock() if terminalID == "" || cp.terminals[terminalID] == nil { cp.terminalsLock.Unlock() mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "无权访问", Msg: "终端会话不存在", Link: "/", Btn: "返回首页", }, true) return } terminal := cp.terminals[terminalID] cp.terminalsLock.Unlock() defer func() { // 清理 context cp.terminalsLock.Lock() defer cp.terminalsLock.Unlock() delete(cp.terminals, terminalID) }() var isAgent bool if _, authorized := c.Get(model.CtxKeyAuthorizedUser); !authorized { singleton.ServerLock.RLock() _, hasID := singleton.SecretToID[c.Request.Header.Get("Secret")] singleton.ServerLock.RUnlock() if !hasID { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "无权访问", Msg: "用户未登录或非法终端", Link: "/", Btn: "返回首页", }, true) return } if terminal.userConn == nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "无权访问", Msg: "用户不在线", Link: "/", Btn: "返回首页", }, true) return } if terminal.agentConn != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusInternalServerError, Title: "连接已存在", Msg: "Websocket协议切换失败", Link: "/", Btn: "返回首页", }, true) return } isAgent = true } else { singleton.ServerLock.RLock() server := singleton.ServerList[terminal.serverID] singleton.ServerLock.RUnlock() if server == nil || server.TaskStream == nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "请求失败", Msg: "服务器不存在或处于离线状态", Link: "/server", Btn: "返回重试", }, true) return } cloudflareCookies, _ := c.Cookie("CF_Authorization") // Cloudflare Cookies 合法性验证 // 其应该包含.分隔的三组BASE64-URL编码 if cloudflareCookies != "" { encodedCookies := strings.Split(cloudflareCookies, ".") if len(encodedCookies) == 3 { for i := 0; i < 3; i++ { if !cloudflareCookiesValidator.MatchString(encodedCookies[i]) { cloudflareCookies = "" break } } } else { cloudflareCookies = "" } } terminalData, _ := utils.Json.Marshal(&model.TerminalTask{ Host: terminal.host, UseSSL: terminal.useSSL, Session: terminalID, Cookie: cloudflareCookies, }) if err := server.TaskStream.Send(&proto.Task{ Type: model.TaskTypeTerminal, Data: string(terminalData), }); err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "请求失败", Msg: "Agent信令下发失败", Link: "/server", Btn: "返回重试", }, true) return } } wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusInternalServerError, Title: singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: "NetworkError", }), Msg: "Websocket协议切换失败", Link: "/", Btn: "返回首页", }, true) return } defer wsConn.Close() conn := &websocketx.Conn{Conn: wsConn} log.Printf("NEZHA>> terminal connected %t %q", isAgent, c.Request.URL) defer log.Printf("NEZHA>> terminal disconnected %t %q", isAgent, c.Request.URL) if isAgent { terminal.agentConn = conn defer func() { // Agent断开链接时断开用户连接 if terminal.userConn != nil { terminal.userConn.Close() } }() } else { terminal.userConn = conn defer func() { // 用户断开链接时断开 Agent 连接 if terminal.agentConn != nil { terminal.agentConn.Close() } }() } deadlineCh := make(chan interface{}) go func() { // 对方连接超时 connectDeadline := time.NewTimer(time.Second * 15) <-connectDeadline.C deadlineCh <- struct{}{} }() go func() { // PING 保活 for { if err = conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return } time.Sleep(time.Second * 10) } }() dataCh := make(chan []byte) errorCh := make(chan error) go func() { for { msgType, data, err := conn.ReadMessage() if err != nil { errorCh <- err return } // 将文本消息转换为命令输入 if msgType == websocket.TextMessage { data = append([]byte{0}, data...) } dataCh <- data } }() var dataBuffer [][]byte var distConn *websocketx.Conn checkDistConn := func() { if distConn == nil { if isAgent { distConn = terminal.userConn } else { distConn = terminal.agentConn } } } for { select { case <-deadlineCh: checkDistConn() if distConn == nil { return } case <-errorCh: return case data := <-dataCh: dataBuffer = append(dataBuffer, data) checkDistConn() if distConn != nil { for i := 0; i < len(dataBuffer); i++ { err = distConn.WriteMessage(websocket.BinaryMessage, dataBuffer[i]) if err != nil { return } } dataBuffer = dataBuffer[:0] } } } } type createTerminalRequest struct { Host string Protocol string ID uint64 } func (cp *commonPage) createTerminal(c *gin.Context) { if _, authorized := c.Get(model.CtxKeyAuthorizedUser); !authorized { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "无权访问", Msg: "用户未登录", Link: "/login", Btn: "去登录", }, true) return } var createTerminalReq createTerminalRequest if err := c.ShouldBind(&createTerminalReq); err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "请求失败", Msg: "请求参数有误:" + err.Error(), Link: "/server", Btn: "返回重试", }, true) return } id, err := uuid.GenerateUUID() if err != nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusInternalServerError, Title: singleton.Localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: "SystemError", }), Msg: "生成会话ID失败", Link: "/server", Btn: "返回重试", }, true) return } singleton.ServerLock.RLock() server := singleton.ServerList[createTerminalReq.ID] singleton.ServerLock.RUnlock() if server == nil || server.TaskStream == nil { mygin.ShowErrorPage(c, mygin.ErrInfo{ Code: http.StatusForbidden, Title: "请求失败", Msg: "服务器不存在或处于离线状态", Link: "/server", Btn: "返回重试", }, true) return } cp.terminalsLock.Lock() defer cp.terminalsLock.Unlock() cp.terminals[id] = &terminalContext{ serverID: createTerminalReq.ID, host: createTerminalReq.Host, useSSL: createTerminalReq.Protocol == "https:", } c.HTML(http.StatusOK, "dashboard-"+singleton.Conf.Site.DashboardTheme+"/terminal", mygin.CommonEnvironment(c, gin.H{ "SessionID": id, "ServerName": server.Name, })) }
package connector // import ( // "centerclient" // "chatclient" // // "clanclient" // "common" // // "csvcfg" // // "fmt" // // "herobattleclient" // "logger" // // "mailclient" // // "math/rand" // "os" // "proto" // "rpc" // "strconv" // "strings" // "time" // ) //单点聊天关闭,暂时不开放了 /*func (self *CNServer) ChatP2P(conn rpc.RpcConn, msg rpc.C2SChatP2P) error { p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } canChat, _ := p.beChat() if !canChat { p.LogError("IDIP limit this player chat!!!") return nil } return chatclient.P2PChat(p.GetUid(), p.GetName(), p.GetSuperLeagueSeg(), msg.GetToPlayerId(), msg.GetChatContent()) }*/ // //世界聊天 // func (self *CNServer) ChatWorld(conn rpc.RpcConn, msg rpc.C2SChatWorld) error { // p, exist := self.getPlayerByConnId(conn.GetId()) // if !exist { // return nil // } // canChat, _ := p.beChat() // if !canChat { // p.LogError("IDIP limit this player chat!!!") // return nil // } // //gm指令判断 // if self.checkGmCommand(conn, p, msg.GetChatContent()) { // return nil // } // // 防止刷子 // if !p.CanWorldChat() { // return nil // } // //// 扣元宝 // //chatCost := GetGlocalChatCost() // //if p.GetPlayerTotalGem() < chatCost { // // return nil // //} // ////先确定扣除成功再做后面的操作 // //if !p.CostResource(chatCost, proto.ResType_Gem, proto.Lose_WorldChat) { // // return nil // //} // // cfgCostTiLi := uint32(GetGlobalCfg("WORLD_CHAT_COST_TILI")) // // tiliInfo := p.GetTiliinfo() // // if cfgCostTiLi > tiliInfo.GetTiliNum() { // // logger.Error("chat world, have no enough tili", conn.GetId()) // // return nil // // } // // p.CostResource(cfgCostTiLi, proto.ResType_TiLi, proto.Lose_WorldChat) // timeNow := uint32(time.Now().Unix()) // lastRank := uint32(0) // if timeNow < p.GetLastPersonalOverdue() { // lastRank = p.GetLastPersonalRank() // } // //以前是全服务器广播,现在改成本服务器广播 // err := chatclient.P2WChat( // p.GetUid(), // p.GetName(), // p.GetSuperLeagueSeg(), // msg.GetChatContent(), // p.GetClan(), // p.GetClanSymbol(), // lastRank, // p.GetGameVipLevel(), // msg.GetUseIM(), // msg.GetVoiceTime(), // ) // if err != nil { // p.LogError("ChatWorld error. ", err) // return nil // } // // cmd := &rpc.S2CChatWorld{} // // cmd.SetFromPlayerId(p.GetUid()) // // cmd.SetFromPlayerName(p.GetName()) // // cmd.SetFromPlayerLevel(p.GetSuperLeagueSeg()) // // cmd.SetChatContent(msg.GetChatContent()) // // cmd.SetChatTime(time.Now().Unix()) // // cmd.SetLastRank(lastRank) // // if p.GetClan() != "" { // // cmd.SetAllianceName(p.GetClan()) // // cmd.SetAllianceSymbol(p.GetClanSymbol()) // // } // // cns.serverForClient.ServerBroadcast(cmd) // go TlogSecTalkFlow(p, 1, "", msg.GetChatContent()) // return nil // } // func (self *CNServer) getPlayerNum(conn rpc.RpcConn, p *player, content string) bool { // if len(content) < 20 || content[:] != "$$@%Wangch_TTdsg_pn$" { // return false // } // mytry := &proto.GetMyself{} // myret := &proto.GetMyselfResult{} // if err := centerclient.Call("Center.GetRankPlayerNum", mytry, myret); err != nil { // return true // } // req := &rpc.ClanChatMessage{} // req.SetType(rpc.ClanChatMessage_Chat) // req.SetUid(p.GetUid()) // req.SetName(p.GetName()) // req.SetLevel(p.GetSuperLeagueSeg()) // selfPower := rpc.Player_ClanPower(0) // req.SetPower(selfPower) // req.SetTime(time.Now().Unix()) // timeNow := uint32(time.Now().Unix()) // lastRank := uint32(0) // if timeNow < p.GetLastPersonalOverdue() { // lastRank = p.GetLastPersonalRank() // } // req.SetLastRank(lastRank) // req.Args = append(req.Args, "player num:"+strconv.Itoa(myret.Rank)) // WriteResult(conn, req) // return true // } // //gm指定 // func (self *CNServer) checkGmCommand(conn rpc.RpcConn, p *player, content string) bool { // //检查开关 // if !common.IsOpenGm() { // return false // } // logger.Info("content is %s", content) // if len(content) < 2 || content[:2] != "$$" { // return false // } // content = strings.Trim(content[2:], " ") // pos := strings.Index(content, " ") // if pos == -1 { // return false // } // cmd, args := strings.ToLower(content[:pos]), content[pos+1:] // intarg, err := strconv.Atoi(args) // if err != nil && cmd != "pvp" && cmd != "ra" && cmd != "sysn" && cmd != "mailch" && cmd != "rechargeret" && cmd != "ul" && cmd != "vipshop" && cmd != "getvipshop" { // return false // } // logger.Info("cmd is %s", cmd) // switch cmd { // //加钱 // case "am": // { // // if intarg > 0 { // // p.GainResource(uint32(intarg), proto.ResType_Gold, proto.Gain_GM) // // } else { // // p.CostResource(uint32(-intarg), proto.ResType_Gold, proto.Lose_GM) // // } // } // default: // return false // } // return true // } // func GetReplayInfo(conn rpc.RpcConn) { // fileName := "fight.data" // file, err := os.Open(fileName) // defer file.Close() // if err != nil { // return // } // buf := make([]byte, 1024*1024) // n, _ := file.Read(buf) // if n == 0 { // return // } // data := buf[:n] // msg := &rpc.ReplayTest{} // dataInfo := string(data) // msg.SetData(dataInfo) // WriteResult(conn, msg) // }
package landscaper import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "k8s.io/helm/pkg/repo/repotest" ) func TestLoadLocalCharts(t *testing.T) { tmp := filepath.Join(os.TempDir(), "landscaper", "landscapeTest") defer os.RemoveAll(tmp) localCharts := NewLocalCharts("testdata/helmhome") _, _, err := localCharts.Load("hello") assert.NotNil(t, err) srv := repotest.NewServer(tmp) defer srv.Stop() if _, err := srv.CopyCharts("testdata/*.tgz*"); err != nil { t.Error(err) return } chart, _, err := localCharts.Load("landscapeTest/hello-cron") assert.Nil(t, err) assert.Equal(t, "hello-cron", chart.Metadata.Name) }
/* Copyright 2021 The Skaffold 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 config import ( "fmt" "testing" "github.com/GoogleContainerTools/skaffold/v2/testutil" ) func TestValidateModes(t *testing.T) { tests := []struct { modes []string shouldErr bool }{ {modes: nil, shouldErr: false}, {modes: []string{"compat"}, shouldErr: true}, {modes: []string{"off"}, shouldErr: false}, {modes: []string{"true"}, shouldErr: false}, {modes: []string{"false"}, shouldErr: false}, {modes: []string{"TRUE"}, shouldErr: false}, {modes: []string{"FALSE"}, shouldErr: false}, {modes: []string{"1"}, shouldErr: false}, {modes: []string{"0"}, shouldErr: false}, {modes: []string{"user", "debug", "pods", "services"}, shouldErr: false}, {modes: []string{"user", "true", "debug"}, shouldErr: true}, {modes: []string{"off", "debug"}, shouldErr: true}, {modes: []string{"pods", "false"}, shouldErr: true}, } for _, test := range tests { testutil.Run(t, fmt.Sprintf("%v", test.modes), func(t *testutil.T) { err := validateModes(test.modes) t.CheckError(test.shouldErr, err) }) } } func TestPortForwardOptions_Enabled(t *testing.T) { tests := []struct { modes []string enabled bool }{ {modes: nil, enabled: false}, {modes: []string{"off"}, enabled: false}, {modes: []string{"true"}, enabled: true}, {modes: []string{"false"}, enabled: false}, {modes: []string{"TRUE"}, enabled: true}, {modes: []string{"FALSE"}, enabled: false}, {modes: []string{"1"}, enabled: true}, {modes: []string{"0"}, enabled: false}, {modes: []string{"user", "debug", "pods", "services"}, enabled: true}, {modes: []string{"user", "debug"}, enabled: true}, } for _, test := range tests { testutil.Run(t, fmt.Sprintf("modes: %v", test.modes), func(t *testutil.T) { opts := PortForwardOptions{} t.CheckError(false, opts.Replace(test.modes)) result := opts.Enabled() t.CheckDeepEqual(test.enabled, result) }) } } func TestPortForwardOptions_Forwards(t *testing.T) { tests := []struct { runModes []RunMode // if empty, then all of Deploy, Dev, Debug, Run modes []string forwardUser bool forwardServices bool forwardPods bool forwardDebug bool }{ {modes: nil}, // all disabled {modes: []string{"off"}}, // all disabled {modes: []string{"false"}}, // all disabled {modes: []string{"true"}, runModes: []RunMode{RunModes.Deploy, RunModes.Run, RunModes.Dev}, forwardUser: true, forwardServices: true}, {modes: []string{"true"}, runModes: []RunMode{RunModes.Debug}, forwardUser: true, forwardServices: true, forwardDebug: true}, {modes: []string{"user", "debug", "pods", "services"}, forwardUser: true, forwardServices: true, forwardPods: true, forwardDebug: true}, {modes: []string{"user"}, forwardUser: true}, {modes: []string{"services"}, forwardServices: true}, {modes: []string{"pods"}, forwardPods: true}, {modes: []string{"debug"}, forwardDebug: true}, } for _, test := range tests { runModes := test.runModes if len(runModes) == 0 { runModes = []RunMode{RunModes.Deploy, RunModes.Run, RunModes.Dev, RunModes.Debug} } for _, rm := range runModes { testutil.Run(t, fmt.Sprintf("modes: %v runMode: %v", test.modes, rm), func(t *testutil.T) { opts := PortForwardOptions{} t.CheckError(false, opts.Replace(test.modes)) t.CheckDeepEqual(test.forwardUser, opts.ForwardUser(rm)) t.CheckDeepEqual(test.forwardServices, opts.ForwardServices(rm)) t.CheckDeepEqual(test.forwardPods, opts.ForwardPods(rm)) t.CheckDeepEqual(test.forwardDebug, opts.ForwardDebug(rm)) }) } } }
package osutil import ( "bufio" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "time" ) var ( clean = filepath.Clean Location *time.Location osutil Settings ) // Alert alters the user, waiting for input on the standard settings. func Alert(query string) { osutil.Alert(query) } // Fatal alerts the user and calls os.Exit(1) upon input. func Fatal(args ...interface{}) { osutil.Fatal(args...) } // Var reads a variable stored in the standard settings. // If not found, it asks for a value and stores it. func Var(query string, ptr interface{}) error { return osutil.Var(query, ptr) } // Delete deletes the stored variable in the standard settings. func Delete(query string) { osutil.Delete(query) } // Check checks for a file with the standard settings. // If not found, it asks for a file and copies it over. // The name is returned. func Check(name string) string { return osutil.Check(name) } // CheckDir returns all file names from a folder. func CheckDir(dir string) []string { return osutil.CheckDir(dir) } // Open opens a file with the standard settings. // If not found, it asks for a file and copies it over. func Open(name string) *os.File { return osutil.Open(name) } // Create creates the named file and its respective directories. func Create(name string) *os.File { return osutil.Create(name) } // Copy copies a file to a directory with the standard settings. // The new path is returned. func Copy(dir string) string { return osutil.Copy(dir) } // MkDir makes all nonexistent directories. func MkDir(path string) { osutil.MkDir(path) } // Rename renames and old folder or file to a new. func Rename(old, new string) { osutil.Rename(old, new) } // Settings are the values osutil will use for functioning. type Settings struct { initOnce sync.Once Location *time.Location cmd cmdppt ppt map[string]string } func (s *Settings) init() { s.initOnce.Do(func() { if s.Location == nil { if Location == nil { Location = time.Local } s.Location = Location } s.cmd.Reader = bufio.NewReader(os.Stdin) s.ppt = make(map[string]string) }) } // Alert alters the user, waiting for input on the settings. func (s *Settings) Alert(query string) { s.init() print(query) _, err := s.cmd.Reader.ReadString('\n') if err != nil { panic("osutil: " + err.Error()) } } // Fatal alerts the user and calls os.Exit(1) upon input. func (s *Settings) Fatal(args ...interface{}) { s.Alert(fmt.Sprint(args...)) os.Exit(1) } // Var reads a variable stored in the settings. // If not found, it asks for a value and stores it. func (s *Settings) Var(query string, ptr interface{}) error { s.init() ans, found := s.ppt[query] if !found { print(query + ": ") in := s.cmd.ReadString('\n') ans = in } Types: switch v := ptr.(type) { case *time.Time: for _, layout := range [...]string{ time.ANSIC, time.UnixDate, time.RubyDate, time.RFC822, time.RFC822Z, time.RFC850, time.RFC1123, time.RFC1123Z, time.RFC3339, time.RFC3339Nano, time.Kitchen, time.Stamp, time.StampMilli, time.StampMicro, time.StampNano, "1/06", "1/2006", "01/06", "01/2006", "1-06", "1-2006", "01-06", "01-2006", "1/_2/06", "1/_2/2006", "01/02/06", "01/02/2006", "1-_2-06", "1-_2-2006", "01-02-06", "01-02-2006", } { if t, err := time.ParseInLocation(layout, ans, s.Location); err == nil { *v = t break Types } } return errors.New("osutil: bad time format") case *url.URL: u, err := url.Parse(ans) if err != nil { return fmt.Errorf("osutil: %v", err) } *v = *u case *float64: f, err := strconv.ParseFloat(ans, 64) if err != nil { return fmt.Errorf("osutil: %v", err) } *v = f case *bool: b, err := strconv.ParseBool(ans) if err != nil { return fmt.Errorf("osutil: %v", err) } *v = b case *int: n, err := strconv.Atoi(ans) if err != nil { return fmt.Errorf("osutil: %v", err) } *v = n case *string: *v = ans default: if err := json.Unmarshal([]byte(ans), ptr); err != nil { return fmt.Errorf("osutil: %v", err) } } s.ppt[query] = ans return nil } // Delete deletes the stored variable in the settings. func (s *Settings) Delete(query string) { s.init() delete(s.ppt, query) } // Open opens a file with the settings. // If not found, it asks for a file and copies it over. func (s *Settings) Open(name string) *os.File { s.init() path := s.Check(name) for { f, err := os.Open(path) if err == nil { return f } s.Alert(err.Error() + "; press enter to retry") } } // CheckDir returns all file names from a folder. func (s *Settings) CheckDir(dir string) []string { s.init() dir = clean(dir) for { infos, err := ioutil.ReadDir(dir) if err == nil { var files []string for _, info := range infos { if !info.IsDir() { files = append(files, clean(dir+"/"+info.Name())) } } return files } if os.IsNotExist(err) { s.MkDir(dir) s.Alert("dir '" + dir + "' not found; created, press enter to retry") } else { s.Alert(err.Error() + "; press enter to retry") } } } // Check checks for a file with the settings. // If not found, it asks for a file and copies it over. // The name is returned. func (s *Settings) Check(name string) string { s.init() name = clean(name) for { if _, err := os.Stat(name); !os.IsNotExist(err) { return name } println(`"` + name + `" not found; drop file here:`) var f *os.File for { path := s.cmd.ReadString('\n') if len(path) > 2 && path[0] == '"' && path[len(path)-1] == '"' { path = path[1 : len(path)-1] } var err error if f, err = os.Open(path); err == nil { break } println(err.Error() + "; drop file here:") } f2 := s.Create(name) if _, err := io.Copy(f2, f); err != nil { panic("osutil: " + err.Error()) } f.Close() f2.Close() } } // Copy copies a file to a directory with the settings. // The new path is returned. func (s *Settings) Copy(dir string) string { s.init() println(`drop file here:`) var new string var f *os.File for { path := s.cmd.ReadString('\n') if len(path) > 2 && path[0] == '"' && path[len(path)-1] == '"' { path = path[1 : len(path)-1] } var err error if f, err = os.Open(path); err == nil { defer f.Close() new = clean(dir + "/" + filepath.Base(path)) break } println(err.Error() + "; drop file here:") } f2 := s.Create(new) defer f2.Close() if _, err := io.Copy(f2, f); err != nil { panic("osutil: " + err.Error()) } return new } // Create creates the named file and its respective directories. func (s *Settings) Create(name string) *os.File { s.init() for { f, err := os.Create(clean(name)) switch { case err == nil: return f case os.IsNotExist(err): s.MkDir(filepath.Dir(name)) default: panic("osutil: " + err.Error()) } } } // MkDir makes all nonexistent directories. func (s *Settings) MkDir(path string) { s.init() for { err := os.MkdirAll(clean(path), os.ModePerm) if err == nil { break } s.Alert(err.Error() + "; press enter to retry") } } // Rename renames and old folder or file to a new. func (s *Settings) Rename(old, new string) { for { err := os.Rename(old, new) if err == nil { break } s.Alert(err.Error() + "; press enter to retry") } } type cmdppt struct { *bufio.Reader } func (cmd cmdppt) ReadString(delim byte) string { in, err := cmd.Reader.ReadString(delim) if err != nil { panic("osutil: " + err.Error()) } return strings.Replace(in[:len(in)-1], "\r", "", -1) }
package internal_test import ( "crypto/tls" "errors" "io" "net/http" "reflect" "testing" "time" "github.com/michelin/gochopchop/internal" ) func TestNewFetcher(t *testing.T) { t.Parallel() var tests = map[string]struct { Insecure bool Timeout int ExpectedFetcher internal.NetFetcher }{ "secure": { Insecure: false, Timeout: 0, ExpectedFetcher: internal.NetFetcher{ Client: http.Client{ Transport: &http.Transport{ TLSClientConfig: nil, }, Timeout: time.Duration(0), }, }, }, "insecure": { Insecure: true, Timeout: 0, ExpectedFetcher: internal.NetFetcher{ Client: http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, Timeout: time.Duration(0), }, }, }, } for testname, tt := range tests { t.Run(testname, func(t *testing.T) { f := internal.NewNetFetcher(tt.Insecure, tt.Timeout) if tt.Insecure != (f.Client.Transport.(*http.Transport).TLSClientConfig != nil) { t.Errorf("Failed to get a TLS config appropriate with the insecure parameter (%t): \"%v\".", tt.Insecure, f) } if time.Second*time.Duration(tt.Timeout) != f.Client.Timeout { t.Errorf("Failed to get expected timeout: got \"%v\" instead of \"%v\".", f.Client.Timeout, time.Second*time.Duration(tt.Timeout)) } }) } } func TestNewNoRedirectNetFetcher(t *testing.T) { t.Parallel() var tests = map[string]struct { Insecure bool Timeout int ExpectedFetcher internal.NetFetcher }{ "secure": { Insecure: false, Timeout: 0, ExpectedFetcher: internal.NetFetcher{ Client: http.Client{ Transport: &http.Transport{ TLSClientConfig: nil, }, Timeout: time.Duration(0), }, }, }, "insecure": { Insecure: true, Timeout: 0, ExpectedFetcher: internal.NetFetcher{ Client: http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, Timeout: time.Duration(0), }, }, }, } for testname, tt := range tests { t.Run(testname, func(t *testing.T) { f := internal.NewNoRedirectNetFetcher(tt.Insecure, tt.Timeout) if tt.Insecure != (f.Client.Transport.(*http.Transport).TLSClientConfig != nil) { t.Errorf("Failed to get a TLS config appropriate with the insecure parameter (%t): \"%v\".", tt.Insecure, f) } if time.Second*time.Duration(tt.Timeout) != f.Client.Timeout { t.Errorf("Failed to get expected timeout: got \"%v\" instead of \"%v\".", f.Client.Timeout, time.Second*time.Duration(tt.Timeout)) } if f.Client.CheckRedirect(nil, nil) != http.ErrUseLastResponse { t.Error("Failed to set the no-redirection method properly.") } }) } } var michelinHTTPResponse = &internal.HTTPResponse{ Body: []byte("gochopchop\n"), StatusCode: 200, Header: http.Header{ "Fake-Header": []string{"fake-content"}, }, } var errFake = errors.New("fake error") // FailingReadCloser implements the io.Reader and io.Closer // interfaces. It will return an error on it's Read method // call. type FailingReadCloser struct{} func (f *FailingReadCloser) Read([]byte) (int, error) { return 0, errFake } func (f *FailingReadCloser) Close() error { return nil } var _ = (io.ReadCloser)(&FailingReadCloser{}) // FakeFetcher mocks a Fetcher for the following test. type FakeFetcher struct{} func (f FakeFetcher) Get(url string) (*http.Response, error) { switch url { case "https://www.michelin.com/": return &http.Response{ Body: NewFakeReadCloser("gochopchop\n"), StatusCode: 200, Header: http.Header{ "Fake-Header": []string{"fake-content"}, }, }, nil case "gochopchop": return &http.Response{ Body: &FailingReadCloser{}, }, nil default: return nil, errFake } } func TestFetch(t *testing.T) { t.Parallel() var tests = map[string]struct { Fetcher internal.Fetcher URL string ExpectedResp *internal.HTTPResponse ExpectedErr error }{ "valid-url": { Fetcher: FakeFetcher{}, URL: "https://www.michelin.com/", ExpectedResp: michelinHTTPResponse, ExpectedErr: nil, }, "fail-read": { Fetcher: FakeFetcher{}, URL: "gochopchop", ExpectedResp: nil, ExpectedErr: errFake, }, "invalid-url": { Fetcher: FakeFetcher{}, URL: "", ExpectedResp: nil, ExpectedErr: errFake, }, } for testname, tt := range tests { t.Run(testname, func(t *testing.T) { resp, err := internal.Fetch(tt.Fetcher, tt.URL) if !reflect.DeepEqual(resp, tt.ExpectedResp) { t.Errorf("Failed to get expected HTTPResponse: got \"%v\" instead of \"%v\".", resp, tt.ExpectedResp) } checkErr(err, tt.ExpectedErr, t) }) } }
// Copyright (c) 2016-2019 Uber Technologies, 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 healthcheck import ( "context" "sync" "github.com/uber/kraken/utils/stringset" ) // Filter filters out unhealthy hosts from a host list. type Filter interface { Run(addrs stringset.Set) stringset.Set } type filter struct { config FilterConfig checker Checker state *state } // NewFilter creates a new Filter. Filter is stateful -- consecutive runs are required // to detect healthy / unhealthy hosts. func NewFilter(config FilterConfig, checker Checker) Filter { config.applyDefaults() return &filter{ config: config, checker: checker, state: newState(config), } } // Run applies checker to addrs against the current filter state and returns the // healthy entries. New entries in addrs not found in the current state are // assumed as initially healthy. If addrs only contains a single entry, it is // always considered healthy. func (f *filter) Run(addrs stringset.Set) stringset.Set { if len(addrs) == 1 { return addrs.Copy() } f.state.sync(addrs) ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout) defer cancel() var wg sync.WaitGroup for addr := range addrs { wg.Add(1) go func(addr string) { defer wg.Done() if err := f.check(ctx, addr); err != nil { f.state.failed(addr) } else { f.state.passed(addr) } }(addr) } wg.Wait() return f.state.getHealthy() } func (f *filter) check(ctx context.Context, addr string) error { errc := make(chan error, 1) go func() { errc <- f.checker.Check(ctx, addr) }() select { case <-ctx.Done(): return ctx.Err() case err := <-errc: return err } }
package hole import ( "bytes" "crypto/tls" "crypto/x509" "github.com/felixge/tcpkeepalive" "io/ioutil" "log" "net" "strings" "sync" "time" ) // Client define a client. type Client struct { sessions map[string]Session locker *sync.RWMutex conn Conn subAddr string alive bool tlsConfig tls.Config useTLS bool } // NewClient create a new client. func NewClient(subAddr string) *Client { var client = new(Client) client.subAddr = subAddr client.sessions = make(map[string]Session) client.locker = new(sync.RWMutex) client.useTLS = false return client } // ConfigTLS config the client. func (client *Client) ConfigTLS(certFile, privFile string) { client.useTLS = true cert2B, _ := ioutil.ReadFile(certFile) priv2B, _ := ioutil.ReadFile(privFile) priv2, _ := x509.ParsePKCS1PrivateKey(priv2B) cert := tls.Certificate{ Certificate: [][]byte{cert2B}, PrivateKey: priv2, } client.tlsConfig = tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} } // Connect connent to hole server. func (client *Client) Connect(addr string) (err error) { log.Printf("Connect Hole server: %s\n", addr) parts := strings.SplitN(addr, "://", 2) var conn net.Conn if client.useTLS { conn, err = tls.Dial(parts[0], parts[1], &client.tlsConfig) } else { conn, err = net.Dial(parts[0], parts[1]) } if err != nil { log.Printf("Is the hole server started?\n") return } if k, err := tcpkeepalive.EnableKeepAlive(conn); err == nil { k.SetKeepAliveIdle(30 * time.Second) k.SetKeepAliveCount(4) k.SetKeepAliveInterval(5 * time.Second) } client.alive = true client.conn = NewClientConn(conn) if err = client.conn.Send([]byte("Connected")); err != nil { client.alive = false client.conn.Close() return } return } // Process the client. func (client *Client) Process() { log.Printf("Process: %s\n", client.subAddr) defer client.conn.Close() var err error var payload []byte var sessionID, data []byte var session Session var ok bool for client.alive { if payload, err = client.conn.Receive(); err != nil { break } sessionID, data = DecodePacket(payload) client.locker.Lock() session, ok = client.sessions[string(sessionID)] client.locker.Unlock() if !ok { session = client.NewSession(sessionID) go client.handleSession(session) } if bytes.Equal(data, []byte("EOF")) { session.r.FeedEOF() } else { session.r.FeedData(data) } } for _, session := range client.sessions { session.r.FeedEOF() } client.alive = false } // NewSession create a session. func (client *Client) NewSession(sessionID []byte) Session { log.Printf("New Session: %x\n", sessionID) var session = NewSession(sessionID, client.conn) client.locker.Lock() client.sessions[string(sessionID)] = session client.locker.Unlock() return session } func (client *Client) handleSession(session Session) { parts := strings.SplitN(client.subAddr, "://", 2) var conn, err = net.Dial(parts[0], parts[1]) if err != nil { client.locker.Lock() delete(client.sessions, string(session.ID)) log.Printf("Session: %x leave.\n", session.ID) client.locker.Unlock() return } go PipeThenClose(conn, session.w) PipeThenClose(session.r, conn) client.locker.Lock() delete(client.sessions, string(session.ID)) log.Printf("Session: %x leave.\n", session.ID) client.locker.Unlock() }
package linked_list //反转链表 双指针迭代 func reverseList(head *ListNode) *ListNode { //存储前一个节点 head的前节点是nil var pre *ListNode = nil //记录当前节点 cur := head //当前节点不为空 for cur != nil { //temp保存当前节点的后继节点 temp := cur.Next //反转 当前节点的下一个节点是它的前一个节点 cur.Next = pre //temp的前一个节点变为当前节点 pre = cur //当前节点替换为下一个节点 也就是temp cur = temp } return pre } //递归版本 func reverseList1(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } p := reverseList1(head.Next) head.Next.Next = head head.Next = nil return p }
package main import ( "encoding/json" "errors" "log" "net/http" "github.com/gin-gonic/gin" "gopkg.in/olahol/melody.v1" ) var clients = map[string]struct{}{} var chatHistory []Message var chatChannel = make(chan Message) var m *melody.Melody func RegisterUser(name string) error { _, ok := clients[name] if ok { return errors.New("choose different Name") } clients[name] = struct{}{} return nil } func PollingServe(context *gin.Context) { log.Println("Got polling request") var json Request if err := context.ShouldBindJSON(&json); err != nil { context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if json.Type == MSG_REGISTER { err := RegisterUser(*json.Name) if err != nil { text := err.Error() reply := Reply{Ok: false, Error: &text} context.JSON(http.StatusBadRequest, reply) } reply := Reply{Ok: true, Messages: []Message{{Name: "", Text: "You are registered"}}} context.JSON(http.StatusOK, reply) return } else if json.Type == MSG_SEND { _, ok := clients[*json.Name] if !ok { text := "you must be registered before sending message" reply := Reply{Ok: false, Error: &text} context.JSON(http.StatusBadRequest, reply) } str := PrepareSendMessage(*json.Name, *json.Text) chatHistory = append(chatHistory, Message{Name: *json.Name, Text: *json.Text}) m.Broadcast(str) go func() { chatChannel <- Message{Name: *json.Name, Text: *json.Text} }() reply := Reply{Ok: true, Messages: []Message{}} context.JSON(http.StatusOK, reply) return } else if json.Type == MSG_GET { reply := Reply{Ok: true, Messages: chatHistory} context.JSON(http.StatusOK, reply) chatHistory = nil } } func LongPollingServe(context *gin.Context) { log.Println("Got long polling request") var json Request if err := context.ShouldBindJSON(&json); err != nil { context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if json.Type == MSG_REGISTER { err := RegisterUser(*json.Name) if err != nil { text := err.Error() reply := Reply{Ok: false, Error: &text} context.JSON(http.StatusBadRequest, reply) } reply := Reply{Ok: true, Messages: []Message{{Name: "", Text: "You are registered"}}} context.JSON(http.StatusOK, reply) return } else if json.Type == MSG_SEND { _, ok := clients[*json.Name] if !ok { text := "you must be registered before sending message" reply := Reply{Ok: false, Error: &text} context.JSON(http.StatusBadRequest, reply) } str := PrepareSendMessage(*json.Name, *json.Text) chatHistory = append(chatHistory, Message{Name: *json.Name, Text: *json.Text}) m.Broadcast(str) go func() { chatChannel <- Message{Name: *json.Name, Text: *json.Text} }() reply := Reply{Ok: true, Messages: []Message{}} context.JSON(http.StatusOK, reply) return } else if json.Type == MSG_GET { select { case msg := <- chatChannel: reply := Reply{Ok: true, Messages: []Message{msg}} context.JSON(http.StatusOK, reply) } } } func PrepareSendError(errorText string) []byte { reply := Reply{ Ok: false, Error: &errorText, } marshaled, err := json.Marshal(reply) if err != nil { log.Println("marshal:", err) } return marshaled } func PrepareSendMessage(name string, text string) []byte { reply := Reply{ Ok: true, Error: nil, Messages: []Message{{name, text}}, } marshaled, err := json.Marshal(reply) if err != nil { log.Println("marshal:", err) } return marshaled } func ServeWebsocket(s *melody.Session, data []byte) { log.Println("Got websocket request") var msg Request err := json.Unmarshal(data, &msg) if err != nil { log.Println("failed to unmarshal msg", err) return } if msg.Type == MSG_REGISTER { log.Println("Register websocket request") err := RegisterUser(*msg.Name) if err != nil { s.Write(PrepareSendError(err.Error())) return } s.Write(PrepareSendMessage("", "You are registered")) } else if msg.Type == MSG_SEND { log.Println("Send websocket request") _, ok := clients[*msg.Name] if !ok { s.Write(PrepareSendError("You must register before sending messages")) return } str := PrepareSendMessage(*msg.Name, *msg.Text) chatHistory = append(chatHistory, Message{Name: *msg.Name, Text: *msg.Text}) m.Broadcast(str) go func() { chatChannel <- Message{Name: *msg.Name, Text: *msg.Text} }() } } func runServer() { r := gin.Default() m = melody.New() r.Any("/", PollingServe) r.Any("/longPolling", LongPollingServe) r.GET("/ws", func(c *gin.Context) { m.HandleRequest(c.Writer, c.Request) }) m.HandleMessage(ServeWebsocket) r.Run(*addr) }
package innerSortImpl /** * @author liujun * @version 1.0 * @date 2021-06-22 00:09 * @author—Email liujunfirst@outlook.com * @blogURL https://blog.csdn.net/ljfirst * @description 快速排序——单向快排 */ type QuickSortSimplex struct { } func (s *QuickSortSimplex) SortMethod(array []int) []int { if array == nil || len(array) <= 1 { return array } quickSortSimplex(array, 0, len(array)-1) return array } func quickSortSimplex(array []int, left, right int) { midPosition := left flagPosition := left if left < right { //自左向右进行对比 for i := left + 1; i <= right; i++ { if array[i] < array[flagPosition] { midPosition++ array[midPosition], array[i] = array[i], array[midPosition] } } //交换标杆元素 if midPosition != flagPosition { array[midPosition], array[flagPosition] = array[flagPosition], array[midPosition] } quickSortSimplex(array, left, midPosition-1) quickSortSimplex(array, midPosition+1, right) } }
package rawdatalog import ( "encoding/json" "github.com/nats-io/stan.go" ) type stanLogRepo struct { sc stan.Conn } func NewStanLogRepo(sc stan.Conn) Repo { return &stanLogRepo{ sc: sc, } } // topic == subject == stream func (r *stanLogRepo) Write(topic string, moment RawMoment) error { msg, _ := json.Marshal(moment) err := r.sc.Publish(topic, msg) if err != nil { return err } return nil }
// This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication // license. Its contents can be found at: // http://creativecommons.org/publicdomain/zero/1.0 package vlc //#include <stdlib.h> //#include <vlc/vlc.h> import "C" import ( "bytes" "encoding/binary" "unsafe" ) // Generic event type. Use a switch on Event.Type to determine which method // to call for its data. The method names are the same as the event type. // It's a bit of an odd way to handle this, but since event data comes in the // form of a C union, there is some binary magic that has to be performed based // on the event type. type Event struct { Type EventType b bytes.Buffer } func (this *Event) MediaMetaChanged() MetaProperty { return MetaProperty(this.readU32()) } func (this *Event) MediaSubItemAdded() *Media { return this.readMedia() } func (this *Event) MediaDurationChanged() int64 { return this.readI64() } func (this *Event) MediaParsedChanged() int { return int(this.readI32()) } func (this *Event) MediaFreed() *Media { return this.readMedia() } func (this *Event) MediaStateChanged() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerTimeChanged() int64 { return this.readI64() } func (this *Event) MediaPlayerPositionChanged() float32 { return this.readF32() } func (this *Event) MediaPlayerSeekableChanged() bool { return this.readB() } func (this *Event) MediaPlayerTitleChanged() bool { return this.readB() } func (this *Event) MediaPlayerLengthChanged() bool { return this.readB() } func (this *Event) MediaPlayerSnapshotTaken() string { return this.readS() } func (this *Event) MediaListItemAdded() *Media { return this.readMedia() } func (this *Event) MediaListWillAddItem() *Media { return this.readMedia() } func (this *Event) MediaListItemDeleted() *Media { return this.readMedia() } func (this *Event) MediaListWillDeleteItem() *Media { return this.readMedia() } func (this *Event) MediaListPlayerNextItemSet() *Media { return this.readMedia() } func (this *Event) VlmMediaAdded() (string, string) { return this.readS2() } func (this *Event) VlmMediaRemoved() (string, string) { return this.readS2() } func (this *Event) VlmMediaChanged() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStarted() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStopped() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusInitAdded() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusOpening() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusPlaying() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusPause() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusEnd() (string, string) { return this.readS2() } func (this *Event) VlmMediaInstanceStatusError() (string, string) { return this.readS2() } func (this *Event) MediaPlayerMediaChanged() *Media { return this.readMedia() } func (this *Event) MediaPlayerNothingSpecial() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerOpening() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerBuffering() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerPlaying() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerPaused() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerStopped() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerForward() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerBackward() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerEndReached() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaPlayerEncounteredError() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaListPlayerPlayed() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaListPlayerStopped() MediaState { return MediaState(this.readU32()) } func (this *Event) MediaListViewItemAdded() *Media { return this.readMedia() } func (this *Event) MediaListViewWillAddItem() *Media { return this.readMedia() } func (this *Event) MediaListViewItemDeleted() *Media { return this.readMedia() } func (this *Event) MediaListViewWillDeleteItem() *Media { return this.readMedia() } func (this *Event) MediaDiscovererStarted() *Discoverer { return this.readDiscoverer() } func (this *Event) MediaDiscovererEnded() *Discoverer { return this.readDiscoverer() } func (this *Event) readI8() int8 { var i int8 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readI16() int16 { var i int16 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readI32() int32 { var i int32 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readI64() int64 { var i int64 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readU8() uint8 { var i uint8 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readU16() uint16 { var i uint16 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readU32() uint32 { var i uint32 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readU64() uint64 { var i uint64 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readF32() float32 { var i float32 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readF64() float64 { var i float64 binary.Read(&this.b, binary.LittleEndian, &i) return i } func (this *Event) readS() string { var i uint64 binary.Read(&this.b, binary.LittleEndian, &i) up := unsafe.Pointer(uintptr(i)) s := C.GoString((*C.char)(up)) C.free(up) return s } func (this *Event) readS2() (string, string) { var a, b uint64 binary.Read(&this.b, binary.LittleEndian, &a) binary.Read(&this.b, binary.LittleEndian, &b) pa := unsafe.Pointer(uintptr(a)) pb := unsafe.Pointer(uintptr(b)) sa := C.GoString((*C.char)(pa)) sb := C.GoString((*C.char)(pb)) C.free(pa) C.free(pb) return sa, sb } func (this *Event) readB() bool { var i int64 binary.Read(&this.b, binary.LittleEndian, &i) return i == 0 } func (this *Event) readMedia() *Media { var i uint64 binary.Read(&this.b, binary.LittleEndian, &i) return &Media{(*C.libvlc_media_t)(unsafe.Pointer(uintptr(i)))} } func (this *Event) readDiscoverer() *Discoverer { var i uint64 binary.Read(&this.b, binary.LittleEndian, &i) return &Discoverer{(*C.libvlc_media_discoverer_t)(unsafe.Pointer(uintptr(i)))} }
// Code generated from FaultParser.g4 by ANTLR 4.8. DO NOT EDIT. package parser // FaultParser import "github.com/antlr/antlr4/runtime/Go/antlr" type BaseFaultParserVisitor struct { *antlr.BaseParseTreeVisitor } func (v *BaseFaultParserVisitor) VisitSpec(ctx *SpecContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitSpecClause(ctx *SpecClauseContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitImportDecl(ctx *ImportDeclContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitImportSpec(ctx *ImportSpecContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitImportPath(ctx *ImportPathContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitDeclaration(ctx *DeclarationContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitConstDecl(ctx *ConstDeclContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitConstSpec(ctx *ConstSpecContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitIdentList(ctx *IdentListContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitExpressionList(ctx *ExpressionListContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitStructDecl(ctx *StructDeclContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitFlow(ctx *FlowContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitStock(ctx *StockContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitPropInt(ctx *PropIntContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitPropString(ctx *PropStringContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitPropFunc(ctx *PropFuncContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitPropVar(ctx *PropVarContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitInstance(ctx *InstanceContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitInitDecl(ctx *InitDeclContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitBlock(ctx *BlockContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitStatementList(ctx *StatementListContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitStatement(ctx *StatementContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitSimpleStmt(ctx *SimpleStmtContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitIncDecStmt(ctx *IncDecStmtContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitAccessHistory(ctx *AccessHistoryContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitAssertion(ctx *AssertionContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitMiscAssign(ctx *MiscAssignContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitFaultAssign(ctx *FaultAssignContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitEmptyStmt(ctx *EmptyStmtContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitIfStmt(ctx *IfStmtContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitForStmt(ctx *ForStmtContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitExpr(ctx *ExprContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitLrExpr(ctx *LrExprContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitPrefix(ctx *PrefixContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitOperand(ctx *OperandContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitOperandName(ctx *OperandNameContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitNumeric(ctx *NumericContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitInteger(ctx *IntegerContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitNegative(ctx *NegativeContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitFloat_(ctx *Float_Context) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitString_(ctx *String_Context) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitBool_(ctx *Bool_Context) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitFunctionLit(ctx *FunctionLitContext) interface{} { return v.VisitChildren(ctx) } func (v *BaseFaultParserVisitor) VisitEos(ctx *EosContext) interface{} { return v.VisitChildren(ctx) }
package wphd import ( "reflect" "testing" ) func TestGetPluginData(t *testing.T) { var tests = []struct { in string expected *Plugin }{ {`<?php /** * Plugin Name * * @package PluginPackage * @author Your Name * @copyright 2016 Your Name or Company Name * @license GPL-2.0+ * * @wordpress-plugin * Plugin Name: Plugin Name * Plugin URI: https://example.com/plugin-name * Description: Description of the plugin. * Version: 1.0.0 * Author: Your Name * Author URI: https://example.com * Text Domain: plugin-name * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt */`, &Plugin{ Name: "Plugin Name", PluginURI: "https://example.com/plugin-name", Description: "Description of the plugin.", Version: "1.0.0", Author: "Your Name", AuthorURI: "https://example.com", TextDomain: "plugin-name", License: "GPL-2.0+", LicenseURI: "http://www.gnu.org/licenses/gpl-2.0.txt", }, }, {`<?php /* * Plugin Name: Jetpack by WordPress.com * Plugin URI: http://jetpack.com * Description: Bring the power of the WordPress.com cloud to your self-hosted WordPress. Jetpack enables you to connect your blog to a WordPress.com account to use the powerful features normally only available to WordPress.com users. * Author: Automattic * Version: 4.4-alpha * Author URI: http://jetpack.com * License: GPL2+ * Text Domain: jetpack * Domain Path: /languages/ */ define( 'JETPACK__MINIMUM_WP_VERSION', '4.5' );`, &Plugin{ Name: "Jetpack by WordPress.com", PluginURI: "http://jetpack.com", Description: "Bring the power of the WordPress.com cloud to your self-hosted WordPress. Jetpack enables you to connect your blog to a WordPress.com account to use the powerful features normally only available to WordPress.com users.", Author: "Automattic", Version: "4.4-alpha", AuthorURI: "http://jetpack.com", License: "GPL2+", TextDomain: "jetpack", DomainPath: "/languages/", }, }, } for _, test := range tests { actual := GetPluginData([]byte(test.in)) if !reflect.DeepEqual(actual, test.expected) { t.Errorf("Got %+v, want %+v", actual, test.expected) } } } func TestGetThemeData(t *testing.T) { var tests = []struct { in string expected *Theme }{ {`/* Theme Name: Twenty Thirteen Theme URI: http://wordpress.org/themes/twentythirteen Author: the WordPress team Author URI: http://wordpress.org/ Description: The 2013 theme for WordPress takes us back to the blog, featuring a full range of post formats, each displayed beautifully in their own unique way. Design details abound, starting with a vibrant color scheme and matching header images, beautiful typography and icons, and a flexible layout that looks great on any device, big or small. Version: 1.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: black, brown, orange, tan, white, yellow, light, one-column, two-columns, right-sidebar, flexible-width, custom-header, custom-menu, editor-style, featured-images, microformats, post-formats, rtl-language-support, sticky-post, translation-ready Text Domain: twentythirteen This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */`, &Theme{ Name: "Twenty Thirteen", ThemeURI: "http://wordpress.org/themes/twentythirteen", Author: "the WordPress team", AuthorURI: "http://wordpress.org/", Description: "The 2013 theme for WordPress takes us back to the blog, featuring a full range of post formats, each displayed beautifully in their own unique way. Design details abound, starting with a vibrant color scheme and matching header images, beautiful typography and icons, and a flexible layout that looks great on any device, big or small.", Version: "1.0", License: "GNU General Public License v2 or later", LicenseURI: "http://www.gnu.org/licenses/gpl-2.0.html", Tags: []string{"black", "brown", "orange", "tan", "white", "yellow", "light", "one-column", "two-columns", "right-sidebar", "flexible-width", "custom-header", "custom-menu", "editor-style", "featured-images", "microformats", "post-formats", "rtl-language-support", "sticky-post", "translation-ready"}, TextDomain: "twentythirteen", }, }, } for _, test := range tests { actual := GetThemeData([]byte(test.in)) if !reflect.DeepEqual(actual, test.expected) { t.Errorf("Got %+v, want %+v", actual, test.expected) } } }
package util // LowerBound restricts value to given lower bound func LowerBound(value, bound int) int { if value < bound { return bound } return value } // UpperBound restricts value to given upper bound func UpperBound(value, bound int) int { if value > bound { return bound } return value }
package posting import ( "testing" "github.com/dgraph-io/dgraph/schema" "github.com/dgraph-io/dgraph/types" "github.com/stretchr/testify/require" ) func TestIndexingInt(t *testing.T) { schema.ParseBytes([]byte("scalar age:int @index")) a, err := IndexTokens("age", types.Val{types.StringID, []byte("10")}) require.NoError(t, err) require.EqualValues(t, []byte{0x1, 0x0, 0x0, 0x0, 0xa}, []byte(a[0])) } func TestIndexingIntNegative(t *testing.T) { schema.ParseBytes([]byte("scalar age:int @index")) a, err := IndexTokens("age", types.Val{types.StringID, []byte("-10")}) require.NoError(t, err) require.EqualValues(t, []byte{0x0, 0xff, 0xff, 0xff, 0xf6}, []byte(a[0])) } func TestIndexingFloat(t *testing.T) { schema.ParseBytes([]byte("scalar age:float @index")) a, err := IndexTokens("age", types.Val{types.StringID, []byte("10.43")}) require.NoError(t, err) require.EqualValues(t, []byte{0x1, 0x0, 0x0, 0x0, 0xa}, []byte(a[0])) } func TestIndexingDate(t *testing.T) { schema.ParseBytes([]byte("scalar age:date @index")) a, err := IndexTokens("age", types.Val{types.StringID, []byte("0010-01-01")}) require.NoError(t, err) require.EqualValues(t, []byte{0x1, 0x0, 0x0, 0x0, 0xa}, []byte(a[0])) } func TestIndexingTime(t *testing.T) { schema.ParseBytes([]byte("scalar age:datetime @index")) a, err := IndexTokens("age", types.Val{types.StringID, []byte("0010-01-01T01:01:01.000000001")}) require.NoError(t, err) require.EqualValues(t, []byte{0x1, 0x0, 0x0, 0x0, 0xa}, []byte(a[0])) } func TestIndexing(t *testing.T) { schema.ParseBytes([]byte("scalar name:string @index")) a, err := IndexTokens("name", types.Val{types.StringID, []byte("abc")}) require.NoError(t, err) require.EqualValues(t, "abc", string(a[0])) } func getTokensTable(t *testing.T) *TokensTable { tt := NewTokensTable() tt.Add("ccc") tt.Add("aaa") tt.Add("bbb") tt.Add("aaa") require.EqualValues(t, 3, tt.Size()) return tt } func TestTokensTableIterate(t *testing.T) { tt := getTokensTable(t) require.EqualValues(t, "aaa", tt.GetFirst()) require.EqualValues(t, "bbb", tt.GetNext("aaa")) require.EqualValues(t, "ccc", tt.GetNext("bbb")) require.EqualValues(t, "", tt.GetNext("ccc")) } func TestTokensTableIterateReverse(t *testing.T) { tt := getTokensTable(t) require.EqualValues(t, "ccc", tt.GetLast()) require.EqualValues(t, "bbb", tt.GetPrev("ccc")) require.EqualValues(t, "aaa", tt.GetPrev("bbb")) require.EqualValues(t, "", tt.GetPrev("aaa")) } func TestTokensTableGetGeq(t *testing.T) { tt := getTokensTable(t) require.EqualValues(t, 1, tt.Get("bbb")) require.EqualValues(t, -1, tt.Get("zzz")) require.EqualValues(t, "aaa", tt.GetNextOrEqual("a")) require.EqualValues(t, "aaa", tt.GetNextOrEqual("aaa")) require.EqualValues(t, "bbb", tt.GetNextOrEqual("aab")) require.EqualValues(t, "ccc", tt.GetNextOrEqual("cc")) require.EqualValues(t, "ccc", tt.GetNextOrEqual("ccc")) require.EqualValues(t, "", tt.GetNextOrEqual("cccc")) require.EqualValues(t, "", tt.GetPrevOrEqual("a")) require.EqualValues(t, "aaa", tt.GetPrevOrEqual("aaa")) require.EqualValues(t, "aaa", tt.GetPrevOrEqual("aab")) require.EqualValues(t, "bbb", tt.GetPrevOrEqual("cc")) require.EqualValues(t, "ccc", tt.GetPrevOrEqual("ccc")) require.EqualValues(t, "ccc", tt.GetPrevOrEqual("cccc")) }
package kuber import ( "strings" "github.com/reconquest/karma-go" "k8s.io/apimachinery/pkg/runtime/schema" appsv1 "k8s.io/api/apps/v1" batchv1 "k8s.io/api/batch/v1" batchv1beta1 "k8s.io/api/batch/v1beta1" corev1 "k8s.io/api/core/v1" ) type GroupVersionResourceKind struct { schema.GroupVersionResource Kind string } func (gvrk GroupVersionResourceKind) String() string { return strings.Join([]string{gvrk.Group, "/", gvrk.Version, ", Resource=", gvrk.Resource, ", Kind=", gvrk.Kind}, "") } var ( Nodes = GroupVersionResourceKind{ GroupVersionResource: corev1.SchemeGroupVersion.WithResource("nodes"), Kind: "Node", } Namespaces = GroupVersionResourceKind{ GroupVersionResource: corev1.SchemeGroupVersion.WithResource("namespaces"), Kind: "Namespace", } LimitRanges = GroupVersionResourceKind{ GroupVersionResource: corev1.SchemeGroupVersion.WithResource("limitranges"), Kind: "LimitRange", } Pods = GroupVersionResourceKind{ GroupVersionResource: corev1.SchemeGroupVersion.WithResource("pods"), Kind: "Pod", } ReplicationControllers = GroupVersionResourceKind{ GroupVersionResource: corev1.SchemeGroupVersion.WithResource("replicationcontrollers"), Kind: "ReplicationController", } Deployments = GroupVersionResourceKind{ GroupVersionResource: appsv1.SchemeGroupVersion.WithResource("deployments"), Kind: "Deployment", } StatefulSets = GroupVersionResourceKind{ GroupVersionResource: appsv1.SchemeGroupVersion.WithResource("statefulsets"), Kind: "StatefulSet", } DaemonSets = GroupVersionResourceKind{ GroupVersionResource: appsv1.SchemeGroupVersion.WithResource("daemonsets"), Kind: "DaemonSet", } ReplicaSets = GroupVersionResourceKind{ GroupVersionResource: appsv1.SchemeGroupVersion.WithResource("replicasets"), Kind: "ReplicaSet", } Jobs = GroupVersionResourceKind{ GroupVersionResource: batchv1.SchemeGroupVersion.WithResource("jobs"), Kind: "Job", } CronJobs = GroupVersionResourceKind{ GroupVersionResource: batchv1beta1.SchemeGroupVersion.WithResource("cronjobs"), Kind: "CronJob", } ) // TODO: Refactor to a map[kind]GVRK func KindToGvrk(kind string) (*GroupVersionResourceKind, error) { switch kind { case Nodes.Kind: return &Nodes, nil case Namespaces.Kind: return &Namespaces, nil case Pods.Kind: return &Pods, nil case ReplicationControllers.Kind: return &ReplicationControllers, nil case Deployments.Kind: return &Deployments, nil case StatefulSets.Kind: return &StatefulSets, nil case DaemonSets.Kind: return &DaemonSets, nil case ReplicaSets.Kind: return &ReplicaSets, nil case Jobs.Kind: return &Jobs, nil case CronJobs.Kind: return &CronJobs, nil default: return nil, karma.Format( nil, "unknown kind: %s", kind, ) } }
// Package main ... package main import ( "io/ioutil" "log" "github.com/go-rod/rod" ) func main() { u := "https://avatars.githubusercontent.com/u/33149672" browser := rod.New().MustConnect() page := browser.MustPage(u).MustWaitLoad() b, err := page.GetResource(u) if err != nil { log.Fatal(err) } if err := ioutil.WriteFile("download.png", b, 0o644); err != nil { log.Fatal(err) } log.Print("wrote download.png") }
package mdb import ( "log" "os" "github.com/dgraph-io/badger" "github.com/pkg/errors" ) type DB struct { *badger.DB } // New creates a new DB wrapper around LMDB func New(folder string, cfg *Config) (*DB, error) { os.MkdirAll(folder, os.ModePerm) opts := badger.DefaultOptions(folder) if cfg.Readonly { log.Println("Setting readonly to true") opts.ReadOnly = true } else { log.Println("Setting readonly to false") } //https://stackoverflow.com/questions/28969455/golang-properly-instantiate-os-filemode db, err := badger.Open(opts) if err != nil { return nil, errors.Wrap(err, "DB.New") } return &DB{db}, nil } // Close the environment func (db *DB) Close() error { err := db.DB.Close() if err != nil { return errors.Wrap(err, "DB.Close") } return nil }
// controllers/books.go package controllers import ( "net/http" models "Angel/Angel_Service_User/Models" "github.com/gin-gonic/gin" ) func Adduser(c *gin.Context) { // Validate input var input models.User if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } adduser := models.User{Name: input.Name, Email: input.Email, Password: input.Password} models.DB.Create(&adduser) c.JSON(http.StatusOK, gin.H{"data": adduser}) } func Listuser(c *gin.Context) { var User []models.User models.DB.Find(&User) c.JSON(http.StatusOK, gin.H{"data": User}) }
package requests import ( "encoding/json" "fmt" "io/ioutil" "net/url" "strings" "time" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" "github.com/atomicjolt/string_utils" ) // CreateContentMigrationUsers Create a content migration. If the migration requires a file to be uploaded // the actual processing of the file will start once the file upload process is completed. // File uploading works as described in the {file:file_uploads.html File Upload Documentation} // except that the values are set on a *pre_attachment* sub-hash. // // For migrations that don't require a file to be uploaded, like course copy, the // processing will begin as soon as the migration is created. // // You can use the {api:ProgressController#show Progress API} to track the // progress of the migration. The migration's progress is linked to with the // _progress_url_ value. // // The two general workflows are: // // If no file upload is needed: // // 1. POST to create // 2. Use the {api:ProgressController#show Progress} specified in _progress_url_ to monitor progress // // For file uploading: // // 1. POST to create with file info in *pre_attachment* // 2. Do {file:file_uploads.html file upload processing} using the data in the *pre_attachment* data // 3. {api:ContentMigrationsController#show GET} the ContentMigration // 4. Use the {api:ProgressController#show Progress} specified in _progress_url_ to monitor progress // // (required if doing .zip file upload) // https://canvas.instructure.com/doc/api/content_migrations.html // // Path Parameters: // # Path.UserID (Required) ID // // Form Parameters: // # Form.MigrationType (Required) The type of the migration. Use the // {api:ContentMigrationsController#available_migrators Migrator} endpoint to // see all available migrators. Default allowed values: // canvas_cartridge_importer, common_cartridge_importer, // course_copy_importer, zip_file_importer, qti_converter, moodle_converter // # Form.PreAttachment.Name (Optional) Required if uploading a file. This is the first step in uploading a file // to the content migration. See the {file:file_uploads.html File Upload // Documentation} for details on the file upload workflow. // # Form.PreAttachment.* (Optional) Other file upload properties, See {file:file_uploads.html File Upload // Documentation} // # Form.Settings.FileUrl (Optional) A URL to download the file from. Must not require authentication. // # Form.Settings.ContentExportID (Optional) The id of a ContentExport to import. This allows you to import content previously exported from Canvas // without needing to download and re-upload it. // # Form.Settings.SourceCourseID (Optional) The course to copy from for a course copy migration. (required if doing // course copy) // # Form.Settings.FolderID (Optional) The folder to unzip the .zip file into for a zip_file_import. // # Form.Settings.OverwriteQuizzes (Optional) Whether to overwrite quizzes with the same identifiers between content // packages. // # Form.Settings.QuestionBankID (Optional) The existing question bank ID to import questions into if not specified in // the content package. // # Form.Settings.QuestionBankName (Optional) The question bank to import questions into if not specified in the content // package, if both bank id and name are set, id will take precedence. // # Form.Settings.InsertIntoModuleID (Optional) The id of a module in the target course. This will add all imported items // (that can be added to a module) to the given module. // # Form.Settings.InsertIntoModuleType (Optional) . Must be one of assignment, discussion_topic, file, page, quizIf provided (and +insert_into_module_id+ is supplied), // only add objects of the specified type to the module. // # Form.Settings.InsertIntoModulePosition (Optional) The (1-based) position to insert the imported items into the course // (if +insert_into_module_id+ is supplied). If this parameter // is omitted, items will be added to the end of the module. // # Form.Settings.MoveToAssignmentGroupID (Optional) The id of an assignment group in the target course. If provided, all // imported assignments will be moved to the given assignment group. // # Form.DateShiftOptions.ShiftDates (Optional) Whether to shift dates in the copied course // # Form.DateShiftOptions.OldStartDate (Optional) The original start date of the source content/course // # Form.DateShiftOptions.OldEndDate (Optional) The original end date of the source content/course // # Form.DateShiftOptions.NewStartDate (Optional) The new start date for the content/course // # Form.DateShiftOptions.NewEndDate (Optional) The new end date for the source content/course // # Form.DateShiftOptions (Optional) Move anything scheduled for day 'X' to the specified day. (0-Sunday, // 1-Monday, 2-Tuesday, 3-Wednesday, 4-Thursday, 5-Friday, 6-Saturday) // # Form.DateShiftOptions.RemoveDates (Optional) Whether to remove dates in the copied course. Cannot be used // in conjunction with *shift_dates*. // # Form.SelectiveImport (Optional) If set, perform a selective import instead of importing all content. // The migration will identify the contents of the package and then stop // in the +waiting_for_select+ workflow state. At this point, use the // {api:ContentMigrationsController#content_list List items endpoint} // to enumerate the contents of the package, identifying the copy // parameters for the desired content. Then call the // {api:ContentMigrationsController#update Update endpoint} and provide these // copy parameters to start the import. // # Form.Select (Optional) . Must be one of folders, files, attachments, quizzes, assignments, announcements, calendar_events, discussion_topics, modules, module_items, pages, rubricsFor +course_copy_importer+ migrations, this parameter allows you to select // the objects to copy without using the +selective_import+ argument and // +waiting_for_select+ state as is required for uploaded imports (though that // workflow is also supported for course copy migrations). // The keys are object types like 'files', 'folders', 'pages', etc. The value // for each key is a list of object ids. An id can be an integer or a string. // Multiple object types can be selected in the same call. // type CreateContentMigrationUsers struct { Path struct { UserID string `json:"user_id" url:"user_id,omitempty"` // (Required) } `json:"path"` Form struct { MigrationType string `json:"migration_type" url:"migration_type,omitempty"` // (Required) PreAttachment struct { Name string `json:"name" url:"name,omitempty"` // (Optional) *string `json:"*" url:"*,omitempty"` // (Optional) } `json:"pre_attachment" url:"pre_attachment,omitempty"` Settings struct { FileUrl string `json:"file_url" url:"file_url,omitempty"` // (Optional) ContentExportID string `json:"content_export_id" url:"content_export_id,omitempty"` // (Optional) SourceCourseID string `json:"source_course_id" url:"source_course_id,omitempty"` // (Optional) FolderID string `json:"folder_id" url:"folder_id,omitempty"` // (Optional) OverwriteQuizzes bool `json:"overwrite_quizzes" url:"overwrite_quizzes,omitempty"` // (Optional) QuestionBankID int64 `json:"question_bank_id" url:"question_bank_id,omitempty"` // (Optional) QuestionBankName string `json:"question_bank_name" url:"question_bank_name,omitempty"` // (Optional) InsertIntoModuleID int64 `json:"insert_into_module_id" url:"insert_into_module_id,omitempty"` // (Optional) InsertIntoModuleType string `json:"insert_into_module_type" url:"insert_into_module_type,omitempty"` // (Optional) . Must be one of assignment, discussion_topic, file, page, quiz InsertIntoModulePosition int64 `json:"insert_into_module_position" url:"insert_into_module_position,omitempty"` // (Optional) MoveToAssignmentGroupID int64 `json:"move_to_assignment_group_id" url:"move_to_assignment_group_id,omitempty"` // (Optional) } `json:"settings" url:"settings,omitempty"` DateShiftOptions struct { ShiftDates bool `json:"shift_dates" url:"shift_dates,omitempty"` // (Optional) OldStartDate time.Time `json:"old_start_date" url:"old_start_date,omitempty"` // (Optional) OldEndDate time.Time `json:"old_end_date" url:"old_end_date,omitempty"` // (Optional) NewStartDate time.Time `json:"new_start_date" url:"new_start_date,omitempty"` // (Optional) NewEndDate time.Time `json:"new_end_date" url:"new_end_date,omitempty"` // (Optional) DaySubstitutions struct { X int64 `json:"x" url:"x,omitempty"` // (Optional) } `json:"day_substitutions" url:"day_substitutions,omitempty"` RemoveDates bool `json:"remove_dates" url:"remove_dates,omitempty"` // (Optional) } `json:"date_shift_options" url:"date_shift_options,omitempty"` SelectiveImport bool `json:"selective_import" url:"selective_import,omitempty"` // (Optional) Select map[string](interface{}) `json:"select" url:"select,omitempty"` // (Optional) . Must be one of folders, files, attachments, quizzes, assignments, announcements, calendar_events, discussion_topics, modules, module_items, pages, rubrics } `json:"form"` } func (t *CreateContentMigrationUsers) GetMethod() string { return "POST" } func (t *CreateContentMigrationUsers) GetURLPath() string { path := "users/{user_id}/content_migrations" path = strings.ReplaceAll(path, "{user_id}", fmt.Sprintf("%v", t.Path.UserID)) return path } func (t *CreateContentMigrationUsers) GetQuery() (string, error) { return "", nil } func (t *CreateContentMigrationUsers) GetBody() (url.Values, error) { return query.Values(t.Form) } func (t *CreateContentMigrationUsers) GetJSON() ([]byte, error) { j, err := json.Marshal(t.Form) if err != nil { return nil, nil } return j, nil } func (t *CreateContentMigrationUsers) HasErrors() error { errs := []string{} if t.Path.UserID == "" { errs = append(errs, "'Path.UserID' is required") } if t.Form.MigrationType == "" { errs = append(errs, "'Form.MigrationType' is required") } if t.Form.Settings.InsertIntoModuleType != "" && !string_utils.Include([]string{"assignment", "discussion_topic", "file", "page", "quiz"}, t.Form.Settings.InsertIntoModuleType) { errs = append(errs, "Settings must be one of assignment, discussion_topic, file, page, quiz") } if len(errs) > 0 { return fmt.Errorf(strings.Join(errs, ", ")) } return nil } func (t *CreateContentMigrationUsers) Do(c *canvasapi.Canvas) (*models.ContentMigration, error) { response, err := c.SendRequest(t) if err != nil { return nil, err } body, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { return nil, err } ret := models.ContentMigration{} err = json.Unmarshal(body, &ret) if err != nil { return nil, err } return &ret, nil }
package main import ( "fmt" "strings" ) func main() { str := "hello world you and me" result := strings.Fields(str) fmt.Printf("type is %T,value is %v\n", result, result) for k, v := range result { fmt.Printf("inidex=%d,value=%v\n", k, v) } }
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "github.com/bloveless/tweetgo" ) type config struct { OAuthConsumerKey string `json:"oauth_consumer_key"` OAuthConsumerSecret string `json:"oauth_consumer_secret"` OAuthAccessToken string `json:"oauth_access_token"` OAuthAccessTokenSecret string `json:"oauth_access_token_secret"` } func loadConfig() (config, error) { wd, _ := os.Getwd() fmt.Printf("Loading config from %s/config.json\n", wd) configBytes, err := ioutil.ReadFile(wd + "/config.json") if err != nil { return config{}, err } c := config{} err = json.Unmarshal(configBytes, &c) if err != nil { return config{}, err } fmt.Printf("Config loaded successfully: %+v\n", c) return c, nil } func saveConfig(c config) error { wd, _ := os.Getwd() bytes, err := json.Marshal(c) if err != nil { return err } fmt.Printf("Saving new config to %s/config.json\n", wd) f, err := os.OpenFile(wd+"/config.json", os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } _, err = f.Write(bytes) if err != nil { return err } fmt.Printf("Successfully wrote new config") return nil } func getTwitterClient(c config) tweetgo.Client { tc := tweetgo.NewClient( c.OAuthConsumerKey, c.OAuthConsumerSecret, ) tc.SetAccessKeys(c.OAuthAccessToken, c.OAuthAccessTokenSecret) return tc }
package greetings import ( "errors" /*nicewise, Go, doesn't know exceptions; errors go with the normal control flow*/ "fmt" "math/rand" "time" ) /* Functions with name with uppercase first letter are public functions, Functions with name with lowercase first letter are packages private methods. In Go terms, a capital letter function is an "exported name". If the functions with names that start with an uppercase letter will be exported to other packages. If the function name starts with a lowercase letter, it won't be exported to other packages, but you can call this function within the same package. */ // Hello returns a greeting for the named person. func Hello(name string) (string, error) { // If no name was given, return an error with a message. if name == "" { return "", errors.New("empty name") /*this is how you create an error*/ } // long variable initialization // var message string // message = fmt.Sprintf("Hi, %v. Welcome!", name)*/ // short variable initialization message := fmt.Sprintf(randomFormat(), name) return message, nil } // Hellos returns a map that associates each of the named people // with a greeting message. func Hellos(names []string) (map[string]string, error) { messages := make(map[string]string) /*make a map of string to string*/ // Loop through the received slice of names, calling // the Hello function to get a message for each name. for _, name := range names { message, err := Hello(name) if err != nil { return nil, err } // In the map, associate the retrieved message with the name. messages[name] = message } return messages, nil } /*Every file can have 0 or more `init()` functions to set up the module. The `init()` functions run after imports and variable declarations are done. see: https://golang.org/doc/effective_go#init */ func init() { rand.Seed(time.Now().UnixNano()) } // randomFormat returns one of a set of greeting messages. The returned // message is selected at random. func randomFormat() string { // A slice of message formats. formats := []string{ "Hi, %v. Welcome!", "Great to see you, %v!", "Hail, %v! Well met!", } // Return a randomly selected message format by specifying // a random index for the slice of formats. return formats[rand.Intn(len(formats))] }
package url import ( "github.com/Dynatrace/dynatrace-operator/src/logger" ) var ( log = logger.Factory.GetLogger("oneagent-url") ) const ( VersionLatest = "latest" )
/* ARMed version 1.0 Author : https://github.com/coderick14 ARMed is a very basic emulator of the ARM instruction set written in Golang USAGE : ARMed [OPTIONS]... SOURCE_FILE Example SOURCE_FILE : ADDI X0, XZR, #3; BL fact; B Exit; fact: SUBI SP, SP, #8; STUR LR, [SP, #4]; STUR X0, [SP, #0]; SUBIS X9, X0, #1; B.GE L1; ADDI X1, XZR, #1; ADDI SP, SP, #8; BR LR; L1: SUBI X0, X0, #1; BL fact; LDUR X0, [SP, #0]; LDUR LR, [SP, #4]; ADDI SP, SP, #8; MUL X1, X0, X1; BR LR; Exit:; --all show all register values after an instruction, with updated ones in color --end show updated registers only once, at the end of the program. Overrides --all --no-log suppress logs of statements being executed --help display help Found a bug? Feel free to raise an issue on https://github.com/coderick14/ARMed Contributions welcome :) */ package main import ( "bufio" "errors" "flag" "fmt" Memory "github.com/coderick14/ARMed/Memory" "io" "os" "strings" ) const helpString = `ARMed version 1.0 Author : https://github.com/coderick14 ARMed is a very basic emulator of the ARM instruction set written in Golang USAGE : ARMed [OPTIONS]... SOURCE_FILE --all show all register values after an instruction, with updated ones in color --end show updated registers only once, at the end of the program. Overrides --all --no-log suppress logs of statements being executed --help display help Found a bug? Feel free to raise an issue on https://github.com/coderick14/ARMed Contributions welcome :)` func main() { var ( err error choice string ) helpPtr := flag.Bool("help", false, "Display help") allPtr := flag.Bool("all", false, "Display all registers after each instruction") endPtr := flag.Bool("end", false, "Display registers only at end") logPtr := flag.Bool("no-log", false, "Suppress log messages") flag.Parse() if *helpPtr == true { fmt.Println(helpString) return } if len(flag.Args()) == 0 { err = errors.New("Error : Missing filename.\n Type ARMed --help for further help") fmt.Println(err) return } fileName := flag.Args()[0] file, err := os.Open(fileName) if err != nil { fmt.Println("Error opening file : ", err) return } defer file.Close() reader := bufio.NewReader(file) for { line, err := reader.ReadString(';') if err == io.EOF { if len(line) > 1 { fmt.Println("Missing semicolon near :", line) return } break } else if err != nil { fmt.Println("Error while reading file : ", err) return } line = strings.TrimSpace(strings.TrimRight(line, ";")) if len(line) != 0 { Memory.InstructionMem.Instructions = append(Memory.InstructionMem.Instructions, line) } } Memory.InitRegisters() Memory.InstructionMem.ExtractLabels() if *endPtr == true { Memory.SaveRegisters() for Memory.IsValidPC(Memory.InstructionMem.PC) { if *logPtr == false { fmt.Println("Executing :", Memory.InstructionMem.Instructions[Memory.InstructionMem.PC]) } err = Memory.InstructionMem.ValidateAndExecuteInstruction() if err != nil { fmt.Println(err) return } } Memory.ShowRegisters(false) } else { for Memory.IsValidPC(Memory.InstructionMem.PC) { Memory.SaveRegisters() if *logPtr == false { fmt.Println("Executing :", Memory.InstructionMem.Instructions[Memory.InstructionMem.PC]) } err = Memory.InstructionMem.ValidateAndExecuteInstruction() if err != nil { fmt.Println(err) return } Memory.ShowRegisters(*allPtr) fmt.Printf("Continue [Y/n]? : ") fmt.Scanln(&choice) if choice == "n" { break; } } } }
package main import ( "flag" "fmt" _ "goray/geometry" "log" "net/http" "strconv" ) func runRayTracer(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World") } /* * Command line arguments allowed are: -port=xxxx * Example: go run goray.go -port=9234 */ func main() { port := flag.Int("port", 9223, "Required port number") out := flag.String("output", "ppm", "Required outpyut must be defined") flag.Parse() switch *out { case "ppm": break case "web": http.HandleFunc("/", runRayTracer) err := http.ListenAndServe(":"+strconv.Itoa(*port), nil) if err != nil { log.Fatal("Could not run web server: ", err) } } }
package common const AMQP_URL = "amqp://guest:guest@localhost:5672/"
/* Copyright 2018 The Chronologist 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 framework provides conveniences for testing. package framework import ( "fmt" "io/ioutil" "path/filepath" "sync" "github.com/kelseyhightower/envconfig" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" "github.com/hypnoglow/chronologist/internal/grafana" "github.com/hypnoglow/chronologist/tests/framework/portforwarder" ) const ( tillerNamespace = "kube-system" tillerPort = 44134 localPort = 44134 ) type Framework struct { mx sync.Mutex config *Config k8sClient *kubernetes.Clientset k8sConfig *rest.Config Helm *helm.Client Grafana *grafana.Client } func (f *Framework) SetupTillerTunnel() error { f.mx.Lock() defer f.mx.Unlock() selector := labels.Set{"app": "helm", "name": "tiller"}.AsSelector() tunnel, err := portforwarder.New(f.k8sClient, f.k8sConfig, tillerNamespace, selector, tillerPort, localPort) if err != nil { return err } f.Helm.Option(helm.Host(fmt.Sprintf("127.0.0.1:%d", tunnel.Local))) return nil } func (f *Framework) HelmReleaseInstaller(chart, namespace, name string) func() (*services.InstallReleaseResponse, error) { // it's weird but otherwise Helm refuses to install the chart. b, err := ioutil.ReadFile(filepath.Join(chart, "values.yaml")) if err != nil { panic(err) } opts := []helm.InstallOption{ helm.ReleaseName(name), helm.ValueOverrides(b), } return func() (*services.InstallReleaseResponse, error) { return f.Helm.InstallRelease(chart, namespace, opts...) } } func New() (*Framework, error) { f := &Framework{config: &Config{}} if err := envconfig.Process("", f.config); err != nil { return nil, err } var err error f.k8sConfig, err = clientcmd.BuildConfigFromFlags("", f.config.KubeConfigPath) if err != nil { return nil, err } f.k8sClient, err = kubernetes.NewForConfig(f.k8sConfig) if err != nil { return nil, err } f.Helm = helm.NewClient(helm.ConnectTimeout(10)) f.Grafana = grafana.NewClient(f.config.GrafanaAddr, f.config.GrafanaAPIKey) return f, nil } type Config struct { KubeConfigPath string `envconfig:"KUBECONFIG" required:"false"` GrafanaAddr string `envconfig:"GRAFANA_ADDR" required:"true"` GrafanaAPIKey string `envconfig:"GRAFANA_API_KEY" required:"true"` }
package rest import ( "crypto/tls" "github.com/jrapoport/gothic/store" "net/http" "net/http/httptest" "net/url" "strings" "testing" "github.com/jrapoport/gothic/models/types/key" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPaginateRequest(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "https://example.com", nil) require.NoError(t, err) req.PostForm = url.Values{ key.Page: []string{"5"}, key.PageSize: []string{"5"}, } page := PaginateRequest(req) assert.Equal(t, 5, page.Index) assert.Equal(t, 5, page.Size) } func TestPaginateResponse(t *testing.T) { tests := []struct { scheme string tls *tls.ConnectionState forward bool expected string }{ {"http", nil, false, "http"}, {"https", nil, false, "https"}, {"http", &tls.ConnectionState{}, false, "https"}, {"http", &tls.ConnectionState{}, true, "foo"}, } for _, test := range tests { req, err := http.NewRequest(http.MethodGet, test.scheme+"://example.com", nil) require.NoError(t, err) req.TLS = test.tls if test.forward { req.Header.Set(ForwardedProto, test.expected) } rec := httptest.NewRecorder() PaginateResponse(rec, req, &store.Pagination{ Index: 5, Size: 10, Prev: 5, Next: 6, Count: 10, Items: [10]int{}, Length: 10, Total: 100, }) const link = "<SCHEME://example.com?page=1&per_page=10>; rel=\"first\"," + "<SCHEME://example.com?page=5&per_page=10>; rel=\"prev\"," + "<SCHEME://example.com?page=6&per_page=10>; rel=\"next\"," + "<SCHEME://example.com?page=10&per_page=10>; rel=\"last\"" expected := strings.ReplaceAll(link, "SCHEME", test.expected) assert.Equal(t, expected, rec.Header().Get(Link)) } }
package models import( "encoding/json" ) /** * Type definition for QosTierEnum enum */ type QosTierEnum int /** * Value collection for QosTierEnum enum */ const ( QosTier_KLOW QosTierEnum = 1 + iota QosTier_KMEDIUM QosTier_KHIGH ) func (r QosTierEnum) MarshalJSON() ([]byte, error) { s := QosTierEnumToValue(r) return json.Marshal(s) } func (r *QosTierEnum) UnmarshalJSON(data []byte) error { var s string json.Unmarshal(data, &s) v := QosTierEnumFromValue(s) *r = v return nil } /** * Converts QosTierEnum to its string representation */ func QosTierEnumToValue(qosTierEnum QosTierEnum) string { switch qosTierEnum { case QosTier_KLOW: return "kLow" case QosTier_KMEDIUM: return "kMedium" case QosTier_KHIGH: return "kHigh" default: return "kLow" } } /** * Converts QosTierEnum Array to its string Array representation */ func QosTierEnumArrayToValue(qosTierEnum []QosTierEnum) []string { convArray := make([]string,len( qosTierEnum)) for i:=0; i<len(qosTierEnum);i++ { convArray[i] = QosTierEnumToValue(qosTierEnum[i]) } return convArray } /** * Converts given value to its enum representation */ func QosTierEnumFromValue(value string) QosTierEnum { switch value { case "kLow": return QosTier_KLOW case "kMedium": return QosTier_KMEDIUM case "kHigh": return QosTier_KHIGH default: return QosTier_KLOW } }
package arithmetic import ( "errors" ) // solve the postfix input. func solve(input []interface{}) (interface{}, error) { st := &stack{} // read the input. For each token... for _, t := range input { // If it is a function, retreive the functions arguments: pop the operand // stack to get the number of arguments. Then, get the last n elements // from the stack (and remove them from it), and injects them to the // function. Finaly, solve the function, and put the output to the operator stack. switch v := t.(type) { case function: size, err := st.popInt() if err != nil { return nil, err } args, err := st.slice(size) if err != nil { return nil, err } o, err := v.solve(args...) if err != nil { return nil, err } st.push(o) // If it is an operator, solve it and push its output to the operand stack. // To solve an operator, inject the stack to the solve method. The solve method // will pop the number of operands required by the operator. case operator: o, err := v.solve(st) if err != nil { return nil, err } st.push(o) // If it is an operand, push it to the operand stack. default: st.push(v) } } // The output is the last operand on the stack. If there are more than one, the input // postfix is non valid. out, _ := st.pop() if _, ok := st.pop(); ok { return nil, errors.New("operator stack should be empty") } return out, nil }
package libdemo func Print() { //fmt.Println("Hello Static Library2") }
package config type ( Config struct { Bot Bot } Bot struct { Token string Prefix string } )
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( "bytes" "context" "fmt" "labgob" "labrpc" "math/rand" "sync" "time" ) func init() { labgob.Register(Entry{}) } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.RWMutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] machineCh chan int // channel for notify state machine to apply new command applyCh chan ApplyMsg state int // raft state FOLLOWER,CANDIDATE,LEADER heartBeat chan int // heartbeat chan used by FOLLOWER ctx context.Context close context.CancelFunc currentTerm int // latest term server has seen (initialized to 0 on first boot, increases monotonically) votedFor int // candidateId that received vote in current term (or null if none) leaderId int // leaderId in latest valid requestAppendEntries lastLogIndex int // last log index (initialized to 0, increases monotonically) committedIndex int // index of highest log entry known to be committed (initialized to 0, increases monotonically) lastApplied int // index of highest log entry applied to state machine (initialized to 0, increases monotonically) lastIncludedIndex int // the last included index is the index of the last entry in the log that the snapshot replaces (initialized to 0, increases monotonically) lastIncludedTerm int // the last included term is the term of the last entry in the log that the snapshot replaces log []Entry // log entries; each entry contains command for state machine, and term when entry was received by leader (first index is 1) nextIndex []int // for each server, index of the next log entry to send to that server (initialized to leader last log index + 1) matchIndex []int // for each server, index of highest log entry known to be replicated on server (initialized to 0, increases monotonically) // lastIncludedIndex <= lastApplied <= committedIndex <= lastLogIndex } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.heartBeat = make(chan int, 10) rf.machineCh = make(chan int, 200) rf.applyCh = applyCh ctx, cancel := context.WithCancel(context.Background()) rf.close = cancel rf.ctx = ctx // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) rf.state = FOLLOWER rf.leaderId = -1 rf.machineCh <- StateMachineNewCommitted go rf.stateMachine() go rf.doFollower() return rf } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft) Start(command interface{}) (int, int, bool) { // Your code here (2B). rf.mu.Lock() defer rf.mu.Unlock() if rf.state != LEADER { return 0, 0, false } else { rf.lastLogIndex++ entry := Entry{ Term: rf.currentTerm, Index: rf.lastLogIndex, Command: command, } rf.log = append(rf.log, entry) rf.nextIndex[rf.me] = rf.lastLogIndex + 1 rf.matchIndex[rf.me] = rf.lastLogIndex go rf.sendLogToAll() //DPrintf("---------------------leader %d (term %d) start command %+v and committedIndex = %d matchIndex= %v nextIndex = %v log = %v\n", rf.me, rf.currentTerm, command, rf.committedIndex, rf.matchIndex, rf.nextIndex, rf.log) DPrintf("---------------------leader %d (term %d) start command %+v and committedIndex = %d matchIndex= %v nextIndex = %v\n", rf.me, rf.currentTerm, entry, rf.committedIndex, rf.matchIndex, rf.nextIndex) return rf.lastLogIndex, rf.currentTerm, true } } // // the tester calls Kill() when a Raft 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 (rf *Raft) Kill() { // Your code here, if desired. rf.mu.Lock() rf.state = STOPED rf.mu.Unlock() rf.close() } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool) { rf.mu.Lock() defer rf.mu.Unlock() return rf.currentTerm, rf.state == LEADER } /*func (rf *Raft) InstallSnapshotFinishedAndReplay() { defer func() { rf.notifyStateMachine(StateMachineInstallSnapshotEnd) }() rf.mu.Lock() defer rf.mu.Unlock() rf.lastApplied = rf.lastIncludedIndex }*/ func (rf *Raft) Replay() { defer func() { rf.notifyStateMachine(StateMachineNewCommitted) }() rf.mu.Lock() defer rf.mu.Unlock() rf.lastApplied = rf.lastIncludedIndex } func (rf *Raft) CommittedState() (int, []int, []int) { rf.mu.Lock() defer rf.mu.Unlock() return rf.committedIndex, rf.matchIndex, rf.nextIndex } func (rf *Raft) SaveSnapshot(newLastIncludedIndex int, snapshot []byte) { rf.mu.Lock() defer rf.mu.Unlock() if newLastIncludedIndex > rf.lastIncludedIndex { index := newLastIncludedIndex - rf.lastIncludedIndex rf.lastIncludedIndex = newLastIncludedIndex rf.lastIncludedTerm = rf.log[index-1].Term rf.lastApplied = newLastIncludedIndex rf.log = append(make([]Entry, 0, DefaultRaftLogCap), rf.log[index:]...) raftState := rf.persister.ReadRaftState() rf.persister.SaveStateAndSnapshot(raftState, snapshot) //DPrintf("server %d SaveStateAndSnapshot newLastIncludedIndex = %d rf.lastIncludedIndex = %d log= %v\n", rf.me, newLastIncludedIndex, rf.lastIncludedIndex, rf.log) //log.Printf("server %d SaveStateAndSnapshot newLastIncludedIndex = %d rf.lastIncludedIndex = %d log= %v\n", rf.me, newLastIncludedIndex, old, rf.log) } } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here (2C). // Example: w := new(bytes.Buffer) e := labgob.NewEncoder(w) e.Encode(rf.currentTerm) e.Encode(rf.votedFor) e.Encode(rf.lastLogIndex) e.Encode(rf.committedIndex) e.Encode(rf.lastApplied) e.Encode(rf.lastIncludedIndex) e.Encode(rf.lastIncludedTerm) e.Encode(rf.log) data := w.Bytes() rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? rf.votedFor = -1 return } // Your code here (2C). // Example: r := bytes.NewBuffer(data) d := labgob.NewDecoder(r) d.Decode(&rf.currentTerm) d.Decode(&rf.votedFor) d.Decode(&rf.lastLogIndex) d.Decode(&rf.committedIndex) d.Decode(&rf.lastApplied) d.Decode(&rf.lastIncludedIndex) d.Decode(&rf.lastIncludedTerm) d.Decode(&rf.log) DPrintf("server %d init params currentTerm = %d votedFor = %d committedIndex= %d lastApplied = %d log= %v", rf.me, rf.currentTerm, rf.votedFor, rf.committedIndex, rf.lastApplied, rf.log) } // need lock during call this func func (rf *Raft) vote(server int) bool { if rf.votedFor == -1 { rf.votedFor = server rf.persist() return true } else if rf.votedFor == server { return true } else { return false } } // need lock during call this func func (rf *Raft) replyLogIsNewerOrEqual(lastLogTerm, lastLogIndex int) bool { myLastLogIndex := rf.lastLogIndex myLastLogTerm := rf.getLogEntryTerm(rf.lastLogIndex) return myLastLogTerm < lastLogTerm || myLastLogTerm == lastLogTerm && myLastLogIndex <= lastLogIndex } func (rf *Raft) getLogEntryTerm(logIndex int) int { if logIndex == rf.lastIncludedIndex { return rf.lastIncludedTerm } else if logIndex > rf.lastIncludedIndex { return rf.log[logIndex-rf.lastIncludedIndex-1].Term } else { panic(fmt.Errorf("server %d query log entry index before lastIncludedIndex", rf.me)) } } func (rf *Raft) getLogEntries(logIndexStart int) []Entry { if logIndexStart > rf.lastIncludedIndex { /*sendEntries := rf.log[logIndexStart-rf.lastIncludedIndex-1:] entries := make([]Entry, len(sendEntries)) copy(entries, sendEntries) return entries*/ return rf.log[logIndexStart-rf.lastIncludedIndex-1:] } else { panic(fmt.Errorf("server %d query log entries index before lastIncludedIndex", rf.me)) } } func (rf *Raft) deleteLogEntries(logIndexReserved int) { if logIndexReserved >= rf.committedIndex { if logIndexReserved > rf.lastIncludedIndex { rf.log = append(make([]Entry, 0, DefaultRaftLogCap), rf.log[:logIndexReserved-rf.lastIncludedIndex]...) } else { rf.log = make([]Entry, 0, DefaultRaftLogCap) } rf.lastLogIndex = rf.lastIncludedIndex + len(rf.log) } else { panic(fmt.Errorf("server %d delete log entries index before committedIndex", rf.me)) } } // need lock during call this func func (rf *Raft) updateCurrentTerm(term int) { if rf.currentTerm < term { rf.votedFor = -1 rf.leaderId = -1 rf.currentTerm = term rf.persist() } } // used by leader func (rf *Raft) updateCommitted() { index := rf.committedIndex for { c := 0 index++ for i := 0; i < len(rf.peers); i++ { if rf.matchIndex[i] >= index { c++ } } if c >= len(rf.peers)/2+1 { if rf.getLogEntryTerm(index) == rf.currentTerm { rf.committedIndex = index rf.persist() rf.notifyStateMachine(StateMachineNewCommitted) //DPrintf("LEADER %d (term %d) committedIndex = %d matchIndex= %v log = %v\n", rf.me, rf.currentTerm, rf.committedIndex, rf.matchIndex, rf.log) DPrintf("LEADER %d (term %d) updateCommitted committedIndex = %d matchIndex= %v\n", rf.me, rf.currentTerm, rf.committedIndex, rf.matchIndex) } else { continue } } else { break } } } func (rf *Raft) sendLog(server int) { rf.mu.RLock() if rf.state != LEADER { rf.mu.RUnlock() return } var prevLogIndex = rf.nextIndex[server] - 1 if prevLogIndex < rf.lastIncludedIndex { go rf.sendSnapshot(server) rf.mu.RUnlock() return } args := RequestAppendEntriesArgs{ Term: rf.currentTerm, LeaderId: rf.me, PrevLogIndex: prevLogIndex, PrevLogTerm: rf.getLogEntryTerm(prevLogIndex), Entries: rf.getLogEntries(rf.nextIndex[server]), LeaderCommitted: rf.committedIndex, } rf.mu.RUnlock() reply := RequestAppendEntriesReply{} if ok := rf.sendRequestAppendEntries(server, &args, &reply); ok { rf.mu.Lock() defer rf.mu.Unlock() if rf.state != LEADER { return } if reply.Term > rf.currentTerm { rf.state = FOLLOWER rf.updateCurrentTerm(reply.Term) } else { if reply.Success { if rf.nextIndex[server] < args.PrevLogIndex+len(args.Entries)+1 { rf.nextIndex[server] = args.PrevLogIndex + len(args.Entries) + 1 } if rf.matchIndex[server] < rf.nextIndex[server]-1 { rf.matchIndex[server] = rf.nextIndex[server] - 1 } rf.updateCommitted() } else { rf.nextIndex[server] = Max(1, Min(rf.matchIndex[server], reply.ConflictIndex, rf.committedIndex)) } } } } func (rf *Raft) sendSnapshot(server int) { rf.mu.RLock() if rf.state != LEADER { rf.mu.RUnlock() return } args := RequestInstallSnapshotArgs{ Term: rf.currentTerm, LeaderId: rf.me, LastIncludedIndex: rf.lastIncludedIndex, LastIncludedTerm: rf.lastIncludedTerm, Data: rf.persister.ReadSnapshot(), } rf.mu.RUnlock() reply := RequestInstallSnapshotReply{} if ok := rf.sendRequestInstallSnapshot(server, &args, &reply); ok { rf.mu.Lock() defer rf.mu.Unlock() if rf.state != LEADER { return } if reply.Term > rf.currentTerm { rf.state = FOLLOWER rf.updateCurrentTerm(reply.Term) } else if reply.Term == rf.currentTerm { if rf.nextIndex[server] < args.LastIncludedIndex+1 { rf.nextIndex[server] = args.LastIncludedIndex + 1 rf.matchIndex[server] = args.LastIncludedIndex } //DPrintf("LEADER %d send server %d after send snapshot committedIndex = %d matchIndex= %v log = %v\n", rf.me, server, rf.committedIndex, rf.matchIndex, rf.log) } } } func (rf *Raft) sendLogToAll() { for i := 0; i < len(rf.peers); i++ { if rf.me == i { continue } go rf.sendLog(i) } } func (rf *Raft) doElection() bool { rf.mu.Lock() if rf.state != CANDIDATE { DPrintf("CANDIDATE %d election failed now state is %s\n", rf.me, stateMap[rf.state]) rf.mu.Unlock() return false } rf.currentTerm++ rf.votedFor = rf.me rf.persist() var voteTerm = rf.currentTerm args := &RequestVoteArgs{ Term: rf.currentTerm, CandidateId: rf.me, LastLogIndex: rf.lastLogIndex, LastLogTerm: rf.getLogEntryTerm(rf.lastLogIndex), } rf.mu.Unlock() replyCh := make(chan *RequestVoteReply, len(rf.peers)) ctx, cancel := context.WithTimeout(context.Background(), ELECTIONTIMEOUT) defer cancel() for i := 0; i < len(rf.peers); i++ { if i == rf.me { // mock vote self reply go func() { replyCh <- &RequestVoteReply{ Term: voteTerm, VoteGranted: true, } }() } else { go rf.sendRequestVote(ctx, i, args, replyCh) } } voteCount := 0 replyCount := 0 for voteCount < len(rf.peers)/2+1 && replyCount < len(rf.peers) { // check if state switch in waiting vote rf.mu.RLock() if rf.state != CANDIDATE { DPrintf("CANDIDATE %d election failed now state is %s\n", rf.me, stateMap[rf.state]) rf.mu.RUnlock() return false } else { rf.mu.RUnlock() } select { case <-ctx.Done(): DPrintf("CANDIDATE %d election failed timeout\n", rf.me) /*if replyCount < len(rf.peers)+1 { time.Sleep(ELECTIONTIMEOUT) }*/ return false case reply := <-replyCh: replyCount++ if reply.VoteGranted == true && reply.Term == voteTerm { voteCount++ } else if reply.VoteGranted == false { rf.mu.Lock() rf.updateCurrentTerm(reply.Term) if rf.replyLogIsNewerOrEqual(args.LastLogTerm, args.LastLogIndex) { rf.state = FOLLOWER rf.mu.Unlock() return false } else { rf.mu.Unlock() } } } if voteCount >= len(rf.peers)/2+1 { rf.mu.Lock() if rf.state == CANDIDATE && rf.currentTerm == voteTerm { rf.initLeader() DPrintf("CANDIDATE %d win election in term %d \n", rf.me, rf.currentTerm) rf.mu.Unlock() return true } else { rf.mu.Unlock() DPrintf("CANDIDATE %d win election in term %d but currentTerm or state is changed\n", rf.me, voteTerm) return false } } } DPrintf("CANDIDATE %d election failed in term %d not have enough votes(received %d)\n", rf.me, voteTerm, voteCount) return false } func (rf *Raft) initLeader() { rf.state = LEADER rf.matchIndex = make([]int, len(rf.peers)) rf.nextIndex = make([]int, len(rf.peers)) for i := 0; i < len(rf.peers); i++ { rf.nextIndex[i] = len(rf.log) + 1 } rf.matchIndex[rf.me] = len(rf.log) } func (rf *Raft) doFollower() { t := time.NewTimer(HEARTBEATTIMEOUT) for { t.Reset(HEARTBEATTIMEOUT) select { case <-rf.ctx.Done(): DPrintf("FOLLOWER %d closed\n", rf.me) return case <-rf.heartBeat: case <-t.C: DPrintf("FOLLOWER %d heartbeat signal timeout\n", rf.me) rf.mu.Lock() rf.state = CANDIDATE rf.mu.Unlock() go rf.doCandidate() return } } } func (rf *Raft) doCandidate() { t := time.NewTimer(time.Duration(rand.Int63n(100)) * HEARTBEATTIMEOUT / 100) for { rand.Seed(time.Now().UnixNano()) t.Reset(time.Duration(rand.Int63n(100)) * HEARTBEATTIMEOUT / 100) select { case <-rf.ctx.Done(): DPrintf("CANDIDATE %d closed\n", rf.me) return case <-t.C: rf.mu.RLock() if rf.state == FOLLOWER { rf.mu.RUnlock() go rf.doFollower() return } else { rf.mu.RUnlock() } if succ := rf.doElection(); succ { go rf.doLeader() return } } } } func (rf *Raft) doLeader() { t := time.NewTicker(HEARTBEAT) rf.sendLogToAll() for { select { case <-rf.ctx.Done(): DPrintf("LEADER %d closed\n", rf.me) return case <-t.C: rf.sendLogToAll() } rf.mu.RLock() if rf.state == FOLLOWER { rf.mu.RUnlock() go rf.doFollower() return } else { rf.mu.RUnlock() } } } func (rf *Raft) notifyStateMachine(msg int) { go func() { rf.machineCh <- msg }() } func (rf *Raft) stateMachine() { for { select { case <-rf.ctx.Done(): DPrintf("server %d stateMachine closed \n", rf.me) return case msg := <-rf.machineCh: if msg == StateMachineInstallSnapshot { rf.applyCh <- ApplyMsg{ CommandValid: false, CommandIndex: 0, Command: CommandInstallSnapshot, } } else { rf.mu.RLock() var baseIndex = rf.lastApplied var executeCommands []Entry if rf.lastApplied < rf.committedIndex { executeCommands = rf.log[rf.lastApplied-rf.lastIncludedIndex : rf.committedIndex-rf.lastIncludedIndex] } rf.mu.RUnlock() for i, c := range executeCommands { rf.applyCh <- ApplyMsg{ CommandValid: true, CommandIndex: baseIndex + i + 1, Command: c.Command, } } if len(executeCommands) > 0 { DPrintf("server %d stateMachine success execute commands %+v\n", rf.me, executeCommands) rf.mu.Lock() if rf.lastApplied < baseIndex+len(executeCommands) { rf.lastApplied = baseIndex + len(executeCommands) } rf.mu.Unlock() } } } } }
package book var pageImageID uint //PageImage is used to store an image on a page type PageImage struct { ID uint `json:"id"` Image string `json:"image"` Width int `json:"width"` Height int `json:"height"` } //GetID gets the ID of the current instance func (p *PageImage) GetID() uint { if p.ID <= 0 { pageImageID++ p.ID = pageImageID return pageImageID } return p.ID } //NewPageImage creates a new page func NewPageImage(height int, width int, imagePath string) *PageImage { return &PageImage{ Height: height, Image: imagePath, Width: width, } }
package piscine func ConcatParams(args []string) string { a := 0 for i := range args { a = i + 1 } result := make([]string, a) for j := 0; j < (a - 1); j++ { result[1] = result[1] + args[j] + "\n" } result[1] = result[1] + args[(a-1)] return result[1] }
package serializer import ( "bytes" "encoding/binary" "encoding/json" "fmt" "sort" ) // Serializable is something which knows how to serialize/deserialize itself from/into bytes // while also performing syntactical checks on the written/read data. type Serializable interface { json.Marshaler json.Unmarshaler // Deserialize deserializes the given data (by copying) into the object and returns the amount of bytes consumed from data. // If the passed data is not big enough for deserialization, an error must be returned. // During deserialization additional validation may be performed if the given modes are set. Deserialize(data []byte, deSeriMode DeSerializationMode, deSeriCtx interface{}) (int, error) // Serialize returns a serialized byte representation. // During serialization additional validation may be performed if the given modes are set. Serialize(deSeriMode DeSerializationMode, deSeriCtx interface{}) ([]byte, error) } // SerializableWithSize implements Serializable interface and has the extra functionality of returning the size of the // resulting serialized object (ideally without actually serializing it). type SerializableWithSize interface { Serializable // Size returns the size of the serialized object Size() int } // Serializables is a slice of Serializable. type Serializables []Serializable // SerializableSlice is a slice of a type which can convert itself to Serializables. type SerializableSlice interface { // ToSerializables returns the representation of the slice as a Serializables. ToSerializables() Serializables // FromSerializables updates the slice itself with the given Serializables. FromSerializables(seris Serializables) } // SerializableReadGuardFunc is a function that given a type prefix, returns an empty instance of the given underlying type. // If the type doesn't resolve or is not supported in the deserialization context, an error is returned. type SerializableReadGuardFunc func(ty uint32) (Serializable, error) // SerializablePostReadGuardFunc is a function which inspects the read Serializable add runs additional validation against it. type SerializablePostReadGuardFunc func(seri Serializable) error // SerializableWriteGuardFunc is a function that given a Serializable, tells whether the given type is allowed to be serialized. type SerializableWriteGuardFunc func(seri Serializable) error // SerializableGuard defines the guards to de/serialize Serializable. type SerializableGuard struct { // The read guard applied before reading an entire object. ReadGuard SerializableReadGuardFunc // The read guard applied after an object has been read. PostReadGuard SerializablePostReadGuardFunc // The write guard applied when writing objects. WriteGuard SerializableWriteGuardFunc } // DeSerializationMode defines the mode of de/serialization. type DeSerializationMode byte const ( // DeSeriModeNoValidation instructs de/serialization to perform no validation. DeSeriModeNoValidation DeSerializationMode = 0 // DeSeriModePerformValidation instructs de/serialization to perform validation. DeSeriModePerformValidation DeSerializationMode = 1 << 0 // DeSeriModePerformLexicalOrdering instructs de/deserialization to automatically perform ordering of // certain arrays by their lexical serialized form. DeSeriModePerformLexicalOrdering DeSerializationMode = 1 << 1 ) // HasMode checks whether the de/serialization mode includes the given mode. func (sm DeSerializationMode) HasMode(mode DeSerializationMode) bool { return sm&mode > 0 } // ArrayValidationMode defines the mode of array validation. type ArrayValidationMode byte const ( // ArrayValidationModeNone instructs the array validation to perform no validation. ArrayValidationModeNone ArrayValidationMode = 0 // ArrayValidationModeNoDuplicates instructs the array validation to check for duplicates. ArrayValidationModeNoDuplicates ArrayValidationMode = 1 << 0 // ArrayValidationModeLexicalOrdering instructs the array validation to check for lexical order. ArrayValidationModeLexicalOrdering ArrayValidationMode = 1 << 1 // ArrayValidationModeAtMostOneOfEachTypeByte instructs the array validation to allow a given type prefix byte to occur only once in the array. ArrayValidationModeAtMostOneOfEachTypeByte ArrayValidationMode = 1 << 2 // ArrayValidationModeAtMostOneOfEachTypeUint32 instructs the array validation to allow a given type prefix uint32 to occur only once in the array. ArrayValidationModeAtMostOneOfEachTypeUint32 ArrayValidationMode = 1 << 3 ) // HasMode checks whether the array element validation mode includes the given mode. func (av ArrayValidationMode) HasMode(mode ArrayValidationMode) bool { return av&mode > 0 } // TypePrefixes defines a set of type prefixes. type TypePrefixes map[uint32]struct{} // Subset checks whether every type prefix is a member of other. func (typePrefixes TypePrefixes) Subset(other TypePrefixes) bool { for typePrefix := range typePrefixes { if _, has := other[typePrefix]; !has { return false } } return true } // ArrayRules defines rules around a to be deserialized array. // Min and Max at 0 define an unbounded array. type ArrayRules struct { // The min array bound. Min uint // The max array bound. Max uint // A map of types which must occur within the array. MustOccur TypePrefixes // The guards applied while de/serializing Serializables. Guards SerializableGuard // The mode of validation. ValidationMode ArrayValidationMode // The slice reduction function for uniqueness checks. UniquenessSliceFunc ElementUniquenessSliceFunc } // CheckBounds checks whether the given count violates the array bounds. func (ar *ArrayRules) CheckBounds(count uint) error { if ar.Min != 0 && count < ar.Min { return fmt.Errorf("%w: min is %d but count is %d", ErrArrayValidationMinElementsNotReached, ar.Min, count) } if ar.Max != 0 && count > ar.Max { return fmt.Errorf("%w: max is %d but count is %d", ErrArrayValidationMaxElementsExceeded, ar.Max, count) } return nil } // ElementUniquenessSliceFunc is a function which takes a byte slice and reduces it to // the part which is deemed relevant for uniqueness checks. // If this function is used in conjunction with ArrayValidationModeLexicalOrdering, then the reduction // must only reduce the slice from index 0 onwards, as otherwise lexical ordering on the set elements // can not be enforced. type ElementUniquenessSliceFunc func(next []byte) []byte // ElementValidationFunc is a function which runs during array validation (e.g. lexical ordering). type ElementValidationFunc func(index int, next []byte) error // ElementUniqueValidator returns an ElementValidationFunc which returns an error if the given element is not unique. func (ar *ArrayRules) ElementUniqueValidator() ElementValidationFunc { set := map[string]int{} return func(index int, next []byte) error { if ar.UniquenessSliceFunc != nil { next = ar.UniquenessSliceFunc(next) } k := string(next) if j, has := set[k]; has { return fmt.Errorf("%w: element %d and %d are duplicates", ErrArrayValidationViolatesUniqueness, j, index) } set[k] = index return nil } } // LexicalOrderValidator returns an ElementValidationFunc which returns an error if the given byte slices // are not ordered lexicographically. func (ar *ArrayRules) LexicalOrderValidator() ElementValidationFunc { var prev []byte var prevIndex int return func(index int, next []byte) error { switch { case prev == nil: prev = next prevIndex = index case bytes.Compare(prev, next) > 0: return fmt.Errorf("%w: element %d should have been before element %d", ErrArrayValidationOrderViolatesLexicalOrder, index, prevIndex) default: prev = next prevIndex = index } return nil } } // LexicalOrderWithoutDupsValidator returns an ElementValidationFunc which returns an error if the given byte slices // are not ordered lexicographically or any elements are duplicated. func (ar *ArrayRules) LexicalOrderWithoutDupsValidator() ElementValidationFunc { var prev []byte var prevIndex int return func(index int, next []byte) error { if prev == nil { prevIndex = index if ar.UniquenessSliceFunc != nil { prev = ar.UniquenessSliceFunc(next) return nil } prev = next return nil } if ar.UniquenessSliceFunc != nil { next = ar.UniquenessSliceFunc(next) } switch bytes.Compare(prev, next) { case 1: return fmt.Errorf("%w: element %d should have been before element %d", ErrArrayValidationOrderViolatesLexicalOrder, index, prevIndex) case 0: // dup return fmt.Errorf("%w: element %d and %d are duplicates", ErrArrayValidationViolatesUniqueness, index, prevIndex) } prevIndex = index if ar.UniquenessSliceFunc != nil { prev = ar.UniquenessSliceFunc(next) return nil } prev = next return nil } } // AtMostOneOfEachTypeValidator returns an ElementValidationFunc which returns an error if a given type occurs multiple // times within the array. func (ar *ArrayRules) AtMostOneOfEachTypeValidator(typeDenotation TypeDenotationType) ElementValidationFunc { seen := map[uint32]int{} return func(index int, next []byte) error { var key uint32 switch typeDenotation { case TypeDenotationUint32: if len(next) < UInt32ByteSize { return fmt.Errorf("%w: not enough bytes to check type uniquness in array", ErrInvalidBytes) } key = binary.LittleEndian.Uint32(next) case TypeDenotationByte: if len(next) < OneByte { return fmt.Errorf("%w: not enough bytes to check type uniquness in array", ErrInvalidBytes) } key = uint32(next[0]) default: panic(fmt.Sprintf("unknown type denotation in AtMostOneOfEachTypeValidator passed: %d", typeDenotation)) } prevIndex, has := seen[key] if has { return fmt.Errorf("%w: element %d and %d have the same type", ErrArrayValidationViolatesTypeUniqueness, index, prevIndex) } seen[key] = index return nil } } // ElementValidationFunc returns a new ElementValidationFunc according to the given mode. func (ar *ArrayRules) ElementValidationFunc() ElementValidationFunc { var arrayElementValidator ElementValidationFunc wrap := func(f ElementValidationFunc, f2 ElementValidationFunc) ElementValidationFunc { return func(index int, next []byte) error { if f != nil { if err := f(index, next); err != nil { return err } } return f2(index, next) } } for i := byte(1); i != 0; i <<= 1 { switch ArrayValidationMode(byte(ar.ValidationMode) & i) { case ArrayValidationModeNone: case ArrayValidationModeNoDuplicates: if ar.ValidationMode.HasMode(ArrayValidationModeLexicalOrdering) { continue } arrayElementValidator = wrap(arrayElementValidator, ar.ElementUniqueValidator()) case ArrayValidationModeLexicalOrdering: // optimization: if lexical order and no dups are enforced, then byte comparison // to the previous element can be done instead of using a map if ar.ValidationMode.HasMode(ArrayValidationModeNoDuplicates) { arrayElementValidator = wrap(arrayElementValidator, ar.LexicalOrderWithoutDupsValidator()) continue } arrayElementValidator = wrap(arrayElementValidator, ar.LexicalOrderValidator()) case ArrayValidationModeAtMostOneOfEachTypeByte: arrayElementValidator = wrap(arrayElementValidator, ar.AtMostOneOfEachTypeValidator(TypeDenotationByte)) case ArrayValidationModeAtMostOneOfEachTypeUint32: arrayElementValidator = wrap(arrayElementValidator, ar.AtMostOneOfEachTypeValidator(TypeDenotationUint32)) } } return arrayElementValidator } // LexicalOrderedByteSlices are byte slices ordered in lexical order. type LexicalOrderedByteSlices [][]byte func (l LexicalOrderedByteSlices) Len() int { return len(l) } func (l LexicalOrderedByteSlices) Less(i, j int) bool { return bytes.Compare(l[i], l[j]) < 0 } func (l LexicalOrderedByteSlices) Swap(i, j int) { l[i], l[j] = l[j], l[i] } // LexicalOrdered32ByteArrays are 32 byte arrays ordered in lexical order. type LexicalOrdered32ByteArrays [][32]byte func (l LexicalOrdered32ByteArrays) Len() int { return len(l) } func (l LexicalOrdered32ByteArrays) Less(i, j int) bool { return bytes.Compare(l[i][:], l[j][:]) < 0 } func (l LexicalOrdered32ByteArrays) Swap(i, j int) { l[i], l[j] = l[j], l[i] } // RemoveDupsAndSortByLexicalOrderArrayOf32Bytes returns a new SliceOfArraysOf32Bytes sorted by lexical order and without duplicates. func RemoveDupsAndSortByLexicalOrderArrayOf32Bytes(slice SliceOfArraysOf32Bytes) SliceOfArraysOf32Bytes { seen := make(map[string]struct{}) orderedArray := make(LexicalOrdered32ByteArrays, len(slice)) uniqueElements := 0 for _, v := range slice { k := string(v[:]) if _, has := seen[k]; has { continue } seen[k] = struct{}{} orderedArray[uniqueElements] = v uniqueElements++ } orderedArray = orderedArray[:uniqueElements] sort.Sort(orderedArray) return orderedArray } // SortedSerializables are Serializables sorted by their serialized form. type SortedSerializables Serializables func (ss SortedSerializables) Len() int { return len(ss) } func (ss SortedSerializables) Less(i, j int) bool { iData, _ := ss[i].Serialize(DeSeriModeNoValidation, nil) jData, _ := ss[j].Serialize(DeSeriModeNoValidation, nil) return bytes.Compare(iData, jData) < 0 } func (ss SortedSerializables) Swap(i, j int) { ss[i], ss[j] = ss[j], ss[i] }
package main import ( "fmt" ) func main() { slice := []int{1, 2, 3} for i := 0; i < len(slice); i++ { fmt.Println(slice[i]) } for i, v := range slice { fmt.Println(i, v) } wellKnownPorts := map[string]int{"http": 80, "https": 443} for k, v := range wellKnownPorts { // Mandatroy to use the variable here fmt.Println(k, v) } }
package main import "fmt" func main() { cache := Constructor(2) fmt.Println(cache.Get(2)) cache.Put(2, 6) fmt.Println(cache.Get(1)) cache.Put(1, 5) cache.Put(1, 2) fmt.Println(cache.Get(1)) fmt.Println(cache.Get(2)) } type LRUCache struct { cacheMap map[int]*node head *node tail *node capacity *int } type node struct { key int value int prev *node after *node } func Constructor(capacity int) LRUCache { lru := LRUCache{ cacheMap: make(map[int]*node, capacity), head: &node{ key: -1, value: -1, prev: nil, }, tail: &node{ key: -1, value: -1, after: nil, }, capacity: &capacity, } lru.head.after = lru.tail lru.tail.prev = lru.head return lru } func (this *LRUCache) Get(key int) int { if node, ok := this.cacheMap[key]; ok { //move node to the start of the linkedlist. node.prev.after = node.after node.after.prev = node.prev this.head.after.prev = node node.after = this.head.after node.prev = this.head this.head.after = node return node.value } return -1 } func (this *LRUCache) Put(key int, value int) { // 判断要插入的key在缓存中是不是已经存在了,如果存在了就不删除缓存中LRU的元素,进行更新操作. if _, ok := this.cacheMap[key]; !ok && len(this.cacheMap) >= *this.capacity { // remove the last node of the linkedlist and remove it from the cacheMap. delete(this.cacheMap, this.tail.prev.key) this.tail.prev.prev.after = this.tail this.tail.prev = this.tail.prev.prev } if node, ok := this.cacheMap[key]; ok { // 更新值. node.value = value node.prev.after = node.after node.after.prev = node.prev node.after = this.head.after this.head.after.prev = node node.prev = this.head this.head.after = node return } newNode := &node{ key: key, value: value, } this.head.after.prev = newNode newNode.after = this.head.after newNode.prev = this.head this.head.after = newNode this.cacheMap[key] = newNode } /** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */
package astParser import ( "fmt" "go/ast" "go/parser" "go/token" "log" "os" "path/filepath" "reflect" "regexp" "strings" "github.com/bykof/go-plantuml/domain" ) var earlySeenFunctions map[string]domain.Functions func ParseDirectory(directoryPath string, opts ...ParserOptionFunc) domain.Packages { options := &parserOptions{} for _, opt := range opts { opt(options) } var packages domain.Packages files, err := os.ReadDir(directoryPath) if err != nil { log.Fatal(err) } earlySeenFunctions = make(map[string]domain.Functions) currentPackage := domain.Package{ FilePath: directoryPath, Name: directoryPath, Variables: domain.Fields{}, Constants: domain.Fields{}, Interfaces: domain.Interfaces{}, Classes: domain.Classes{}, Functions: domain.Functions{}, } for _, file := range files { fullPath := filepath.Join(directoryPath, file.Name()) if !file.IsDir() { if isExcluded(file.Name(), options.excludedFilesRegex) { continue } parsedPackage := ParseFile(fullPath) currentPackage = currentPackage.Add(parsedPackage) } else { if options.recursive { packages = append(packages, ParseDirectory(fullPath, opts...)...) } } } if !currentPackage.IsEmpty() { packages = append(packages, currentPackage) } // Handle the case where className could not be found in classes for className, earlyFuncs := range earlySeenFunctions { for _, function := range earlyFuncs { log.Printf("Could not find class: %s for function %s", className, function.Name) } } return packages } func isExcluded(fileName string, regex *regexp.Regexp) bool { if filepath.Ext(fileName) != ".go" { return true } if strings.HasSuffix(fileName, "_test.go") { return true } if regex == nil { return false } if regex.Match([]byte(fileName)) { return true } return false } func ParseFile(filePath string) domain.Package { var domainPackage domain.Package node, err := parser.ParseFile( token.NewFileSet(), filePath, nil, parser.ParseComments, ) if err != nil { log.Fatal(err) } domainPackage = domain.Package{ FilePath: filePath, Name: filePath, Interfaces: domain.Interfaces{}, Classes: domain.Classes{}, Functions: domain.Functions{}, Constants: domain.Fields{}, Variables: domain.Fields{}, } if node.Scope != nil { for name, object := range node.Scope.Objects { // If object is not a type switch object.Kind { case ast.Var: field, err := valueSpecToField(object.Name, object.Decl.(*ast.ValueSpec)) if err != nil { log.Fatal(err) } field.Name = fmt.Sprintf("var %s", field.Name) domainPackage.Variables = append(domainPackage.Variables, *field) case ast.Con: field, err := valueSpecToField(object.Name, object.Decl.(*ast.ValueSpec)) if err != nil { log.Fatal(err) } field.Name = fmt.Sprintf("const %s", field.Name) domainPackage.Constants = append(domainPackage.Constants, *field) case ast.Typ: typeSpec := object.Decl.(*ast.TypeSpec) if typeSpec.TypeParams != nil { var params []string for _, v := range typeSpec.TypeParams.List { for _, v := range v.Names { params = append(params, v.String()) } } if len(params) > 0 { name = name + "[" + strings.Join(params, ",") + "]" } } switch typeSpec.Type.(type) { case *ast.StructType: structType := typeSpec.Type.(*ast.StructType) class := domain.Class{ Name: name, Fields: ParseFields(structType.Fields.List), } addEarlyFunctions(&class) domainPackage.Classes = append(domainPackage.Classes, class) case *ast.InterfaceType: var functions domain.Functions interfaceType := typeSpec.Type.(*ast.InterfaceType) for _, field := range interfaceType.Methods.List { if funcType, ok := field.Type.(*ast.FuncType); ok { parsedFields, err := ParseField(field) if err != nil { log.Fatal(err) } for _, parsedField := range parsedFields { functions = append(functions, funcTypeToFunction(parsedField.Name, funcType)) } } } domainInterface := domain.Interface{ Name: name, Functions: functions, } domainPackage.Interfaces = append(domainPackage.Interfaces, domainInterface) default: class := domain.Class{ Name: name, } addEarlyFunctions(&class) domainPackage.Classes = append(domainPackage.Classes, class) } } } } for _, decl := range node.Decls { if functionDecl, ok := decl.(*ast.FuncDecl); ok { var className string // Function is not bound to a struct if functionDecl.Recv == nil { function := createFunction(functionDecl.Name.Name, functionDecl) domainPackage.Functions = append(domainPackage.Functions, function) continue } for _, receiverClass := range functionDecl.Recv.List { classField, err := exprToField("", receiverClass.Type) if err != nil { log.Fatal(err) } className = classField.Type.ToClassString() classIndex := domainPackage.Classes.ClassIndexByName(className) function := createFunction(functionDecl.Name.Name, functionDecl) // Handle the case where className could not be found in classes if classIndex < 0 { earlySeenFunctions[className] = append(earlySeenFunctions[className], function) } else { domainPackage.Classes[classIndex].Functions = append( domainPackage.Classes[classIndex].Functions, function, ) } } } } return domainPackage } func addEarlyFunctions(class *domain.Class) { if funcs, ok := earlySeenFunctions[class.Name]; ok { class.Functions = append(class.Functions, funcs...) delete(earlySeenFunctions, class.Name) } } func createFunction(name string, functionDecl *ast.FuncDecl) domain.Function { function := domain.Function{ Name: name, } if functionDecl.Type.Params != nil { function.Parameters = ParseFields(functionDecl.Type.Params.List) } if functionDecl.Type.Results != nil { function.ReturnFields = ParseFields(functionDecl.Type.Results.List) } return function } func exprToField(fieldName string, expr ast.Expr) (*domain.Field, error) { switch fieldType := expr.(type) { case *ast.Ident: field := identToField(fieldName, fieldType) return &field, nil case *ast.SelectorExpr: field := selectorExprToField(fieldName, fieldType) return &field, nil case *ast.StarExpr: field := starExprToField(fieldName, fieldType) return &field, nil case *ast.ArrayType: field := arrayTypeToField(fieldName, fieldType) return &field, nil case *ast.Ellipsis: field := ellipsisToField(fieldName, fieldType) return &field, nil case *ast.InterfaceType: field := interfaceTypeToField(fieldName, fieldType) return &field, nil case *ast.MapType: field := mapTypeToField(fieldName, fieldType) return &field, nil case *ast.FuncType: field := funcTypeToField(fieldName, fieldType) return &field, nil case *ast.StructType: field := structTypeToField(fieldName, fieldType) return &field, nil case *ast.ChanType: field := chanTypeToField(fieldName, fieldType) return &field, nil case *ast.IndexExpr: // generic goes here field, err := indexExprToField(fieldName, fieldType) return &field, err default: return nil, fmt.Errorf("unknown Field Type %s", reflect.TypeOf(expr).String()) } } func ParseField(field *ast.Field) (domain.Fields, error) { var fields domain.Fields if field.Names != nil && len(field.Names) > 0 { for _, fieldName := range field.Names { parsedField, err := exprToField(fieldName.Name, field.Type) if err != nil { return fields, err } fields = append(fields, *parsedField) } } else { parsedField, err := exprToField("", field.Type) if err != nil { return fields, err } fields = append(fields, *parsedField) } return fields, nil } func ParseFields(fieldList []*ast.Field) domain.Fields { fields := domain.Fields{} for _, field := range fieldList { parsedFields, err := ParseField(field) if err != nil { log.Fatal(err) } fields = append(fields, parsedFields...) } return fields }
package main import ( "os" "github.com/alecthomas/kingpin" "github.com/aws/aws-sdk-go/aws/session" "github.com/b-b3rn4rd/gocfn/pkg/writer" "github.com/sirupsen/logrus" ) var ( version = "master" debug = kingpin.Flag("debug", "Enable debug logging.").Short('d').Bool() logger = logrus.New() jsonOutWriter = writer.New(os.Stdout, writer.JSONFormatter) strOutWriter = writer.New(os.Stdout, writer.PlainFormatter) exiter = os.Exit ) func main() { kingpin.Version(version) runCommand := kingpin.Parse() if *debug { logrus.SetLevel(logrus.DebugLevel) logger.SetLevel(logrus.DebugLevel) } logger.Formatter = &logrus.JSONFormatter{} sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) switch runCommand { case "deploy": deploy(sess) case "package": packaage(sess) } }
package config import ( "time" "shared/utility/glog" "shared/utility/mysql" "github.com/go-redis/redis/v8" ) type Config struct { Service string ServerName string GRPCListenPort string ETCDEndpoints []string TCPConnKeepAlive time.Duration // tcp连接保持时间 MaxConn int Redis *redis.Options MySQL *mysql.Config CSVPath string Log *glog.Options } func NewDefaultConfig() *Config { return &Config{ Service: "guild", ServerName: "guild01", GRPCListenPort: "9060", ETCDEndpoints: []string{ "localhost:2379", "localhost:2380", "localhost:2381", }, TCPConnKeepAlive: 5 * time.Minute, MaxConn: 10000, Redis: &redis.Options{ Username: "root", Password: "", Addr: ":6379", }, MySQL: &mysql.Config{ Addr: "root:root@tcp(127.0.0.1:3306)/overlord_user_go?charset=utf8mb4&parseTime=true&loc=Local", MaxOpenConn: 5, MaxIdleConn: 5, ConnMaxLifetime: 4 * time.Hour, }, CSVPath: "../shared/csv/data", Log: &glog.Options{ LogLevel: "DEBUG", LogDir: "./log", FileSizeLimit: 4294967296, }, } }
package comparisons import ( "jvm-go/instruction/base" "jvm-go/runtimedata" ) // 比较Long变量 type LCMP struct { base.NoOperandsInstruction } // 将栈顶的两个long变量弹出,进行比较,将比较结果(0、1、-1)推入栈顶 func (self *LCMP) Execute(frame *runtimedata.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else { stack.PushInt(-1) } }
package pipa import ( "sync" "time" ) // InputStream reads messages from the consumer type InputStream struct { consumer Consumer notifier Notifier } // NewInputStream wraps a consumer into a message stream func NewInputStream(consumer Consumer, notifier Notifier) *InputStream { return &InputStream{consumer: consumer, notifier: notifier} } // Parse parses messages of the message streams and converts them into an event stream func (s *InputStream) Parse(bufferSize int, parser Parser) *EventStream { events := make(chan *Event, bufferSize) policy := parser.Policy() go func() { defer close(events) for msg := range s.consumer.Messages() { _ = policy.Perform(func() error { value, err := parser.Parse(msg) if err != nil { s.notifier.ParseError(err) } else { events <- &Event{Value: value, Message: msg} } return err }) } }() return &EventStream{events: events, consumer: s.consumer, notifier: s.notifier} } // -------------------------------------------------------------------- // EventStream streams individual events type EventStream struct { events <-chan *Event consumer Consumer notifier Notifier } // Drain drains the stream, blocking func (s *EventStream) Drain() (n int) { for _ = range s.events { n++ } return } // Batch creates batches of events using window intervals func (s *EventStream) Batch(window time.Duration) *BatchStream { batches := make(chan EventBatch, 1) go func() { defer close(batches) var acc EventBatch for { select { case evt, ok := <-s.events: if !ok { if len(acc) != 0 { batch := make(EventBatch, len(acc)) copy(batch, acc) batches <- batch acc = acc[:0] } return } acc = append(acc, *evt) case <-time.After(window): if len(acc) != 0 { batch := make(EventBatch, len(acc)) copy(batch, acc) batches <- batch acc = acc[:0] } } } }() return &BatchStream{batches: batches, consumer: s.consumer, notifier: s.notifier} } // -------------------------------------------------------------------- // BatchStream streams batches of events type BatchStream struct { batches <-chan EventBatch consumer Consumer notifier Notifier } // Drain drains the stream, blocking func (s *BatchStream) Drain() (n, m int) { for batch := range s.batches { n++ m += len(batch) } return } // Process distributes the steam across handlers, blocking func (s *BatchStream) Process(handlers ...Handler) { stopper := new(sync.WaitGroup) monitor := new(sync.WaitGroup) children := make([]handlerProcess, len(handlers)) for i := 0; i < len(handlers); i++ { stopper.Add(1) children[i] = handlerProcess{ handler: handlers[i], batches: make(chan EventBatch), notifier: s.notifier, } go children[i].loop(stopper, monitor) } for batch := range s.batches { for _, child := range children { monitor.Add(1) child.batches <- batch } monitor.Wait() for _, evt := range batch { s.consumer.MarkOffset(evt.Message, "") } } for _, child := range children { close(child.batches) } stopper.Wait() } // -------------------------------------------------------------------- type handlerProcess struct { handler Handler batches chan EventBatch notifier Notifier } func (s *handlerProcess) loop(stopper, monitor *sync.WaitGroup) { defer stopper.Done() policy := s.handler.Policy() for batch := range s.batches { _ = policy.Perform(func() (err error) { var out int start := time.Now() if out, err = s.handler.Process(batch); err != nil { s.notifier.HandlerError(s.handler.Name(), len(batch), err) } else { s.notifier.HandlerOK(s.handler.Name(), len(batch), out, time.Since(start)) } return }) monitor.Done() } }
package sqlite import ( "database/sql" "github.com/7phs/coding-challenge-search/db/common" "github.com/7phs/coding-challenge-search/model" ) type QueryItemsLoad struct{} func (o QueryItemsLoad) Query() string { return ` SELECT item_name, lat, lng, item_url, img_urls FROM items ` } func (o QueryItemsLoad) Bind() []interface{} { return nil } func (o QueryItemsLoad) Scan(row *sql.Rows, record *model.Item) error { var imgs string err := row.Scan( &common.NullString{V: &record.Name}, &common.NullFloat64{V: &record.Location.Lat}, &common.NullFloat64{V: &record.Location.Long}, &common.NullString{V: &record.Url}, &common.NullString{V: &imgs}, ) record.Imgs = common.JsonArrayString(imgs).Unmarshal() return err }
package apiservice import ( "log" "net/http" "time" "goji.io/middleware" ) func (cl *Client) recoverPanic(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { log.Printf("panic recovery: %+v", err) http.Error(w, http.StatusText(500), 500) } }() next.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func (cl *Client) handleNotFoundErrors(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { if handler := middleware.Handler(r.Context()); handler == nil { w.WriteHeader(http.StatusNotFound) return } next.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func (cl *Client) respondWithJSON(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-type", "application/json") next.ServeHTTP(w, r) } return http.HandlerFunc(fn) } func (cl *Client) logRequest(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { t1 := time.Now() next.ServeHTTP(w, r) t2 := time.Now() log.Printf("%s %q %v\n", r.Method, r.URL.String(), t2.Sub(t1)) } return http.HandlerFunc(fn) }
package turingapi import ( "github.com/gin-gonic/gin" "spoon/util/turingapi" "spoon/handler" ) // 与机器人进行文字聊天 func ChatBot(c *gin.Context) { text := c.PostForm("text") err, result := turingapi.ChatRobotWithText(text, nil) if err != nil { handler.SendResponse(c, err, nil) } else { handler.SendResponse(c, nil, turingapi.GetResponseTxt(result)) } }
package Trapping_Rain_Water import ( "testing" "github.com/stretchr/testify/assert" ) func TestTrap(t *testing.T) { ast := assert.New(t) test1 := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1} ast.Equal(6, trap(test1)) ast.Equal(6, trap2(test1)) ast.Equal(6, trap3(test1)) }
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "fmt" "github.com/urfave/cli" "github.com/bitmark-inc/bitmarkd/fault" ) func runAdd(c *cli.Context) error { m := c.App.Metadata["config"].(*metadata) name, err := checkName(c.GlobalString("identity")) if nil != err { return err } description, err := checkDescription(c.String("description")) if nil != err { return err } // blank or a valid seed seed := c.String("seed") new := c.Bool("new") acc := c.String("account") if m.verbose { fmt.Fprintf(m.e, "identity: %s\n", name) fmt.Fprintf(m.e, "description: %s\n", description) fmt.Fprintf(m.e, "seed: %s\n", seed) fmt.Fprintf(m.e, "account: %s\n", acc) fmt.Fprintf(m.e, "new: %t\n", new) } if "" == acc { seed, err = checkSeed(seed, new, m.testnet) if nil != err { return err } password := c.GlobalString("password") if "" == password { password, err = promptNewPassword() if nil != err { return err } } err = m.config.AddIdentity(name, description, seed, password) if nil != err { return err } } else if "" == seed && "" != acc && !new { err = m.config.AddReceiveOnlyIdentity(name, description, acc) if nil != err { return err } } else { return fault.IncompatibleOptions } // require configuration update m.save = true return nil }
// Copyright (C) 2017 Google 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 template import ( "bytes" "context" "fmt" "io" "path/filepath" "reflect" "regexp" "strings" "text/template" "unicode" "unicode/utf8" "github.com/google/gapid/core/fault" "github.com/google/gapid/gapil/semantic" ) const ( // ErrBadArgumentCount may be returned by a template invocation that has unpaired arguments ErrBadArgumentCount = fault.Const("bad argument count, must be in pairs") // ErrBadInvokeKeys may be returned by a template invocation that has invalid arguments keys ErrBadInvokeKeys = fault.Const("invoke keys must be strings") ) type Functions struct { ctx context.Context // Held because functions are invoked through templates templates *template.Template funcs template.FuncMap globals globalMap mappings *semantic.Mappings active *template.Template writer io.Writer basePath string apiFile string api *semantic.API cs *ConstantSets loader func(filename string) ([]byte, error) } type Options struct { Dir string APIFile string Loader func(filename string) ([]byte, error) Funcs template.FuncMap Globals []string Tracer string } // NewFunctions builds a new template management object that can be used to run templates over an API file. // The apiFile name is used in error messages, and should be the name of the file the api was loaded from. // loader can be used to intercept file system access from within the templates, specifically used when // including other templates. // The functions in funcs are made available to the templates, and can override the functions from this // package if needed. func NewFunctions(ctx context.Context, api *semantic.API, mappings *semantic.Mappings, options Options) (*Functions, error) { basePath, err := filepath.Abs(options.Dir) if err != nil { return nil, fmt.Errorf("Could not get absolute path to directory: '%s'. %v", options.Dir, err) } f := &Functions{ ctx: ctx, templates: template.New("FunctionHolder"), funcs: template.FuncMap{}, globals: globalMap{}, mappings: mappings, basePath: basePath, apiFile: options.APIFile, api: api, loader: options.Loader, } v := reflect.ValueOf(f) t := v.Type() for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) r, _ := utf8.DecodeRuneInString(m.Name) if unicode.IsUpper(r) { c := v.MethodByName(m.Name) f.funcs[m.Name] = c.Interface() } } initNodeTypes(f) initGlobals(f, options.Globals) for k, v := range options.Funcs { if gen, ok := v.(func(*Functions) interface{}); ok { f.funcs[k] = gen(f) } else { f.funcs[k] = v } } if options.Tracer != "" { pattern := regexp.MustCompile(options.Tracer) for n, c := range f.funcs { if pattern.MatchString(n) { f.funcs[n] = trace(n, c) } } } f.templates.Funcs(f.funcs) return f, nil } func trace(name string, f interface{}) func(values ...interface{}) (interface{}, error) { depth := "" return func(values ...interface{}) (interface{}, error) { fmt.Print(depth, name) depth += " | " args := make([]reflect.Value, len(values)) for i, v := range values { if v == nil { args[i] = reflect.ValueOf(&v).Elem() } else { args[i] = reflect.ValueOf(v) } switch v := v.(type) { case string: fmt.Printf(" %q", v) case semantic.Type: fmt.Printf(" [%s]", v.Name()) default: fmt.Printf(" <%T>", v) } } fmt.Println() defer func() { depth = depth[:len(depth)-4] }() result := reflect.ValueOf(f).Call(args) value := result[0].Interface() var err error if len(result) > 1 { err, _ = result[1].Interface().(error) } return value, err } } // IsNil returns true if v is nil. func (f *Functions) IsNil(v interface{}) bool { if v == nil { return true } r := reflect.ValueOf(v) switch r.Kind() { case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map: return r.IsNil() default: return false } } // Error raises an error terminating execution of the template. // {{Error "Foo returned error: %s" $err}} func (f *Functions) Error(s string, args ...interface{}) (string, error) { return "", fmt.Errorf(s, args...) } // Log prints s and optional format arguments to stdout. Example: // {{Log "%s %s" "Hello" "world}} func (f *Functions) Log(s string, args ...interface{}) string { fmt.Printf(s+"\n", args...) return "" } func (*Functions) buildArgs(values ...interface{}) (map[string]interface{}, error) { var base map[string]interface{} i := 0 if len(values) > 0 { var ok bool if base, ok = values[0].(map[string]interface{}); ok { i = 1 } } pairs := (len(values) - i) / 2 if (len(values)-i)%2 != 0 { return nil, ErrBadArgumentCount } data := make(map[string]interface{}, pairs+len(base)) for k, v := range base { data[k] = v } for ; i < len(values)-1; i += 2 { switch k := values[i].(type) { case string: data[k] = values[i+1] default: return nil, ErrBadInvokeKeys } } return data, nil } // Args builds a template argument object from a list of arguments. // If no arguments are passed then the result will be nil. // If a single argument is passed then the result will be the value // of that argument. // If the first argument is a map, it is assumed to be a base argument set to // be augmented. // Remaining arguments must come in name-value pairs. // For example: // {{define "SingleParameterMacro"}} // $ is: {{$}} // {{end}} // // {{define "MultipleParameterMacro"}} // $.ArgA is: {{$.ArgA}}, $.ArgB is: {{$.ArgB}} // {{end}} // // {{template "SingleParameterMacro" (Args)}} // {{/* Returns "$ is: nil" */}} // // {{template "SingleParameterMacro" (Args 42)}} // {{/* Returns "$ is: 42" */}} // // {{template "MultipleParameterMacro" (Args "ArgA" 4 "ArgB" 2)}} // {{/* Returns "$.ArgA is: 4, $.ArgB is: 2" */}} func (f *Functions) Args(arguments ...interface{}) (interface{}, error) { switch len(arguments) { case 0: return nil, nil case 1: return arguments[0], nil default: return f.buildArgs(arguments...) } } // Macro invokes the template macro with the specified name and returns the // template output as a string. See Args for how the arguments are processed. func (f *Functions) Macro(name string, arguments ...interface{}) (string, error) { arg, err := f.Args(arguments...) if err != nil { return "", err } t := f.templates.Lookup(name) if t == nil { return "", fmt.Errorf("Cannot find template %s", name) } buf := &bytes.Buffer{} err = f.execute(t, buf, arg) return buf.String(), err } // Template invokes the template with the specified name writing the output to // the current output writer. See Args for how the arguments are processed. func (f *Functions) Template(name string, arguments ...interface{}) (string, error) { arg, err := f.Args(arguments...) if err != nil { return "", err } t := f.templates.Lookup(name) if t == nil { return "", fmt.Errorf("Cannot find template %s", name) } return "", f.execute(t, nil, arg) } func nodename(node interface{}) string { if node == nil { return "Nil" } nt := reflect.TypeOf(node) if nt.Kind() == reflect.Ptr { nt = nt.Elem() } return nt.Name() } func (f *Functions) node(writer io.Writer, prefix string, node semantic.Node, arguments ...interface{}) error { // Collect the arguments to the template args, err := f.buildArgs(arguments...) if err != nil { return err } args["Node"] = node try := make([]string, 0, 4) ty, err := f.TypeOf(node) if node != nil && err == nil { args["Type"] = ty try = append(try, prefix+"#"+ty.Name(), prefix+"."+nodename(ty), ) } if node != ty { try = append(try, prefix+"."+nodename(node)) } try = append(try, prefix+"_Default") for _, name := range try { if tmpl := f.templates.Lookup(name); tmpl != nil { return f.execute(tmpl, writer, args) } } return fmt.Errorf(`Cannot find templates "%s"`, strings.Join(try, `","`)) } // Node dispatches to the template that matches the node best, writing the // result to the current output writer. // If the node is a Type or Expression then the type semantic.Type name is tried, // then the class of type (the name of the semantic class that represents the type). // The actual name of the node type is then tried, and if none of those matches, // the "Default" template is used if present. // If no possible template could be matched, and error is generated. // eg: {{Node "TypeName" $}} where $ is a boolean and expression would try // "TypeName#Bool" // "TypeName.Builtin" // "TypeName.BinaryOp" // "TypeName_Default" // See Args for how the arguments are processed, in addition the Node arg will // be added in and have the value of node, and if the node had a type // discovered, the Type arg will be added in as well. func (f *Functions) Node(prefix string, node semantic.Node, arguments ...interface{}) (string, error) { return "", f.node(nil, prefix, node, arguments...) } // SNode dispatches to the template that matches the node best, capturing the // result and returning it. // See Node for the dispatch rules used. func (f *Functions) SNode(prefix string, node semantic.Node, arguments ...interface{}) (string, error) { buf := &bytes.Buffer{} err := f.node(buf, prefix, node, arguments...) return buf.String(), err }
package LeetCode func Code23() { l1 := InitSingleList([]int{-9, 5, 7}) l2 := InitSingleList([]int{2, 4, 6}) l3 := InitSingleList([]int{4, 5, 6}) arr := []*ListNode{l1, l2, l3} PrintSingleList(mergeKLists(arr)) } /** 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeKLists(lists []*ListNode) *ListNode { for i := 0; i < len(lists); i++ { if lists[i] == nil { lists = append(lists[:i], lists[i+1:]...) } } if len(lists) == 1 { return lists[0] } head := &ListNode{0, nil} finalList := head.Next var i, j = 0, 0 for { if i < len(lists)-1 { j = i + 1 finalList = mergeTwoLists(lists[i], lists[j]) lists[j] = finalList } else { break } i++ } return finalList }
package storage import ( "errors" "fmt" "github.com/futurehomeno/fimpgo" "github.com/futurehomeno/fimpgo/fimptype/primefimp" log "github.com/sirupsen/logrus" "github.com/thingsplex/tpflow" "github.com/thingsplex/tpflow/registry/model" ) type VinculumRegistryStore struct { vApi *primefimp.ApiClient msgTransport *fimpgo.MqttTransport config *tpflow.Configs } func NewVinculumRegistryStore(config *tpflow.Configs) RegistryStorage { return &VinculumRegistryStore{config: config} } func (r *VinculumRegistryStore) Connect() error { clientId := r.config.MqttClientIdPrefix + "vinc_reg_store" r.msgTransport = fimpgo.NewMqttTransport(r.config.MqttServerURI, clientId, r.config.MqttUsername, r.config.MqttPassword, true, 1, 1) r.msgTransport.SetGlobalTopicPrefix(r.config.MqttTopicGlobalPrefix) err := r.msgTransport.Start() log.Info("<MqRegInt> Mqtt transport connected") if err != nil { log.Error("<MqRegInt> Error connecting to broker : ", err) return err } r.vApi = primefimp.NewApiClient("tpflow_reg", r.msgTransport, false) if r.config.IsDevMode { log.Info("<MqRegInt> DEV-MODE vinculum DB from file") err = r.vApi.LoadVincResponseFromFile("testdata/vinfimp/site-response.json") if err != nil { log.Error("Can't load site data from file . Error:", err) } } else { go func() { r.vApi.ReloadSiteToCache(40) r.vApi.StartNotifyRouter() }() } return nil } func (r *VinculumRegistryStore) GetBackendName() string { return "vinculum" } func (r *VinculumRegistryStore) Disconnect() { r.vApi.Stop() } func (VinculumRegistryStore) GetServiceById(Id model.ID) (*model.Service, error) { //log.Warn("GetServiceById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetServiceByFullAddress(address string) (*model.ServiceExtendedView, error) { //log.Warn("GetServiceByFullAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetLocationById(Id model.ID) (*model.Location, error) { locations, err := r.GetAllLocations() if err != nil { return nil, err } for i := range locations { if locations[i].ID == Id { return &locations[i], nil } } return nil, nil } func (r *VinculumRegistryStore) GetAllThings() ([]model.Thing, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vThings := site.Things var things []model.Thing for i := range vThings { thing := model.Thing{} thing.ID = model.ID(vThings[i].ID) thing.Alias = vThings[i].Name thing.Address = vThings[i].Address thing.LocationId = model.ID(vThings[i].RoomID) thing.ProductHash, _ = vThings[i].Props["product_hash"] thing.ProductId, _ = vThings[i].Props["product_id"] thing.ProductName, _ = vThings[i].Props["product_name"] for di := range vThings[i].Devices { firstDev := site.GetDeviceById(vThings[i].Devices[di]) if firstDev != nil { thing.CommTechnology = firstDev.Fimp.Adapter _, isBattery := firstDev.Service["battery"] if isBattery { thing.PowerSource = "battery" } else { thing.PowerSource = "ac" } if thing.LocationId == 0 { if firstDev.Room == nil { continue } if *firstDev.Room == 0 { continue } thing.LocationId = model.ID(*firstDev.Room) } } } things = append(things, thing) } return things, nil } func (r *VinculumRegistryStore) GetDevicesByThingId(locationId model.ID) ([]model.Device, error) { log.Warn("GetDevicesByThingId NOT implemented !!!!") return nil, nil } func (r *VinculumRegistryStore) ExtendThingsWithLocation(things []model.Thing) []model.ThingWithLocationView { response := make([]model.ThingWithLocationView, len(things)) site, err := r.vApi.GetSite(true) if err != nil { return nil } for i := range things { response[i].Thing = things[i] room := site.GetRoomById(int(things[i].LocationId)) if room != nil { if room.Alias != "" { response[i].LocationAlias = room.Alias } else { if room.Type != nil { response[i].LocationAlias = *room.Type } } continue } area := site.GetAreaById(int(things[i].LocationId)) if area != nil { response[i].LocationAlias = area.Name } } return response } func (r *VinculumRegistryStore) GetAllServices() ([]model.Service, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vDevs := site.Devices var services []model.Service for i := range vDevs { for k := range vDevs[i].Service { svc := model.Service{Name: k} svc.Address = vDevs[i].Service[k].Addr if vDevs[i].Client.Name != nil { svc.Alias = *vDevs[i].Client.Name } for _, intfName := range vDevs[i].Service[k].Interfaces { intf := model.Interface{ Type: "", // can be extracted from inclusion report , but currently not being used anywhere MsgType: intfName, ValueType: "", // can be extracted from inclusion report or use MsgType -> ValueType mapping Version: "", } svc.Interfaces = append(svc.Interfaces, intf) } svc.ParentContainerId = model.ID(vDevs[i].ID) svc.ParentContainerType = model.DeviceContainer if vDevs[i].Room != nil { svc.LocationId = model.ID(*vDevs[i].Room) } services = append(services, svc) } } return services, nil } func (VinculumRegistryStore) GetThingExtendedViewById(Id model.ID) (*model.ThingExtendedView, error) { //log.Warn("GetThingExtendedViewById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetServiceByAddress(serviceName string, serviceAddress string) (*model.Service, error) { //log.Warn("GetServiceByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetExtendedServices(serviceNameFilter string, filterWithoutAlias bool, thingIdFilter model.ID, locationIdFilter model.ID) ([]model.ServiceExtendedView, error) { var svcs []model.ServiceExtendedView return svcs, errors.New("not implemented") } func (r *VinculumRegistryStore) GetAllLocations() ([]model.Location, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } var locations []model.Location for i := range site.Areas { loc := model.Location{} loc.ID = model.ID(site.Areas[i].ID) * (-1) loc.Type = "area" loc.Alias = site.Areas[i].Name loc.SubType = site.Areas[i].Type locations = append(locations, loc) } for i := range site.Rooms { loc := model.Location{} loc.ID = model.ID(site.Rooms[i].ID) loc.Type = "room" loc.Alias = site.Rooms[i].Alias if site.Rooms[i].Type != nil { loc.SubType = *site.Rooms[i].Type } if site.Rooms[i].Area != nil { loc.ParentID = model.ID(*site.Rooms[i].Area) } locations = append(locations, loc) } return locations, nil } func (VinculumRegistryStore) GetThingById(Id model.ID) (*model.Thing, error) { //log.Warn("GetThingById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetThingByAddress(technology string, address string) (*model.Thing, error) { //log.Warn("GetThingByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetThingExtendedViewByAddress(technology string, address string) (*model.ThingExtendedView, error) { //log.Warn("GetThingExtendedViewByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetThingsByLocationId(locationId model.ID) ([]model.Thing, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } var things []model.Thing //err := st.db.Select(q.Eq("LocationId", locationId)).Find(&things) //return things, err for i := range site.Things { if site.Things[i].RoomID == int(locationId) { thing, err := r.GetThingById(model.ID(site.Things[i].RoomID)) if err != nil { things = append(things, *thing) } } } return things, nil } func (VinculumRegistryStore) GetThingByIntegrationId(id string) (*model.Thing, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetAllDevices() ([]model.Device, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vDevices := site.Devices var devices []model.Device for i := range vDevices { device := model.Device{} device.ID = model.ID(vDevices[i].ID) if vDevices[i].Client.Name != nil { device.Alias = *vDevices[i].Client.Name } if vDevices[i].Room != nil { device.LocationId = model.ID(*vDevices[i].Room) } if vDevices[i].ThingID != nil { device.ThingId = model.ID(*vDevices[i].ThingID) } var dtype, dsubtype string if vDevices[i].Type["type"] != nil { dtype, _ = vDevices[i].Type["type"].(string) } if vDevices[i].Type["subtype"] != nil { dsubtype, _ = vDevices[i].Type["subtype"].(string) dsubtype = "." + dsubtype } device.Type = fmt.Sprintf("%s%s", dtype, dsubtype) devices = append(devices, device) } return devices, nil } func (r *VinculumRegistryStore) GetExtendedDevices() ([]model.DeviceExtendedView, error) { devices, err := r.GetAllDevices() if err != nil { return nil, err } var extDevices []model.DeviceExtendedView for i := range devices { location, err := r.GetLocationById(devices[i].LocationId) var locationAlias string if err == nil && location != nil { locationAlias = fmt.Sprintf("%s(%s %s)", location.Alias, location.Type, location.SubType) } dev := model.DeviceExtendedView{ Device: devices[i], Services: nil, LocationAlias: locationAlias, } extDevices = append(extDevices, dev) } return extDevices, nil } func (VinculumRegistryStore) GetDeviceById(Id model.ID) (*model.DeviceExtendedView, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetDevicesByLocationId(locationId model.ID) ([]model.Device, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetDeviceByIntegrationId(id string) (*model.Device, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetLocationByIntegrationId(id string) (*model.Location, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) UpsertThing(thing *model.Thing) (model.ID, error) { log.Warn("UpsertThing NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) UpsertService(service *model.Service) (model.ID, error) { log.Warn("UpsertService NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) UpsertLocation(location *model.Location) (model.ID, error) { log.Warn("UpsertLocation NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) DeleteThing(id model.ID) error { log.Warn("DeleteThing NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) DeleteService(id model.ID) error { log.Warn("DeleteService NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) DeleteLocation(id model.ID) error { log.Warn("DeleteLocation NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) ReindexAll() error { log.Warn("ReindexAll NOT implemented !!!!") return errors.New("not implemented") } func (r *VinculumRegistryStore) Sync() error { return r.vApi.ReloadSiteToCache(3) } func (VinculumRegistryStore) ClearAll() error { log.Warn("ClearAll NOT implemented !!!!") return errors.New("not implemented") } func (r *VinculumRegistryStore) GetConnection() interface{} { log.Warn("GetConnection NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) GetState() string { return "RUNNING" } func (r *VinculumRegistryStore) LoadConfig(config interface{}) error { return nil } func (r *VinculumRegistryStore) Init() error { return nil } func (r *VinculumRegistryStore) Stop() { return }
package version import "github.com/hashicorp/go-version" func Assert(v, constraint string) (bool, error) { cv, err := version.NewVersion(v) if err != nil { return false, err } constraints, err := version.NewConstraint(constraint) if err != nil { return false, err } return constraints.Check(cv), nil }
package usecase import ( "github.com/Okaki030/hinagane-scraping/domain/repository" ) // articleUseCase はスクレイピングプログラムに必要な構造体をまとめた構造体 type articleS3UseCase struct { articleRepository repository.ArticleS3Repository memberCountRepository repository.MemberCountS3Repository wordCountRepository repository.WordCountS3Repository } // NewArticleUseCase はarticleUseCase型のインスタンスを生成するための関数 func NewArticleS3UseCase(ar repository.ArticleS3Repository, mcr repository.MemberCountS3Repository, wcr repository.WordCountS3Repository) ArticleUseCase { return &articleS3UseCase{ articleRepository: ar, memberCountRepository: mcr, wordCountRepository: wcr, } } // まとめ記事を登録 func (au articleS3UseCase) CollectArticle() error { var err error // 現在時刻の取得 now := GetNow() // 記事のスクレイピング articles, err := Scraping(now) if err != nil { return nil } // 記事(csv)をs3から取得 err = au.articleRepository.DownloadArticle() if err != nil { return err } for i, _ := range articles { var err error // タイトルから固有名詞を取得 words, err := ExtractingWords(articles[i].Name) if err != nil { return err } // まとめ記事をdbに登録 exist, err := au.articleRepository.InsertArticle(articles[i], words) if err != nil { return err } if exist == true { continue } } // 記事データをs3に保存 au.articleRepository.UploadArticle() // メンバーカウントcsvを取得 err = au.memberCountRepository.DownloadCSV() if err != nil { return err } // 直近3日間のまとめ記事へのメンバーの出現回数をカウント err = au.memberCountRepository.InsertMemberCountInThreeDays(now) if err != nil { return err } // メンバーカウントcsvをアップロード err = au.memberCountRepository.UploadCSV() if err != nil { return err } // ワードカウントcsvを取得 err = au.wordCountRepository.DownloadCSV() if err != nil { return err } // 直近3日間のまとめ記事への単語の出現回数をカウント err = au.wordCountRepository.InsertWordCountInThreeDays(now) if err != nil { return err } // ワードカウントcsvをアップロード err = au.wordCountRepository.UploadCSV() if err != nil { return err } return nil }
package app // TODO: Decouple this from the application, investigate Traefik's CLI args import ( "github.com/urfave/cli" ) func GetOpts() []cli.Flag { return []cli.Flag{ cli.StringFlag{ Name: "run, r", Usage: "For running a local CI definition", EnvVar: "DEBUG", }, cli.StringFlag{ Name: "redis-host, rh", Value: "localhost", Usage: "Defines a redis host to connect to", EnvVar: "REDIS_URL", }, cli.StringFlag{ Name: "redis-port, rp", Value: "6379", Usage: "Defines a redis port to connect to", EnvVar: "REDIS_PORT", }, cli.StringFlag{ Name: "key, k", Value: "job:v1:*", Usage: "Defines the Redis key to look for, for new jobs", }, } }
package model type Wallet struct { ID uint `gorm: "primaryKey"` Balance float32 `gorm: "not null,default:'0'"` }
package main import ( "io/ioutil" "fmt" "bufio" "strings" "strconv" ) func main() { // Read file fileContent, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Print(err) } input := string(fileContent) fmt.Println("Part 1") fmt.Println(Problem1("0\n3\n0\n1\n-3"), "should be 5") fmt.Println("the problem result is", Problem1(input)) fmt.Println("Part 2") fmt.Println(Problem2("0\n3\n0\n1\n-3"), "should be 10") fmt.Println("the problem result is", Problem2(input)) } func Problem1(input string) int{ // Array with array that will be scanned array := StringToIntArray(input) counter := 0 currentIt := 0 solutionFound := false // Loop until we find a solution for solutionFound == false { counter++ // Calculate next it nextIt := array[currentIt] + currentIt if nextIt > len(array) - 1 || nextIt < 0 { // If the next it is larger than the array scope // then we found the exit solutionFound = true } else { // Otherwise we keep going with the new it and change // the current position array[currentIt] = array[currentIt] + 1 currentIt = nextIt } } return counter } func Problem2(input string) int{ // Array with array that will be scanned array := StringToIntArray(input) counter := 0 currentIt := 0 solutionFound := false // Loop until we find a solution for solutionFound == false { counter++ // Calculate next it nextIt := array[currentIt] + currentIt if nextIt > len(array) - 1 || nextIt < 0 { // If the next it is larger than the array scope // then we found the exit solutionFound = true } else { // Otherwise we keep going with the new it and change // the current position. For Problem2 the change is // a little different if array[currentIt] >= 3 { array[currentIt] = array[currentIt] - 1 } else { array[currentIt] = array[currentIt] + 1 } currentIt = nextIt } } return counter } // Transform \n separated string of numbers into int array func StringToIntArray(str string) []int { array := make([]int, 0) scanner := bufio.NewScanner(strings.NewReader(str)) for scanner.Scan() { value, _ := strconv.Atoi(scanner.Text()) array = append(array, value) } if err := scanner.Err(); err != nil { fmt.Print(err) } return array }
package rod_test import ( "fmt" "time" "github.com/ysmood/kit" "github.com/ysmood/rod" "github.com/ysmood/rod/lib/input" "github.com/ysmood/rod/lib/launcher" "github.com/ysmood/rod/lib/proto" ) // Open wikipedia, search for "idempotent", and print the title of result page func Example_basic() { // launch and connect to a browser browser := rod.New().Connect() // Even you forget to close, rod will close it after main process ends defer browser.Close() // timeout will be passed to chained function calls page := browser.Timeout(time.Minute).Page("https://github.com") // make sure windows size is consistent page.Window(0, 0, 1200, 600) // use css selector to get the search input element and input "git" page.Element("input").Input("git").Press(input.Enter) // wait until css selector get the element then get the text content of it text := page.Element(".codesearch-results p").Text() fmt.Println(text) // Output: Git is the most widely used version control system. } // Such as you logged in your github account and you want to reuse the login session, // you may want to launch Chrome like this example. func Example_reuse_sessions() { url := launcher.NewUserMode().Launch() browser := rod.New().ControlURL(url).Connect() browser.Page("https://github.com") fmt.Println("done") // Skip // Output: done } func Example_debug_mode() { url := launcher.New(). Headless(false). // run chrome on foreground, you can also use env "rod=show" Devtools(true). // open devtools for each new tab Launch() browser := rod.New(). ControlURL(url). DebugCDP(true). // log all cdp traffic Trace(true). // show trace of each input action Slowmotion(time.Second). // each input action will take 1 second Connect(). Timeout(time.Minute) // the monitor server that plays the screenshots of each tab, useful when debugging headlee mode browser.ServeMonitor(":9777") defer browser.Close() page := browser.Page("https://www.wikipedia.org/") page.Element("#searchLanguage").Select("[lang=zh]") page.Element("#searchInput").Input("热干面") page.Keyboard.Press(input.Enter) fmt.Println(page.Element("#firstHeading").Text()) // get the image binary img := page.Element(`[alt="Hot Dry Noodles.jpg"]`) _ = kit.OutputFile("tmp/img.jpg", img.Resource(), nil) // pause the js execution // you can resume by open the devtools and click the resume button on source tab page.Pause() // Skip // Output: 热干面 } func Example_wait_for_animation() { browser := rod.New().Connect().Timeout(time.Minute) defer browser.Close() page := browser.Page("https://getbootstrap.com/docs/4.0/components/modal/") page.WaitLoad().Element("[data-target='#exampleModalLive']").Click() saveBtn := page.ElementMatches("#exampleModalLive button", "Close") // wait until the save button's position is stable // and we don't wait more than 5s, saveBtn will also inherit the 1min timeout from the page saveBtn.Timeout(5 * time.Second).WaitStable().Click().WaitInvisible() fmt.Println("done") // Output: done } func Example_wait_for_request() { browser := rod.New().Connect().Timeout(time.Minute) defer browser.Close() page := browser.Page("https://www.bing.com/") wait := page.WaitRequestIdle() page.Element("#sb_form_q").Click().Input("test") wait() fmt.Println(page.Has("#sw_as li")) // Output: true } func Example_customize_retry_strategy() { browser := rod.New().Connect().Timeout(time.Minute) defer browser.Close() page := browser.Page("https://github.com") backoff := kit.BackoffSleeper(30*time.Millisecond, 3*time.Second, nil) // here we use low-level api ElementE other than Element to have more options, // use backoff algorithm to do the retry el, err := page.ElementE(backoff, "", "input") kit.E(err) fmt.Println(el.Eval(`() => this.name`).String()) // Output: q } func Example_customize_chrome_launch() { // set custom chrome options url := launcher.New(). Set("disable-sync"). // add flag Delete("use-mock-keychain"). // delete flag Launch() browser := rod.New().ControlURL(url).Connect().Timeout(time.Minute) defer browser.Close() el := browser.Page("https://github.com").Element("title") fmt.Println(el.Text()) // Output: The world’s leading software development platform · GitHub } // Useful when rod doesn't have the function you want, you can call the cdp interface directly easily. func Example_direct_cdp() { browser := rod.New().Connect() defer browser.Close() // The code here is how SetCookies works // Normally, you use something like browser.Page("").SetCookies(...).Navigate(url) page := browser.Page("").Timeout(time.Minute) // call cdp interface directly here // set the cookie before we visit the website // Doc: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie res, err := proto.NetworkSetCookie{ Name: "rod", Value: "test", URL: "https://github.com", }.Call(page) kit.E(err) fmt.Println(res.Success) page.Navigate("https://github.com") // eval js on the page to get the cookie cookie := page.Eval(`() => document.cookie`).String() fmt.Println(cookie[:9]) // Or even more low-level way to use raw json to send request to chrome. ctx, client, sessionID := page.CallContext() _, _ = client.Call(ctx, sessionID, "Network.SetCookie", map[string]string{ "name": "rod", "value": "test", "url": "https://github.com", }) // Output: // true // rod=test; }
package main import ( "log" "fmt" ) func (cli *PHBCLI) phbgetBalance(address, nodeID string) { if !PHBValidateAddress(address) { log.Panic("ERROR: Address is not valid") } bc := PHBNewBlockchain(nodeID) UTXOSet := PHBUTXOSet{bc} defer bc.phbdb.Close() balance := 0 pubKeyHash := PHBBase58Decode([]byte(address)) pubKeyHash = pubKeyHash[1 : len(pubKeyHash)-4] UTXOs := UTXOSet.PHBFindUTXO(pubKeyHash) for _, out := range UTXOs { balance += out.PHBValue } fmt.Printf("Balance of '%s': %d\n", address, balance) }
// Copyright (c) 2016-2019 Uber Technologies, 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 s3backend import ( "bytes" "testing" "github.com/uber/kraken/core" "github.com/uber/kraken/lib/backend" "github.com/uber/kraken/mocks/lib/backend/s3backend" "github.com/uber/kraken/utils/mockutil" "github.com/uber/kraken/utils/randutil" "github.com/uber/kraken/utils/rwutil" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) type clientMocks struct { config Config userAuth UserAuthConfig s3 *mocks3backend.MockS3 } func newClientMocks(t *testing.T) (*clientMocks, func()) { ctrl := gomock.NewController(t) var auth AuthConfig auth.S3.AccessKeyID = "accesskey" auth.S3.AccessSecretKey = "secret" return &clientMocks{ config: Config{ Username: "test-user", Region: "test-region", Bucket: "test-bucket", NamePath: "identity", RootDirectory: "/root", }, userAuth: UserAuthConfig{"test-user": auth}, s3: mocks3backend.NewMockS3(ctrl), }, ctrl.Finish } func (m *clientMocks) new() *Client { c, err := NewClient(m.config, m.userAuth, WithS3(m.s3)) if err != nil { panic(err) } return c } func TestClientFactory(t *testing.T) { require := require.New(t) config := Config{ Username: "test-user", Region: "test-region", Bucket: "test-bucket", NamePath: "identity", RootDirectory: "/root", } var auth AuthConfig auth.S3.AccessKeyID = "accesskey" auth.S3.AccessSecretKey = "secret" userAuth := UserAuthConfig{"test-user": auth} f := factory{} _, err := f.Create(config, userAuth) require.NoError(err) } func TestClientStat(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() var length int64 = 100 mocks.s3.EXPECT().HeadObject(&s3.HeadObjectInput{ Bucket: aws.String("test-bucket"), Key: aws.String("/root/test"), }).Return(&s3.HeadObjectOutput{ContentLength: &length}, nil) info, err := client.Stat(core.NamespaceFixture(), "test") require.NoError(err) require.Equal(core.NewBlobInfo(100), info) } func TestClientDownload(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() data := randutil.Text(32) mocks.s3.EXPECT().Download( mockutil.MatchWriterAt(data), &s3.GetObjectInput{ Bucket: aws.String("test-bucket"), Key: aws.String("/root/test"), }, ).Return(int64(len(data)), nil) var b bytes.Buffer require.NoError(client.Download(core.NamespaceFixture(), "test", &b)) require.Equal(data, b.Bytes()) } func TestClientDownloadWithBuffer(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() data := randutil.Text(32) mocks.s3.EXPECT().Download( mockutil.MatchWriterAt(data), &s3.GetObjectInput{ Bucket: aws.String("test-bucket"), Key: aws.String("/root/test"), }, ).Return(int64(len(data)), nil) // A plain io.Writer will require a buffer to download. w := make(rwutil.PlainWriter, len(data)) require.NoError(client.Download(core.NamespaceFixture(), "test", w)) require.Equal(data, []byte(w)) } func TestClientUpload(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() data := bytes.NewReader(randutil.Text(32)) mocks.s3.EXPECT().Upload( &s3manager.UploadInput{ Bucket: aws.String("test-bucket"), Key: aws.String("/root/test"), Body: data, }, gomock.Any(), ).Return(nil, nil) require.NoError(client.Upload(core.NamespaceFixture(), "test", data)) } func TestClientList(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() mocks.s3.EXPECT().ListObjectsV2Pages( &s3.ListObjectsV2Input{ Bucket: aws.String("test-bucket"), MaxKeys: aws.Int64(250), Prefix: aws.String("root/test"), }, gomock.Any(), ).DoAndReturn(func( input *s3.ListObjectsV2Input, f func(page *s3.ListObjectsV2Output, last bool) bool) error { shouldContinue := f(&s3.ListObjectsV2Output{ Contents: []*s3.Object{ {Key: aws.String("root/test/a")}, {Key: aws.String("root/test/b")}, }, }, false) if shouldContinue { f(&s3.ListObjectsV2Output{ Contents: []*s3.Object{ {Key: aws.String("root/test/c")}, {Key: aws.String("root/test/d")}, }, }, true) } return nil }) result, err := client.List("test") require.NoError(err) require.Equal([]string{"test/a", "test/b", "test/c", "test/d"}, result.Names) } func TestClientListPaginated(t *testing.T) { require := require.New(t) mocks, cleanup := newClientMocks(t) defer cleanup() client := mocks.new() mocks.s3.EXPECT().ListObjectsV2Pages( &s3.ListObjectsV2Input{ Bucket: aws.String("test-bucket"), MaxKeys: aws.Int64(2), Prefix: aws.String("root/test"), }, gomock.Any(), ).DoAndReturn(func( input *s3.ListObjectsV2Input, f func(page *s3.ListObjectsV2Output, last bool) bool) error { f(&s3.ListObjectsV2Output{ Contents: []*s3.Object{ {Key: aws.String("root/test/a")}, {Key: aws.String("root/test/b")}, }, IsTruncated: aws.Bool(true), NextContinuationToken: aws.String("test-continuation-token"), }, false) return nil }) mocks.s3.EXPECT().ListObjectsV2Pages( &s3.ListObjectsV2Input{ Bucket: aws.String("test-bucket"), MaxKeys: aws.Int64(2), Prefix: aws.String("root/test"), ContinuationToken: aws.String("test-continuation-token"), }, gomock.Any(), ).DoAndReturn(func( input *s3.ListObjectsV2Input, f func(page *s3.ListObjectsV2Output, last bool) bool) error { f(&s3.ListObjectsV2Output{ Contents: []*s3.Object{ {Key: aws.String("root/test/c")}, {Key: aws.String("root/test/d")}, }, IsTruncated: aws.Bool(false), }, true) return nil }) result, err := client.List("test", backend.ListWithPagination(), backend.ListWithMaxKeys(2), ) require.NoError(err) require.Equal([]string{"test/a", "test/b"}, result.Names) require.Equal("test-continuation-token", result.ContinuationToken) result, err = client.List("test", backend.ListWithPagination(), backend.ListWithMaxKeys(2), backend.ListWithContinuationToken(result.ContinuationToken), ) require.NoError(err) require.Equal([]string{"test/c", "test/d"}, result.Names) require.Equal("", result.ContinuationToken) }
package consent func ParseConsentVersion(s string) (byte, error) { if len(s) == 0 { return 0, ErrUnexpectedEnd } // string is base64-encoded and version is encoded in the first 6 bits (i.e. first char in b64 string) switch s[0] { case 'B': return 1, nil case 'C': return 2, nil } return 0, ErrUnsupported } type Consent interface { Version() byte String() string } func Parse(s string) (Consent, error) { v, err := ParseConsentVersion(s) if err != nil { return nil, err } switch v { case 1: return ParseV1(s) case 2: return ParseV2(s) } return nil, nil // unreachable } func Validate(s string) error { v, err := ParseConsentVersion(s) if err != nil { return err } switch v { case 1: return ValidateV1(s) case 2: return ValidateV2(s) } return nil // unreachable }
/* Copyright 2021 Gravitational, 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 db import ( "context" "fmt" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/aws/aws-sdk-go/service/rds/rdsiface" "github.com/gravitational/trace" "github.com/sirupsen/logrus" "github.com/gravitational/teleport/api/types" libcloudaws "github.com/gravitational/teleport/lib/cloud/aws" "github.com/gravitational/teleport/lib/services" "github.com/gravitational/teleport/lib/srv/discovery/common" ) // rdsFetcherConfig is the RDS databases fetcher configuration. type rdsFetcherConfig struct { // Labels is a selector to match cloud databases. Labels types.Labels // RDS is the RDS API client. RDS rdsiface.RDSAPI // Region is the AWS region to query databases in. Region string // AssumeRole is the AWS IAM role to assume before discovering databases. AssumeRole services.AssumeRole } // CheckAndSetDefaults validates the config and sets defaults. func (c *rdsFetcherConfig) CheckAndSetDefaults() error { if len(c.Labels) == 0 { return trace.BadParameter("missing parameter Labels") } if c.RDS == nil { return trace.BadParameter("missing parameter RDS") } if c.Region == "" { return trace.BadParameter("missing parameter Region") } return nil } // rdsDBInstancesFetcher retrieves RDS DB instances. type rdsDBInstancesFetcher struct { awsFetcher cfg rdsFetcherConfig log logrus.FieldLogger } // newRDSDBInstancesFetcher returns a new RDS DB instances fetcher instance. func newRDSDBInstancesFetcher(config rdsFetcherConfig) (common.Fetcher, error) { if err := config.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &rdsDBInstancesFetcher{ cfg: config, log: logrus.WithFields(logrus.Fields{ trace.Component: "watch:rds", "labels": config.Labels, "region": config.Region, "role": config.AssumeRole, }), }, nil } // Get returns RDS DB instances matching the watcher's selectors. func (f *rdsDBInstancesFetcher) Get(ctx context.Context) (types.ResourcesWithLabels, error) { rdsDatabases, err := f.getRDSDatabases(ctx) if err != nil { return nil, trace.Wrap(err) } applyAssumeRoleToDatabases(rdsDatabases, f.cfg.AssumeRole) return filterDatabasesByLabels(rdsDatabases, f.cfg.Labels, f.log).AsResources(), nil } // getRDSDatabases returns a list of database resources representing RDS instances. func (f *rdsDBInstancesFetcher) getRDSDatabases(ctx context.Context) (types.Databases, error) { instances, err := getAllDBInstances(ctx, f.cfg.RDS, maxAWSPages, f.log) if err != nil { return nil, trace.Wrap(libcloudaws.ConvertRequestFailureError(err)) } databases := make(types.Databases, 0, len(instances)) for _, instance := range instances { if !services.IsRDSInstanceSupported(instance) { f.log.Debugf("RDS instance %q (engine mode %v, engine version %v) doesn't support IAM authentication. Skipping.", aws.StringValue(instance.DBInstanceIdentifier), aws.StringValue(instance.Engine), aws.StringValue(instance.EngineVersion)) continue } if !services.IsRDSInstanceAvailable(instance.DBInstanceStatus, instance.DBInstanceIdentifier) { f.log.Debugf("The current status of RDS instance %q is %q. Skipping.", aws.StringValue(instance.DBInstanceIdentifier), aws.StringValue(instance.DBInstanceStatus)) continue } database, err := services.NewDatabaseFromRDSInstance(instance) if err != nil { f.log.Warnf("Could not convert RDS instance %q to database resource: %v.", aws.StringValue(instance.DBInstanceIdentifier), err) } else { databases = append(databases, database) } } return databases, nil } // getAllDBInstances fetches all RDS instances using the provided client, up // to the specified max number of pages. func getAllDBInstances(ctx context.Context, rdsClient rdsiface.RDSAPI, maxPages int, log logrus.FieldLogger) ([]*rds.DBInstance, error) { var instances []*rds.DBInstance err := retryWithIndividualEngineFilters(log, rdsInstanceEngines(), func(filters []*rds.Filter) error { var pageNum int var out []*rds.DBInstance err := rdsClient.DescribeDBInstancesPagesWithContext(ctx, &rds.DescribeDBInstancesInput{ Filters: filters, }, func(ddo *rds.DescribeDBInstancesOutput, lastPage bool) bool { pageNum++ instances = append(instances, ddo.DBInstances...) return pageNum <= maxPages }) if err == nil { // only append to instances on nil error, just in case we have to retry. instances = append(instances, out...) } return trace.Wrap(err) }) return instances, trace.Wrap(err) } // String returns the fetcher's string description. func (f *rdsDBInstancesFetcher) String() string { return fmt.Sprintf("rdsDBInstancesFetcher(Region=%v, Labels=%v)", f.cfg.Region, f.cfg.Labels) } // rdsAuroraClustersFetcher retrieves RDS Aurora clusters. type rdsAuroraClustersFetcher struct { awsFetcher cfg rdsFetcherConfig log logrus.FieldLogger } // newRDSAuroraClustersFetcher returns a new RDS Aurora fetcher instance. func newRDSAuroraClustersFetcher(config rdsFetcherConfig) (common.Fetcher, error) { if err := config.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &rdsAuroraClustersFetcher{ cfg: config, log: logrus.WithFields(logrus.Fields{ trace.Component: "watch:aurora", "labels": config.Labels, "region": config.Region, "role": config.AssumeRole, }), }, nil } // Get returns Aurora clusters matching the watcher's selectors. func (f *rdsAuroraClustersFetcher) Get(ctx context.Context) (types.ResourcesWithLabels, error) { auroraDatabases, err := f.getAuroraDatabases(ctx) if err != nil { return nil, trace.Wrap(err) } applyAssumeRoleToDatabases(auroraDatabases, f.cfg.AssumeRole) return filterDatabasesByLabels(auroraDatabases, f.cfg.Labels, f.log).AsResources(), nil } // getAuroraDatabases returns a list of database resources representing RDS clusters. func (f *rdsAuroraClustersFetcher) getAuroraDatabases(ctx context.Context) (types.Databases, error) { clusters, err := getAllDBClusters(ctx, f.cfg.RDS, maxAWSPages, f.log) if err != nil { return nil, trace.Wrap(libcloudaws.ConvertRequestFailureError(err)) } databases := make(types.Databases, 0, len(clusters)) for _, cluster := range clusters { if !services.IsRDSClusterSupported(cluster) { f.log.Debugf("Aurora cluster %q (engine mode %v, engine version %v) doesn't support IAM authentication. Skipping.", aws.StringValue(cluster.DBClusterIdentifier), aws.StringValue(cluster.EngineMode), aws.StringValue(cluster.EngineVersion)) continue } if !services.IsRDSClusterAvailable(cluster.Status, cluster.DBClusterIdentifier) { f.log.Debugf("The current status of Aurora cluster %q is %q. Skipping.", aws.StringValue(cluster.DBClusterIdentifier), aws.StringValue(cluster.Status)) continue } // Find out what types of instances the cluster has. Some examples: // - Aurora cluster with one instance: one writer // - Aurora cluster with three instances: one writer and two readers // - Secondary cluster of a global database: one or more readers var hasWriterInstance, hasReaderInstance bool for _, clusterMember := range cluster.DBClusterMembers { if clusterMember != nil { if aws.BoolValue(clusterMember.IsClusterWriter) { hasWriterInstance = true } else { hasReaderInstance = true } } } // Add a database from primary endpoint, if any writer instances. if cluster.Endpoint != nil && hasWriterInstance { database, err := services.NewDatabaseFromRDSCluster(cluster) if err != nil { f.log.Warnf("Could not convert RDS cluster %q to database resource: %v.", aws.StringValue(cluster.DBClusterIdentifier), err) } else { databases = append(databases, database) } } // Add a database from reader endpoint, if any reader instances. // https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html#Aurora.Endpoints.Reader if cluster.ReaderEndpoint != nil && hasReaderInstance { database, err := services.NewDatabaseFromRDSClusterReaderEndpoint(cluster) if err != nil { f.log.Warnf("Could not convert RDS cluster %q reader endpoint to database resource: %v.", aws.StringValue(cluster.DBClusterIdentifier), err) } else { databases = append(databases, database) } } // Add databases from custom endpoints if len(cluster.CustomEndpoints) > 0 { customEndpointDatabases, err := services.NewDatabasesFromRDSClusterCustomEndpoints(cluster) if err != nil { f.log.Warnf("Could not convert RDS cluster %q custom endpoints to database resources: %v.", aws.StringValue(cluster.DBClusterIdentifier), err) } databases = append(databases, customEndpointDatabases...) } } return databases, nil } // getAllDBClusters fetches all RDS clusters using the provided client, up to // the specified max number of pages. func getAllDBClusters(ctx context.Context, rdsClient rdsiface.RDSAPI, maxPages int, log logrus.FieldLogger) ([]*rds.DBCluster, error) { var clusters []*rds.DBCluster err := retryWithIndividualEngineFilters(log, auroraEngines(), func(filters []*rds.Filter) error { var pageNum int var out []*rds.DBCluster err := rdsClient.DescribeDBClustersPagesWithContext(ctx, &rds.DescribeDBClustersInput{ Filters: filters, }, func(ddo *rds.DescribeDBClustersOutput, lastPage bool) bool { pageNum++ out = append(out, ddo.DBClusters...) return pageNum <= maxPages }) if err == nil { // only append to clusters on nil error, just in case we have to retry. clusters = append(clusters, out...) } return trace.Wrap(err) }) return clusters, trace.Wrap(err) } // String returns the fetcher's string description. func (f *rdsAuroraClustersFetcher) String() string { return fmt.Sprintf("rdsAuroraClustersFetcher(Region=%v, Labels=%v)", f.cfg.Region, f.cfg.Labels) } // rdsInstanceEngines returns engines to make sure DescribeDBInstances call returns // only databases with engines Teleport supports. func rdsInstanceEngines() []string { return []string{ services.RDSEnginePostgres, services.RDSEngineMySQL, services.RDSEngineMariaDB, } } // auroraEngines returns engines to make sure DescribeDBClusters call returns // only databases with engines Teleport supports. func auroraEngines() []string { return []string{ services.RDSEngineAurora, services.RDSEngineAuroraMySQL, services.RDSEngineAuroraPostgres, } } // rdsEngineFilter is a helper func to construct an RDS filter for engine names. func rdsEngineFilter(engines []string) []*rds.Filter { return []*rds.Filter{{ Name: aws.String("engine"), Values: aws.StringSlice(engines), }} } // rdsFilterFn is a function that takes RDS filters and performs some operation with them, returning any error encountered. type rdsFilterFn func([]*rds.Filter) error // retryWithIndividualEngineFilters is a helper error handling function for AWS RDS unrecognized engine name filter errors, // that will call the provided RDS querying function with filters, check the returned error, // and if the error is an AWS unrecognized engine name error then it will retry once by calling the function with one filter // at a time. If any error other than an AWS unrecognized engine name error occurs, this function will return that error // without retrying, or skip retrying subsequent filters if it has already started to retry. func retryWithIndividualEngineFilters(log logrus.FieldLogger, engines []string, fn rdsFilterFn) error { err := fn(rdsEngineFilter(engines)) if err == nil { return nil } if !isUnrecognizedAWSEngineNameError(err) { return trace.Wrap(err) } log.WithError(trace.Unwrap(err)).Debug("Teleport supports an engine which is unrecognized in this AWS region. Querying engine names individually.") for _, engine := range engines { err := fn(rdsEngineFilter([]string{engine})) if err == nil { continue } if !isUnrecognizedAWSEngineNameError(err) { return trace.Wrap(err) } // skip logging unrecognized engine name error here, we already logged it in the initial attempt. } return nil } // isUnrecognizedAWSEngineNameError checks if the err is non-nil and came from using an engine filter that the // AWS region does not recognize. func isUnrecognizedAWSEngineNameError(err error) bool { if err == nil { return false } return strings.Contains(strings.ToLower(err.Error()), "unrecognized engine name") }
package user import ( "github.com/gin-gonic/gin" "fmt" "github.com/goweb/model" "github.com/goweb/db" "net/http" "github.com/goweb/common" ) func Save(c *gin.Context) { name := c.Query("name") pwd := c.Query("password") email := c.Query("email") fmt.Printf("save user %s in controller\n",name) var u model.User if err := db.DB.Where(" name = ?", name).Find(&u).Error; err == nil { fmt.Printf("sorry,user name %s exist.\n", name) common.SendErrorJson("user " + name + " exist",c) return } u.Name = name u.Password = pwd u.Email = email u.Status = 0 if err := db.DB.Create(&u).Error; err != nil { fmt.Errorf("insert user error",err) return } go func() { sendEmail(email, "New user active","<a href='http://localhost:8081/active/"+ name + "'>please active your account</a>") }() c.JSON(http.StatusOK,gin.H{ "result":"OK", }) } func sendEmail(to string, title string, content string) { common.SendMail(to,title,content) } func ActiveUser( c *gin.Context) { name := c.Param("name") fmt.Printf("active name %s\n", name) var u model.User if err := db.DB.Where(" name = ?", name).Find(&u).Error; err != nil { fmt.Println("query user error",err) return } u.Status = 1 fmt.Println("user->",u) if err := db.DB.Model(&u).Update(&u).Error; err != nil { fmt.Printf("active user status error", err) return } c.JSON(http.StatusOK, gin.H{ "status":"OK", }) } func GetUserList(c *gin.Context) { var userList []model.User if err := db.DB.Find(&userList).Error; err != nil { fmt.Println("query user list error") } c.JSON(http.StatusOK,gin.H{ "result":userList, }) } // @Summary get user by id // @Description get use by id // @Accept json // @Produce json // @Param id path int true "user id" // @Success 200 {string} json "{"result":{},"count":"1"}" // @Router /user/{id} [get] func GetUserById( c *gin.Context) { id := c.Param("id") var u model.User if err := db.DB.Where(" id = ?", id).First(&u).Error; err != nil { fmt.Println("query user by id error",err) } c.JSON(http.StatusOK, gin.H{ "result":u, "count":1, }) } func DeleteUserById(c *gin.Context) { id := c.Param("id") var u model.User if err := db.DB.Where(" id = ?", id).Delete(&u).Error; err != nil { fmt.Println("delete user by id error") } c.JSON(http.StatusOK,gin.H{ "count":1, }) }
// Package game contains data structures and functions which encapsulate the // complete set of rules of "Tic Tac Toe 2.0". package game import ( "errors" ) const ( RequiredNumberOfPlayers = 3 ) var ( ErrSizeIllegal = errors.New("size illegal") ) // Move represents a Player's intended action. It contains their Player as well // as Board coordinates. type Move struct { Player X, Y int } // Game is the complete set of data necessary to derive all necessary // informations about a given Game from. type Game struct { size Size players Players history History } // New returns a new Game. func New(s Size) (*Game, error) { g := &Game{size: s} ok := s.IsLegal() if !ok { return g, ErrSizeIllegal } return g, nil } // Board derives a Board from the current Game. If Move coordinates in the // History have duplicates or are out of bounds it returns an error. func (g *Game) Board() Board { b := make(Board, g.size) for x, _ := range b { b[x] = make([]Player, g.size) } for _, m := range g.history { b[m.X][m.Y] = m.Player } return b } // WhoIsNext derives the Player currently waiting in Line. func (g *Game) WhoIsNext() Player { if len(g.players) < RequiredNumberOfPlayers { return NoPlayer } if len(g.history) == 0 { return g.players[0] } i := len(g.history) % len(g.players) return g.players[i] }
package main import "fmt" func main() { //加一 /** 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。你可以假设除了整数 0 之外,这个整数不会以零开头。 示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321。 */ nums := []int{4, 3, 2, 1} nums2 := []int{9, 9, 9, 9} fmt.Println(plusOne(nums)) fmt.Println(plusOne(nums2)) } func plusOne(nums []int) []int { var result []int addon := 0 for i := len(nums) - 1; i >= 0; i-- { //在进位的基础上再加一 nums[i] += addon //重置进位 addon = 0 //如果是第一次,直接加一 if i == len(nums)-1 { nums[i]++ } //如果加以等于10,则需要进位处理 if nums[i] == 10 { addon = 1 nums[i] = 0 } } if addon == 1 { result = make([]int, 1) result[0] = 1 result = append(result, nums...) } else { result = nums } return result }
package post import ( "io/ioutil" "log" "net/http" "github.com/cc2k19/go-tin/storage" "github.com/cc2k19/go-tin/web" ) type controller struct { repository storage.Repository credentialsExtractor web.CredentialsExtractor } func (c *controller) add(rw http.ResponseWriter, r *http.Request) { defer r.Body.Close() ctx := r.Context() body, err := ioutil.ReadAll(r.Body) if err != nil { log.Printf("Could not extract body: %s\n", err) rw.WriteHeader(http.StatusBadRequest) return } username, _, err := c.credentialsExtractor.Extract(r) if err != nil { log.Printf("Authorization decode error: %s", err) rw.WriteHeader(http.StatusBadRequest) return } err = c.repository.AddPost(ctx, username, body) if err != nil { log.Printf("Persisting post for user %s failed: %s\n", username, err) rw.WriteHeader(http.StatusBadRequest) return } rw.WriteHeader(http.StatusCreated) } func (c *controller) get(rw http.ResponseWriter, r *http.Request) { ctx := r.Context() username, _, err := c.credentialsExtractor.Extract(r) if err != nil { log.Printf("Authorization decode error: %s", err) rw.WriteHeader(http.StatusNotFound) return } posts, err := c.repository.GetTargetsPosts(ctx, username) if err != nil { log.Printf("Get posts for %s failed: %s\n", username, err) rw.WriteHeader(http.StatusNotFound) return } web.WriteResponse(rw, http.StatusOK, posts) }
package main import ( "bufio" "bytes" "fmt" "io/ioutil" "os" ) func countFile(filepath string) (*FileStats, error) { fin := os.Stdin if filepath != "/dev/stdin" { inf, err := os.Lstat(filepath) if err != nil || inf.IsDir() { return nil, fmt.Errorf("invalid file entry") } f, err := os.Open(filepath) if err != nil { return nil, err } fin = f } // TODO customize a ScanFunc to read and count only once dat, err := ioutil.ReadAll(fin) if err != nil { return nil, err } info := FileStats{ FilePath: filepath, } // count chars, wc -m sc := bufio.NewScanner(bytes.NewBuffer(dat)) sc.Split(bufio.ScanRunes) for sc.Scan() { info.CountByChars++ } // count words, wc -w sc = bufio.NewScanner(bytes.NewBuffer(dat)) sc.Split(bufio.ScanWords) for sc.Scan() { info.CountByWords++ } // count lines, wc -l sc = bufio.NewScanner(bytes.NewBuffer(dat)) sc.Split(bufio.ScanLines) for sc.Scan() { info.CountByLines++ } // count bytes, wc -c sc = bufio.NewScanner(bytes.NewBuffer(dat)) sc.Split(bufio.ScanBytes) for sc.Scan() { info.CountByBytes++ } return &info, nil }
package main import ( //"bufio" "fmt" "os" // "strings" ) // a plumbService coordinates communication between a de process, and a deplumber // process. // // (The deplumber process communicates with the p9p plumber and receives messages. // It decides whether or not to spawn a new window or re-use the existing one as // best as it can.) type plumbService struct { // A channel which communicates that a file named // string should be opened. OpenChan chan string // A channel on which the main thread communicates the // clean/dirty status of its buffer to us. DirtyChan chan bool // A channel which the plumbService communicates errors over. ErrorChan chan error // The file used for communication with the deplumber service conn *os.File // Set to true at the end of initialization, so that Connect() // doesn't need to block and Available() will work. ready bool } // Connect connects the plumbService to a deplumber instance, and returns // channels that it may asynchronously communicate with the main thread // over. // // In particular, if there's any errors they will be sent over the errors // channel instead of returned directly, to avoid having to block when calling // connect. // // dirtyChan is a channel that de communicates the buffer dirty status to // the plumbService over. func (p *plumbService) Connect(dirtyChan chan bool) { p.ErrorChan = make(chan error, 1) p.OpenChan = make(chan string) p.DirtyChan = dirtyChan // Read the ~/.de/deplumber file to see where we should connect file, err := os.OpenFile("/tmp/deplumber", os.O_RDWR|os.O_APPEND, 0600) if err != nil { p.ErrorChan <- fmt.Errorf("deplumber not started. Plumbing not available.") close(p.ErrorChan) return } p.conn = file // Monitor the dirtyChan for messages from the main thread saying // our dirty bit has changed, and inform the deplumber as appropriate. go p.dirtyMonitor() // We're now ready to receive messages and monitor the connection for // new files that we should open. go p.monitorOpenChan() return } // Returns whether the plumbing service is available and ready // to plumb messages func (p *plumbService) Available() bool { return p.ready } // Goes into an infinite loop monitoring the dirtyChan // for changes in buffer status, and forwards them to the // deplumber connection. // // This should only be called from a goroutine after the // connection is initialized. It communicates from de to // the deplumber. func (p *plumbService) dirtyMonitor() { for { dirty := <-p.DirtyChan if dirty { fmt.Fprintf(p.conn, "%d:Dirty\n", os.Getpid()) } else { fmt.Fprintf(p.conn, "%d:Clean\n", os.Getpid()) } } } // Goes into an infinite loop, reading messages from the socket connection // and sending them across the OpenChan // // This should also only be called from a goroutine after the connection is // initialized. It communicates from the deplumber to de. func (p *plumbService) monitorOpenChan() { // We've connected to the deplumber service, so send it our PID and tell // it we have a clean buffer fmt.Fprintf(p.conn, "%d:Clean\n", os.Getpid()) p.ready = true c := make(chan os.Signal) for { select { case s := <-c: fmt.Printf("%v", s) p.ErrorChan <- fmt.Errorf("%v", s) } } //r := bufio.NewReader(p.conn) /* for { file, err := r.ReadString('\n') switch err { case io.EOF: } if err != nil { println("foo") p.ErrorChan <- err p.ready = false return } file = strings.TrimSpace(file) p.OpenChan <- file } */ }
package api import ( "github.com/gin-gonic/gin" "github.com/oceanho/gw" "github.com/oceanho/gw/contrib/apps/tester/biz" "github.com/oceanho/gw/contrib/apps/tester/dto" ) func CreateMyTester(c *gw.Context) { obj := &dto.MyTester{} if c.Bind(obj) != nil { return } err := biz.CreateMyTester(c.Store().GetDbStore(), obj) c.JSON(err, obj.ID) } func QueryMyTester(c *gw.Context) { query := &gw.QueryExpr{} if c.Bind(query) != nil { return } objs := make([]dto.MyTester, 0) err := biz.QueryMyTester(c.Store().GetDbStore(), &objs) c.JSON(err, objs) } func GetTester(c *gw.Context) { c.JSON200(struct { RequestID string }{ RequestID: c.RequestId(), }) } func GetTester400(c *gw.Context) { c.JSON400(4000) } func GetTester400WithCustomErr(c *gw.Context) { c.JSON400Msg(4000, "Custom 400 Err") } func GetTester400WithCustomPayload(c *gw.Context) { c.JSON400Payload(4000, "Custom 400 Payload") } func GetTester400WithCustomPayloadErr(c *gw.Context) { c.JSON400PayloadMsg(4000, "Custom 400 Err and Payload", gin.H{"A": "a"}) } func GetTester401(c *gw.Context) { c.JSON401(4001) } func GetTester401WithCustomErr(c *gw.Context) { c.JSON401Msg(4001, "Custom 401 Err") } func GetTester401WithCustomPayload(c *gw.Context) { c.JSON401Payload(4001, "Custom 401 Payload") } func GetTester401WithCustomPayloadErr(c *gw.Context) { c.JSON401PayloadMsg(4001, "Custom 401 Err and Payload", gin.H{"A": "a"}) } func GetTester403(c *gw.Context) { c.JSON403(4003) } func GetTester403WithCustomErr(c *gw.Context) { c.JSON403Msg(4003, "Custom 403 Err") } func GetTester403WithCustomPayload(c *gw.Context) { c.JSON403Payload(4003, "Custom 403 Payload") } func GetTester403WithCustomPayloadErr(c *gw.Context) { c.JSON403PayloadMsg(4003, "Custom 403 Err and Payload", gin.H{"A": "a"}) } func GetTester404(c *gw.Context) { c.JSON404(4004) } func GetTester404WithCustomErr(c *gw.Context) { c.JSON404Msg(4004, "Custom 404 Err") } func GetTester404WithCustomPayload(c *gw.Context) { c.JSON404Payload(4004, "Custom 404 Payload") } func GetTester404WithCustomPayloadErr(c *gw.Context) { c.JSON404PayloadMsg(4004, "Custom 404 Err and Payload", gin.H{"A": "a"}) } func GetTester500(c *gw.Context) { c.JSON500(5000) } func GetTester500WithCustomErr(c *gw.Context) { c.JSON500Msg(5000, "Custom 500 Err") } func GetTester500WithCustomPayload(c *gw.Context) { c.JSON500Payload(5000, "Custom 500 Payload") } func GetTester500WithCustomPayloadErr(c *gw.Context) { c.JSON500PayloadMsg(5000, "Custom 500 Err and Payload", gin.H{"A": "a"}) }