text
stringlengths
11
4.05M
package addressmap import ( "github.com/cocher/utils/log" "github.com/cocher/network" "github.com/cocher/peer" ) type Component struct { *network.Component MappingAddress string } var ( // ComponentID to reference address mapping Component ComponentID = (*Component)(nil) _ network.ComponentInterface = (*Component)(nil) ) func (p *Component) Startup(n *network.Network) { log.Infof("Setting up address mapping for address: %s", n.Address) info, err := network.ParseAddress(n.Address) if err != nil { log.Errorf("error parsing network address %s", n.Address) return } mapInfo, err := network.ParseAddress(p.MappingAddress) if err != nil { log.Errorf("error parsing mapping address %s", p.MappingAddress) return } log.Infof("update mapping address from %s to %s", info.String(), mapInfo.String()) n.Address = mapInfo.String() n.ID = peer.CreateID(n.Address, n.GetKeys().PublicKey) }
package main import ( "context" "time" "github.com/prometheus/client_golang/prometheus" "github.com/webdevops/go-common/prometheus/collector" "go.uber.org/zap" devopsClient "github.com/webdevops/azure-devops-exporter/azure-devops-client" ) type MetricsCollectorStats struct { collector.Processor prometheus struct { agentPoolBuildCount *prometheus.CounterVec agentPoolBuildWait *prometheus.SummaryVec agentPoolBuildDuration *prometheus.SummaryVec projectBuildCount *prometheus.CounterVec projectBuildWait *prometheus.SummaryVec projectBuildDuration *prometheus.SummaryVec projectBuildSuccess *prometheus.SummaryVec projectReleaseDuration *prometheus.SummaryVec projectReleaseSuccess *prometheus.SummaryVec } } func (m *MetricsCollectorStats) Setup(collector *collector.Collector) { m.Processor.Setup(collector) // ------------------------------------------ // AgentPool // ------------------------------------------ m.prometheus.agentPoolBuildCount = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "azure_devops_stats_agentpool_builds", Help: "Azure DevOps stats agentpool builds counter", }, []string{ "agentPoolID", "projectID", "result", }, ) m.Collector.RegisterMetricList("agentPoolBuildCount", m.prometheus.agentPoolBuildCount, false) m.prometheus.agentPoolBuildWait = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_agentpool_builds_wait", Help: "Azure DevOps stats agentpool builds wait duration", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "agentPoolID", "projectID", "result", }, ) m.Collector.RegisterMetricList("agentPoolBuildWait", m.prometheus.agentPoolBuildWait, false) m.prometheus.agentPoolBuildDuration = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_agentpool_builds_duration", Help: "Azure DevOps stats agentpool builds process duration", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "agentPoolID", "projectID", "result", }, ) m.Collector.RegisterMetricList("agentPoolBuildDuration", m.prometheus.agentPoolBuildDuration, false) // ------------------------------------------ // Project // ------------------------------------------ m.prometheus.projectBuildCount = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "azure_devops_stats_project_builds", Help: "Azure DevOps stats project builds counter", }, []string{ "projectID", "buildDefinitionID", "result", }, ) m.Collector.RegisterMetricList("projectBuildCount", m.prometheus.projectBuildCount, false) m.prometheus.projectBuildSuccess = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_project_success", Help: "Azure DevOps stats project success", }, []string{ "projectID", "buildDefinitionID", }, ) m.Collector.RegisterMetricList("projectBuildSuccess", m.prometheus.projectBuildSuccess, false) m.prometheus.projectBuildWait = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_project_builds_wait", Help: "Azure DevOps stats project builds wait duration", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "projectID", "buildDefinitionID", "result", }, ) m.Collector.RegisterMetricList("projectBuildWait", m.prometheus.projectBuildWait, false) m.prometheus.projectBuildDuration = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_project_builds_duration", Help: "Azure DevOps stats project builds process duration", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "projectID", "buildDefinitionID", "result", }, ) m.Collector.RegisterMetricList("projectBuildDuration", m.prometheus.projectBuildDuration, false) m.prometheus.projectReleaseDuration = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_project_release_duration", Help: "Azure DevOps stats project release process duration", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "projectID", "releaseDefinitionID", "definitionEnvironmentID", "status", }, ) m.Collector.RegisterMetricList("projectReleaseDuration", m.prometheus.projectReleaseDuration, false) m.prometheus.projectReleaseSuccess = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "azure_devops_stats_project_release_success", Help: "Azure DevOps stats project release success", MaxAge: *opts.Stats.SummaryMaxAge, }, []string{ "projectID", "releaseDefinitionID", "definitionEnvironmentID", }, ) m.Collector.RegisterMetricList("projectReleaseSuccess", m.prometheus.projectReleaseSuccess, false) } func (m *MetricsCollectorStats) Reset() {} func (m *MetricsCollectorStats) Collect(callback chan<- func()) { ctx := m.Context() logger := m.Logger() for _, project := range AzureDevopsServiceDiscovery.ProjectList() { projectLogger := logger.With(zap.String("project", project.Name)) m.CollectBuilds(ctx, projectLogger, callback, project) m.CollectReleases(ctx, projectLogger, callback, project) } } func (m *MetricsCollectorStats) CollectReleases(ctx context.Context, logger *zap.SugaredLogger, callback chan<- func(), project devopsClient.Project) { minTime := time.Now().Add(-*m.Collector.GetScapeTime()) if val := m.Collector.GetLastScapeTime(); val != nil { minTime = *val } releaseList, err := AzureDevopsClient.ListReleaseHistory(project.Id, minTime) if err != nil { logger.Error(err) return } for _, release := range releaseList.List { for _, environment := range release.Environments { switch environment.Status { case "succeeded": m.prometheus.projectReleaseSuccess.With(prometheus.Labels{ "projectID": release.Project.Id, "releaseDefinitionID": int64ToString(release.Definition.Id), "definitionEnvironmentID": int64ToString(environment.DefinitionEnvironmentId), }).Observe(1) case "failed", "partiallySucceeded": m.prometheus.projectReleaseSuccess.With(prometheus.Labels{ "projectID": release.Project.Id, "releaseDefinitionID": int64ToString(release.Definition.Id), "definitionEnvironmentID": int64ToString(environment.DefinitionEnvironmentId), }).Observe(0) } timeToDeploy := environment.TimeToDeploy * 60 if timeToDeploy > 0 { m.prometheus.projectReleaseDuration.With(prometheus.Labels{ "projectID": release.Project.Id, "releaseDefinitionID": int64ToString(release.Definition.Id), "definitionEnvironmentID": int64ToString(environment.DefinitionEnvironmentId), "status": environment.Status, }).Observe(timeToDeploy) } } } } func (m *MetricsCollectorStats) CollectBuilds(ctx context.Context, logger *zap.SugaredLogger, callback chan<- func(), project devopsClient.Project) { minTime := time.Now().Add(-opts.Limit.BuildHistoryDuration) buildList, err := AzureDevopsClient.ListBuildHistoryWithStatus(project.Id, minTime, "completed") if err != nil { logger.Error(err) return } for _, build := range buildList.List { waitDuration := build.QueueDuration().Seconds() m.prometheus.agentPoolBuildCount.With(prometheus.Labels{ "agentPoolID": int64ToString(build.Queue.Pool.Id), "projectID": build.Project.Id, "result": build.Result, }).Inc() m.prometheus.projectBuildCount.With(prometheus.Labels{ "projectID": build.Project.Id, "buildDefinitionID": int64ToString(build.Definition.Id), "result": build.Result, }).Inc() switch build.Result { case "succeeded": m.prometheus.projectBuildSuccess.With(prometheus.Labels{ "projectID": build.Project.Id, "buildDefinitionID": int64ToString(build.Definition.Id), }).Observe(1) case "failed": m.prometheus.projectBuildSuccess.With(prometheus.Labels{ "projectID": build.Project.Id, "buildDefinitionID": int64ToString(build.Definition.Id), }).Observe(0) } if build.FinishTime.Second() >= 0 { jobDuration := build.FinishTime.Sub(build.StartTime) m.prometheus.agentPoolBuildDuration.With(prometheus.Labels{ "agentPoolID": int64ToString(build.Queue.Pool.Id), "projectID": build.Project.Id, "result": build.Result, }).Observe(jobDuration.Seconds()) m.prometheus.projectBuildDuration.With(prometheus.Labels{ "projectID": build.Project.Id, "buildDefinitionID": int64ToString(build.Definition.Id), "result": build.Result, }).Observe(jobDuration.Seconds()) } if waitDuration >= 0 { m.prometheus.agentPoolBuildWait.With(prometheus.Labels{ "agentPoolID": int64ToString(build.Queue.Pool.Id), "projectID": build.Project.Id, "result": build.Result, }).Observe(waitDuration) m.prometheus.projectBuildWait.With(prometheus.Labels{ "projectID": build.Project.Id, "buildDefinitionID": int64ToString(build.Definition.Id), "result": build.Result, }).Observe(waitDuration) } } }
package main import ( "github.com/arstercz/go-mysql/replication" "github.com/siddontang/go-mysql/mysql" "github.com/siddontang/go-mysql/client" "golang.org/x/net/context" "github.com/arstercz/goconfig" _ "github.com/davecgh/go-spew/spew" "os" "regexp" "time" "flag" "fmt" "strings" ) type SQLInfo struct { Type replication.EventType Host string Port int Schema string Table string Timestamp string Executiontime uint32 Binlogname string Logpos uint32 Eventsize uint32 Query string } var ( section = "replication" host = "localhost" port = int64(3306) username = "user_repl" password = "" database = "" table = "" binlog = "" serverid = int64(99999) pos = int64(0) rowevent = false ) func TimeFormat(t uint32) string { const time_format = "2006-01-02T15:04:05" return time.Unix(int64(t), 0).Format(time_format) } func LogOut(info SQLInfo) { fmt.Fprintf(os.Stdout, "\n\n") fmt.Fprintf(os.Stdout, "Time: %s\n", info.Timestamp) fmt.Fprintf(os.Stdout, "Type: %s\n", info.Type) fmt.Fprintf(os.Stdout, "Host: %s, Port: %d\n", info.Host, info.Port) fmt.Fprintf(os.Stdout, "Schema: %s\n", info.Schema) if info.Table != "" { fmt.Fprintf(os.Stdout, "Table: %s\n", info.Table) } fmt.Fprintf(os.Stdout, "Binlog: %s, Logpos: %d, Eventsize: %d\n", info.Binlogname, info.Logpos, info.Eventsize) if info.Query != "" { fmt.Fprintf(os.Stdout, "Query: %s\n", info.Query) } } func main() { conf := flag.String("conf", "", "configure file.") s := flag.String("section", "replication", "configure section.") h := flag.String("host", "localhost", "the mysql master server address.") P := flag.Int64("port", 3306, "the mysql master server port.") u := flag.String("user", "user_repl", "replicate user") p := flag.String("pass", "", "replicate user password") i := flag.Int64("serverid", 99999, "unique server id in the replication") f := flag.String("binlog", "", "replicate from this binlog file") n := flag.Int64("pos", 0, "replicate from this position which in the binlog file") d := flag.String("database", "", "only replicate the database.") t := flag.String("table", "", "only replicate the table, multiple tables are separated by commas") r := flag.Bool("rowevent", false, "whether print row event change") flag.Parse() rowevent = *r if len(*conf) <= 0 { host = *h port = *P username = *u password = *p serverid = *i binlog = *f pos = *n database = *d table = *t } else { section = *s c, err := goconfig.ReadConfigFile(*conf) host, err = c.GetString(section, "host") port, err = c.GetInt64(section, "port") username, err = c.GetString(section, "user") password, err = c.GetString(section, "pass") binlog, err = c.GetString(section, "binlog") pos, err = c.GetInt64(section, "pos") serverid, err = c.GetInt64(section, "serverid") database, err = c.GetString(section, "database") if err != nil { fmt.Fprintf(os.Stderr, "readconfigfile err: " + err.Error()) os.Exit(1) } } if serverid == 0 { serverid = *i } if (password == "") { fmt.Fprintf(os.Stderr, "[ERROR] must set password!\n\n\n") flag.PrintDefaults() os.Exit(1) } TypeCheck := map[replication.EventType]bool { replication.QUERY_EVENT: true, replication.TABLE_MAP_EVENT: true, replication.WRITE_ROWS_EVENTv0: true, replication.UPDATE_ROWS_EVENTv0: true, replication.DELETE_ROWS_EVENTv0: true, replication.WRITE_ROWS_EVENTv1: true, replication.UPDATE_ROWS_EVENTv1: true, replication.DELETE_ROWS_EVENTv1: true, replication.WRITE_ROWS_EVENTv2: true, replication.UPDATE_ROWS_EVENTv2: true, replication.DELETE_ROWS_EVENTv2: true, } replcfg := replication.BinlogSyncerConfig{ ServerID: uint32(serverid), Flavor: "mysql", Host: host, Port: uint16(port), User: username, Password: password, } if binlog == "" || pos == 0 { c, err := client.Connect(fmt.Sprintf("%s:%d", host, port), username, password, "") if err != nil { fmt.Printf("connect master error: %v\n", err) os.Exit(2) } rs, err := c.Execute("SHOW MASTER STATUS") if err != nil { fmt.Printf("get master status error: %v\n", err) os.Exit(3) } binlog, _ = rs.GetString(0, 0) pos, _ = rs.GetInt(0, 1) } syncer := replication.NewBinlogSyncer(replcfg) streamer, err := syncer.StartSync(mysql.Position{Name: binlog, Pos: uint32(pos)}) if err != nil { fmt.Fprintf(os.Stderr, "[ERROR] streamer error %s\n", err) os.Exit(1) } var tableid uint64 = 0 var tabletmp string for { event, _ := streamer.GetEvent(context.Background()) if ! TypeCheck[event.Header.EventType] { continue } meta, _ := event.Event.GetMeta() if database != "" && meta.Schema != "" && database != meta.Schema { continue } eventinfo := SQLInfo{} eventinfo.Type = replication.EventType(event.Header.EventType) eventinfo.Host = host eventinfo.Port = int(port) eventinfo.Timestamp = TimeFormat(event.Header.Timestamp) eventinfo.Binlogname = binlog eventinfo.Logpos = uint32(event.Header.LogPos) eventinfo.Eventsize = event.Header.EventSize ts := strings.Split(table, ",") switch eventinfo.Type { case replication.QUERY_EVENT: eventinfo.Schema = meta.Schema eventinfo.Table = meta.Table eventinfo.Query = meta.Query if len(table) > 0 { var matchstring = fmt.Sprintf("(?i:(\\s+))(") for k, v := range ts { matchstring += fmt.Sprintf("%s|`%s`", v, v) if k < len(ts) - 1 { matchstring += "|" } } matchstring += fmt.Sprintf(")\\s+)") //fmt.Printf("%s\n", matchstring) matched, err := regexp.MatchString(matchstring, meta.Query) if matched && err == nil { eventinfo.Table = table LogOut(eventinfo) } } else { LogOut(eventinfo) } case replication.ROTATE_EVENT: binlog = meta.Binlog case replication.TABLE_MAP_EVENT: eventinfo.Schema = meta.Schema eventinfo.Table = meta.Table tabletmp = meta.Table tableid = meta.TableID if len(table) > 0 { for _, v := range ts { if v == meta.Table { LogOut(eventinfo) } } } else { LogOut(eventinfo) } case replication.WRITE_ROWS_EVENTv0, replication.UPDATE_ROWS_EVENTv0, replication.DELETE_ROWS_EVENTv0, replication.WRITE_ROWS_EVENTv1, replication.UPDATE_ROWS_EVENTv1, replication.DELETE_ROWS_EVENTv1, replication.WRITE_ROWS_EVENTv2, replication.UPDATE_ROWS_EVENTv2, replication.DELETE_ROWS_EVENTv2: if tableid == meta.TableID { if len(table) > 0 { for _, v := range ts { if v == tabletmp { fmt.Fprintf(os.Stdout, "== %s ==\n", replication.EventType(event.Header.EventType)) if rowevent { event.Event.Dump(os.Stdout) } } } } else { fmt.Fprintf(os.Stdout, "== %s ==\n", replication.EventType(event.Header.EventType)) if rowevent { event.Event.Dump(os.Stdout) } } } tableid = 0 tabletmp = "" default: } } }
package ui import ( "image" ) // Group is a container of more components, similar to a transparent Window type Group struct { component } // NewGroup creates a new Group func NewGroup(width, height int) *Group { grp := Group{} grp.backgroundColor = Transparent grp.Dimension.Width = width grp.Dimension.Height = height return &grp } // AddChild adds a child to the group func (grp *Group) AddChild(c Component) { grp.addChild(c) } // Draw redraws internal buffer func (grp *Group) Draw(mx, my int) *image.RGBA { if grp.isHidden { grp.isClean = true return nil } // Limitation of current impl: // we cannot skip if children is clean because tooltip for children won't update then /* if grp.isClean { if grp.isChildrenClean() { return grp.Image } grp.isClean = false } */ grp.initImage() grp.drawChildren(mx-grp.Position.X, my-grp.Position.Y) grp.isClean = true return grp.Image } // Click pass click to window child components func (grp *Group) Click(mouse Point) bool { childPoint := Point{X: mouse.X - grp.Position.X, Y: mouse.Y - grp.Position.Y} for _, c := range grp.children { if childPoint.In(c.GetBounds()) { c.Click(childPoint) return true } } return false }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package utility import ( "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "strings" "github.com/mattermost/mattermost-cloud/internal/tools/helm" "github.com/mattermost/mattermost-cloud/model" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) const ( defaultKubeConfigPath = "" defaultHelmDeploymentSetArgument = "" ) // helmDeployment deploys Helm charts. type helmDeployment struct { chartDeploymentName string chartName string namespace string setArgument string desiredVersion *model.HelmUtilityVersion kubeconfigPath string logger log.FieldLogger } func newHelmDeployment( chartName, chartDeploymentName, namespace, kubeConfigPath string, desiredVersion *model.HelmUtilityVersion, setArgument string, logger log.FieldLogger, ) *helmDeployment { return &helmDeployment{ chartName: chartName, chartDeploymentName: chartDeploymentName, namespace: namespace, kubeconfigPath: kubeConfigPath, desiredVersion: desiredVersion, setArgument: setArgument, logger: logger, } } func (d *helmDeployment) Update() error { logger := d.logger.WithField("helm-update", d.chartName) logger.Infof("Refreshing helm chart %s -- may trigger service upgrade", d.chartName) err := upgradeHelmChart(*d, d.kubeconfigPath, logger) if err != nil { return errors.Wrap(err, fmt.Sprintf("got an error trying to upgrade the helm chart %s", d.chartName)) } return nil } func (d *helmDeployment) Delete() error { logger := d.logger.WithField("helm-delete", d.chartDeploymentName) // Ensure the chart is present before deletion exists, err := d.Exists() if err != nil { return err } if !exists { logger.Warnf("chart %s not present, assuming already deleted", d.chartDeploymentName) return nil } err = deleteHelmChart(*d, d.kubeconfigPath, logger) if err != nil { return errors.Wrapf(err, "got an error trying to delete the helm chart %s", d.chartDeploymentName) } return nil } func (d *helmDeployment) Exists() (bool, error) { list, err := d.List() if err != nil { return false, errors.Wrap(err, "failed to list helm charts") } for _, chart := range list.asSlice() { if chart.Name == d.chartDeploymentName && chart.Namespace == d.namespace { return true, nil } } return false, nil } // AddRepo adds new helm repos func AddRepo(repoName, repoURL string, logger log.FieldLogger) error { logger.Infof("Adding helm repo %s", repoName) arguments := []string{ "repo", "add", repoName, repoURL, } helmClient, err := helm.New(logger) if err != nil { return errors.Wrap(err, "unable to create helm wrapper") } defer helmClient.Close() err = helmClient.RunGenericCommand(arguments...) if err != nil { return errors.Wrapf(err, "unable to add repo %s", repoName) } return helmRepoUpdate(logger) } // helmRepoUpdate updates the helm repos to get latest available charts func helmRepoUpdate(logger log.FieldLogger) error { arguments := []string{ "repo", "update", } helmClient, err := helm.New(logger) if err != nil { return errors.Wrap(err, "unable to create helm wrapper") } defer helmClient.Close() err = helmClient.RunGenericCommand(arguments...) if err != nil { return errors.Wrap(err, "unable to update helm repos") } return nil } // upgradeHelmChart is used to upgrade Helm deployments. func upgradeHelmChart(chart helmDeployment, configPath string, logger log.FieldLogger) error { if chart.desiredVersion == nil || chart.desiredVersion.Version() == "" { currentVersion, err := chart.Version() if err != nil { return errors.Wrap(err, "failed to determine current chart version and no desired target version specified") } if currentVersion.Values() == "" { return errors.New("path to values file must not be empty") } chart.desiredVersion = currentVersion } censoredPath := chart.desiredVersion.ValuesPath defer func(chart *helmDeployment, censoredPath string) { // so that we don't store the GitLab secret in the database chart.desiredVersion.ValuesPath = censoredPath }(&chart, censoredPath) var err error var cleanup func(string) chart.desiredVersion.ValuesPath, cleanup, err = fetchFromGitlabIfNecessary(chart.desiredVersion.ValuesPath) if err != nil { return errors.Wrap(err, "failed to get values file") } if cleanup != nil { defer cleanup(chart.desiredVersion.ValuesPath) } arguments := []string{ "--debug", "upgrade", chart.chartDeploymentName, chart.chartName, "--kubeconfig", configPath, "-f", chart.desiredVersion.Values(), "--namespace", chart.namespace, "--install", "--create-namespace", "--wait", "--timeout", "20m", } if chart.setArgument != "" { arguments = append(arguments, "--set", chart.setArgument) } if chart.desiredVersion.Version() != "" { arguments = append(arguments, "--version", chart.desiredVersion.Version()) } helmClient, err := helm.New(logger) if err != nil { return errors.Wrap(err, "unable to create helm wrapper") } defer helmClient.Close() err = helmClient.RunGenericCommand(arguments...) if err != nil { return errors.Wrapf(err, "unable to upgrade helm chart %s", chart.chartName) } return nil } // deleteHelmChart is used to delete Helm charts. func deleteHelmChart(chart helmDeployment, configPath string, logger log.FieldLogger) error { arguments := []string{ "uninstall", chart.chartDeploymentName, "--kubeconfig", configPath, "--namespace", chart.namespace, "--wait", "--debug", } helmClient, err := helm.New(logger) if err != nil { return errors.Wrap(err, "unable to create helm wrapper") } defer helmClient.Close() err = helmClient.RunGenericCommand(arguments...) if err != nil { return errors.Wrapf(err, "unable to delete helm chart %s", chart.chartDeploymentName) } return nil } type helmReleaseJSON struct { Name string `json:"name"` Revision string `json:"revision"` Updated string `json:"updated"` Status string `json:"status"` Chart string `json:"chart"` AppVersion string `json:"appVersion"` Namespace string `json:"namespace"` } // HelmListOutput is a struct for holding the unmarshaled // representation of the output from helm list --output json type HelmListOutput []helmReleaseJSON func (l HelmListOutput) asSlice() []helmReleaseJSON { return l } func (l HelmListOutput) asListOutput() *HelmListOutput { return &l } func (d *helmDeployment) List() (*HelmListOutput, error) { arguments := []string{ "list", "--kubeconfig", d.kubeconfigPath, "--output", "json", "--all-namespaces", } logger := d.logger.WithFields(log.Fields{ "cmd": "helm3", }) helmClient, err := helm.New(logger) if err != nil { return nil, errors.Wrap(err, "unable to create helm wrapper") } defer helmClient.Close() rawOutput, err := helmClient.RunCommandRaw(arguments...) if err != nil { if len(rawOutput) > 0 { logger.Debugf("Helm output was:\n%s\n", string(rawOutput)) } return nil, errors.Wrap(err, "while listing Helm Releases") } var helmList HelmListOutput err = json.Unmarshal(rawOutput, &helmList) if err != nil { return nil, errors.Wrap(err, "unable to unmarshal JSON output from helm list") } return helmList.asListOutput(), nil } func (d *helmDeployment) Version() (*model.HelmUtilityVersion, error) { output, err := d.List() if err != nil { return nil, errors.Wrap(err, "while getting Helm Deployment version") } for _, release := range output.asSlice() { if release.Name == d.chartDeploymentName { return &model.HelmUtilityVersion{Chart: release.Chart, ValuesPath: d.desiredVersion.Values()}, nil } } return nil, errors.Errorf("unable to get version for chart %s", d.chartDeploymentName) } type gitlabValuesFileResponse struct { Content string `json:"content"` } // fetchFromGitlabIfNecessary returns the path of the values file. If // this is a local path or a non-Gitlab URL, the path is simply // returned unchanged. If a Gitlab URL is provided, the values file is // fetched and stored in the OS's temp dir and the filename of the // file is returned. If a temp file is created, a cleanup routine will // be returned as the second return value, otherwise that value will // be nil func fetchFromGitlabIfNecessary(path string) (string, func(string), error) { gitlabKey := model.GetGitlabToken() if gitlabKey == "" { return path, nil, nil } valPathURL, err := url.Parse(path) if err != nil { return "", nil, errors.Wrap(err, "failed to parse Helm values file path or URL") } // silently allow other public non-Gitlab URLs if !strings.HasPrefix(valPathURL.Host, "git") { return path, nil, nil } // if Gitlab, fetch the file using the API path = fmt.Sprintf("%s&private_token=%s", path, gitlabKey) resp, err := http.Get(path) if err != nil { return "", nil, errors.Wrap(err, "failed to request the values file from Gitlab") } if resp.StatusCode >= 400 { return "", nil, errors.Errorf("request to Gitlab failed with status: %s", resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return "", nil, errors.Wrap(err, "failed to read body from Gitlab response") } valuesFileBytes := new(gitlabValuesFileResponse) err = json.Unmarshal(body, valuesFileBytes) if err != nil { return "", nil, errors.Wrap(err, "failed to unmarshal JSON in Gitlab response") } temporaryValuesFile, err := os.CreateTemp(os.TempDir(), "helm-values-file-") if err != nil { return "", nil, errors.Wrap(err, "failed to create temporary file for Helm values file") } content, err := base64.StdEncoding.DecodeString(valuesFileBytes.Content) if err != nil { return "", nil, errors.Wrap(err, "failed to decode base64-encoded YAML file") } err = os.WriteFile(temporaryValuesFile.Name(), content, 0600) if err != nil { return "", nil, errors.Wrap(err, "failed to write values file to disk for Helm to read") } return temporaryValuesFile.Name(), func(path string) { if strings.HasPrefix(path, os.TempDir()) { os.Remove(path) } }, nil }
package cicd import ( "fmt" "net/http" platformK8s "github.com/dolittle/platform-api/pkg/platform/k8s" "github.com/dolittle/platform-api/pkg/utils" "github.com/gorilla/mux" "github.com/sirupsen/logrus" ) type service struct { logContext logrus.FieldLogger k8sDolittleRepo platformK8s.K8sPlatformRepo } func NewService(logContext logrus.FieldLogger, k8sDolittleRepo platformK8s.K8sPlatformRepo) *service { s := &service{ logContext: logContext, k8sDolittleRepo: k8sDolittleRepo, } return s } func (s *service) GetDevops(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) vars["name"] = "devops" mux.SetURLVars(r, vars) s.getServiceAccountCredentials(w, r) } func (s *service) getServiceAccountCredentials(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) applicationID := vars["applicationID"] serviceAccountName := vars["name"] userID := r.Header.Get("User-ID") customerID := r.Header.Get("Tenant-ID") allowed := s.k8sDolittleRepo.CanModifyApplicationWithResponse(w, customerID, applicationID, userID) if !allowed { return } logContext := s.logContext.WithFields(logrus.Fields{ "method": "GetServiceAccountCredentials", "credentials": "serviceAccount", "customerID": customerID, "applicationID": applicationID, "userID": userID, "serviceAccountName": serviceAccountName, }) logContext.Info("requested credentials") serviceAccount, err := s.k8sDolittleRepo.GetServiceAccount(logContext, applicationID, serviceAccountName) if err != nil { if err == platformK8s.ErrNotFound { utils.RespondWithError(w, http.StatusNotFound, fmt.Sprintf("Service account %s not found in application %s", serviceAccountName, applicationID)) return } utils.RespondWithError(w, http.StatusInternalServerError, "Something went wrong") return } secret, err := s.k8sDolittleRepo.GetSecret(logContext, applicationID, serviceAccount.Secrets[0].Name) if err != nil { utils.RespondWithError(w, http.StatusInternalServerError, "Something went wrong") return } utils.RespondWithJSON(w, http.StatusOK, secret) } func (s *service) GetContainerRegistryCredentials(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) applicationID := vars["applicationID"] userID := r.Header.Get("User-ID") customerID := r.Header.Get("Tenant-ID") allowed := s.k8sDolittleRepo.CanModifyApplicationWithResponse(w, customerID, applicationID, userID) if !allowed { return } logContext := s.logContext.WithFields(logrus.Fields{ "method": "GetServiceAccountCredentials", "credentials": "containerRegistry", "customerID": customerID, "applicationID": applicationID, "userID": userID, }) logContext.Info("requested credentials") secretName := "acr" secret, err := s.k8sDolittleRepo.GetSecret(logContext, applicationID, secretName) if err != nil { if err == platformK8s.ErrNotFound { utils.RespondWithError(w, http.StatusNotFound, fmt.Sprintf("Secret %s not found in application %s", secretName, applicationID)) return } utils.RespondWithError(w, http.StatusInternalServerError, "Something went wrong") return } utils.RespondWithJSON(w, http.StatusOK, secret.Data) }
/* pod-connector is a Command Line Interface tool for querying a local sentinel config file or a Red Skull sentinel management server for a given pod's configuration. It can optionally be used to launch redis-cli to connect to a pod given the pod name. */ package main
// Copyright 2018 Saferwall. All rights reserved. // Use of this source code is governed by Apache v2 license // license that can be found in the LICENSE file. // Package gib implements a gibberish string evaluator. package gib import ( "errors" "math" "strings" ) const ( // MinLength represents minimal length of a string to process. MinLength = 6 // DefaultNgramLength is the default ngram length of the prepared dataset. DefaultNgramLength = 4 // Dataset is the file path to the ngram dataset collected from a corpora. Dataset = "./data/ngram.json" ) // Options provides different option to create a new scorer. type Options struct { Dataset string } var ( lowerCaseLetters = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} scoreLenThreshold = 25. scoreLenPenalty = 0.9233 scoreRepPenalty = 0.9674 // MinScore represents the absolute minimal score for any given string MinScore = 8.6 ) // ngramsFromString returns a list of all n-grams of length n in a given string s. func ngramsFromString(s string, n int) []string { var ngrams = make([]string, 0, len(s)) for i := 0; i < len(s)-n+1; i++ { ngrams = append(ngrams, s[i:i+n]) } return ngrams } // allNgrams returns a list of all possible n-grams. func allNgrams(n int) []string { if n == 0 { return []string{} } else if n == 1 { return lowerCaseLetters } newNgrams := make([]string, 0) for _, letter := range lowerCaseLetters { for _, ngram := range allNgrams(n - 1) { newNgrams = append(newNgrams, letter+ngram) } } return newNgrams } // ngramIDFValue computes scores using modified TF-IDF. func ngramIDFValue(totalStrings, stringFreq, totalFreq, maxFreq float64) float64 { return math.Log2(totalStrings / (1. + stringFreq)) } // highestIDF computes highest idf value in map of ngram frequencies. func highestIDF(ngramFreq NGramScores) float64 { max := 0. for _, ngram := range ngramFreq { max = math.Max(max, ngram.IDF()) } return max } // highestFreq computes highest total frequency of any n-gram in a map of // n-gram score values for a given corpus. func highestFreq(ngramFreq NGramScores) float64 { max := 0. for _, ngram := range ngramFreq { max = math.Max(max, ngram.TotalFrequency()) } return max } // nGramValues computes n-gram statistics across a given corpus of strings. func nGramValues(corpus []string, n int, reAdjust bool) NGramScores { var counts = make(map[string]int, n) var occurrences = NewNGramSet() var numStrings int for _, s := range corpus { s = strings.ToLower(s) numStrings++ for _, ngram := range ngramsFromString(s, n) { occurrences.Add(ngram, s) counts[ngram]++ } } keys := allNgrams(n) values := make([]Score, len(keys)) generatedNGrams := NewNGramDict(keys, values) maxFreq := 0 // computes max count and assign it as max frequency of ngram for _, k := range counts { maxFreq = int(math.Max(float64(k), float64(maxFreq))) } for ngram, strings := range occurrences.Set { stringFreq := len(strings) totalFreq := counts[ngram] score := ngramIDFValue(float64(numStrings), float64(stringFreq), float64(totalFreq), float64(maxFreq)) generatedNGrams[ngram] = [3]float64{ float64(stringFreq), float64(totalFreq), score, } } if reAdjust { maxIDF := math.Ceil(highestIDF(generatedNGrams)) for ngram, value := range generatedNGrams { if value.IDF() == 0 { generatedNGrams[ngram] = [3]float64{ 0., 0., maxIDF, } } } } return generatedNGrams } // TFIDFScoreFunction generates a function that computes a score given a string. func TFIDFScoreFunction(ngramFreq NGramScores, n int, lenThres float64, lenPenalty float64, repPenalty float64) func(string) float64 { // Formula // S : a string to score // NGramFreq : map of NGramData // NGramLen : the n-gram length // MaxFreq : max frequency of any n-gram // LenPenalty : pow(max,0,numNGrams 0 lenThres), lenPenalty) // NGramScoreSum : 0 // for every n-gram in S: // c = count of times the n-gram appears in S // idf = IDF score of the n-gram from the ngramFreq map // tf = 0.5 + 0.5*(c/maxFreq) // repPenalty = pow(c,repPenalty) // ngramScoreSum += (tf * idf * repPenalty) // finalScore = (ngramScoreSum + lenPenalty) / (1 + numNGrams) maxFreq := highestFreq(ngramFreq) ngramLen := n score := func(s string) float64 { s = sanitize(s) ngramsInStr := ngramsFromString(s, ngramLen) ngramCounts := make(map[string]int) for _, ngram := range ngramsInStr { ngramCounts[ngram]++ } numNGrams := len(ngramsInStr) lengthPenalty := math.Pow(math.Max(0., float64(numNGrams)-lenThres), lenPenalty) // compute the scores // scores := make([]float64, 0) score := lengthPenalty for n, c := range ngramCounts { sc := ngramFreq.IDF(n) * math.Pow(float64(c), repPenalty) * (0.5 + 0.5*(float64(c)/maxFreq)) // scores = append(scores, sc) score += sc } return score / (1. + float64(numNGrams)) } return score } // NewScorer creates a new scoring function func NewScorer(opts *Options) (func(string) (bool, error), error) { var ngramFreq NGramScores var err error if opts != nil { ngramFreq, err = loadDataset(opts.Dataset) if err != nil { return nil, errors.New("failed to load dataset with error " + err.Error()) } } else { ngramFreq, err = loadDataset(Dataset) if err != nil { return nil, errors.New("failed to load dataset with error " + err.Error()) } } tfidfScorer := TFIDFScoreFunction(ngramFreq, DefaultNgramLength, scoreLenThreshold, scoreLenPenalty, scoreRepPenalty) scorer := func(s string) (bool, error) { s = sanitize(s) if len(s) < MinLength { return false, errors.New("string to score is too short min length is 6") } score := tfidfScorer(s) result := score > MinScore return result, nil } return scorer, nil }
package main import "fmt" func main() { //unlike Java, you don't need a break statement -- //once a matching case is found, it will break switch signal := 1; signal { case 0: fmt.Println("reg") case 1: fmt.Println("orange") case 2: fmt.Println("green") } var score int = 63 switch { case score <= 25: fmt.Println("beginner") case score <= 75: fmt.Println("pro") default: fmt.Println("expert") } }
package odoo import ( "fmt" ) // FormatAddressMixin represents format.address.mixin model. type FormatAddressMixin struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` } // FormatAddressMixins represents array of format.address.mixin model. type FormatAddressMixins []FormatAddressMixin // FormatAddressMixinModel is the odoo model name. const FormatAddressMixinModel = "format.address.mixin" // Many2One convert FormatAddressMixin to *Many2One. func (fam *FormatAddressMixin) Many2One() *Many2One { return NewMany2One(fam.Id.Get(), "") } // CreateFormatAddressMixin creates a new format.address.mixin model and returns its id. func (c *Client) CreateFormatAddressMixin(fam *FormatAddressMixin) (int64, error) { ids, err := c.CreateFormatAddressMixins([]*FormatAddressMixin{fam}) if err != nil { return -1, err } if len(ids) == 0 { return -1, nil } return ids[0], nil } // CreateFormatAddressMixin creates a new format.address.mixin model and returns its id. func (c *Client) CreateFormatAddressMixins(fams []*FormatAddressMixin) ([]int64, error) { var vv []interface{} for _, v := range fams { vv = append(vv, v) } return c.Create(FormatAddressMixinModel, vv) } // UpdateFormatAddressMixin updates an existing format.address.mixin record. func (c *Client) UpdateFormatAddressMixin(fam *FormatAddressMixin) error { return c.UpdateFormatAddressMixins([]int64{fam.Id.Get()}, fam) } // UpdateFormatAddressMixins updates existing format.address.mixin records. // All records (represented by ids) will be updated by fam values. func (c *Client) UpdateFormatAddressMixins(ids []int64, fam *FormatAddressMixin) error { return c.Update(FormatAddressMixinModel, ids, fam) } // DeleteFormatAddressMixin deletes an existing format.address.mixin record. func (c *Client) DeleteFormatAddressMixin(id int64) error { return c.DeleteFormatAddressMixins([]int64{id}) } // DeleteFormatAddressMixins deletes existing format.address.mixin records. func (c *Client) DeleteFormatAddressMixins(ids []int64) error { return c.Delete(FormatAddressMixinModel, ids) } // GetFormatAddressMixin gets format.address.mixin existing record. func (c *Client) GetFormatAddressMixin(id int64) (*FormatAddressMixin, error) { fams, err := c.GetFormatAddressMixins([]int64{id}) if err != nil { return nil, err } if fams != nil && len(*fams) > 0 { return &((*fams)[0]), nil } return nil, fmt.Errorf("id %v of format.address.mixin not found", id) } // GetFormatAddressMixins gets format.address.mixin existing records. func (c *Client) GetFormatAddressMixins(ids []int64) (*FormatAddressMixins, error) { fams := &FormatAddressMixins{} if err := c.Read(FormatAddressMixinModel, ids, nil, fams); err != nil { return nil, err } return fams, nil } // FindFormatAddressMixin finds format.address.mixin record by querying it with criteria. func (c *Client) FindFormatAddressMixin(criteria *Criteria) (*FormatAddressMixin, error) { fams := &FormatAddressMixins{} if err := c.SearchRead(FormatAddressMixinModel, criteria, NewOptions().Limit(1), fams); err != nil { return nil, err } if fams != nil && len(*fams) > 0 { return &((*fams)[0]), nil } return nil, fmt.Errorf("format.address.mixin was not found with criteria %v", criteria) } // FindFormatAddressMixins finds format.address.mixin records by querying it // and filtering it with criteria and options. func (c *Client) FindFormatAddressMixins(criteria *Criteria, options *Options) (*FormatAddressMixins, error) { fams := &FormatAddressMixins{} if err := c.SearchRead(FormatAddressMixinModel, criteria, options, fams); err != nil { return nil, err } return fams, nil } // FindFormatAddressMixinIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindFormatAddressMixinIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(FormatAddressMixinModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindFormatAddressMixinId finds record id by querying it with criteria. func (c *Client) FindFormatAddressMixinId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(FormatAddressMixinModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("format.address.mixin was not found with criteria %v and options %v", criteria, options) }
package main import ( "errors" "log" "math/rand" "sort" "time" ) func randomArray(length int, maxInteger int) (randAry []int, err error) { if length == 0 || maxInteger == 0 { return randAry, errors.New("length or maxIntegr can not be zero") } rand.Seed(time.Now().UnixNano()) for i := 1; i < length; i++ { randAry = append(randAry, rand.Intn(maxInteger)) } return } func main() { executions := 10 assendingOrder := false for i := 1; i < executions; i++ { inputArray, err := randomArray(10, i*10) if err != nil { log.Printf("Failed with %v", err) return } log.Printf("Input : %v", inputArray) outputArray := sortByOrder(assendingOrder, inputArray) log.Printf("Ouput : %v", outputArray) } } func sortByOrder(assendingOrder bool, ints []int) []int { if assendingOrder { sort.Slice(ints, func(i, j int) bool { return ints[i] < ints[j] }) return ints } sort.Slice(ints, func(i, j int) bool { return ints[i] > ints[j] }) return ints }
package main import ( "flag" "log" "github.com/benbjohnson/megajson/generator" ) func init() { log.SetFlags(0) } func main() { flag.Parse() if flag.NArg() == 0 { usage() } path := flag.Arg(0) g := generator.New() if err := g.Generate(path); err != nil { log.Fatalln(err) } } func usage() { log.Fatal("usage: megajson OPTIONS FILE") }
package model type TaggedData struct { Tag string `json:"tag"` }
// Package report outlines how reports are formatted and validated package report import ( "encoding/json" "github.com/UnityTech/nemesis/pkg/cis" "github.com/golang/glog" ) const ( // Failed indicates that a resource did not match expected spec Failed = "failed" // Passed indicates that a resource met the expected spec Passed = "passed" ) // Control is a measurable unit of an audit type Control struct { Title string `json:"title"` Desc string `json:"desc"` Status string `json:"status"` Error string `json:"error,omitempty"` } // NewControl returns a new Control with the given title func NewControl(title string, desc string) Control { return Control{ Title: title, Desc: desc, Status: Failed, } } // NewCISControl returns a new Control based on the CIS controls with a description func NewCISControl(recommendationID string, desc string) Control { rec, ok := cis.Registry[recommendationID] if !ok { glog.Fatalf("Couldn't find CIS recommendation with ID '%v'", recommendationID) } return Control{ Title: rec.Format(), Desc: desc, Status: Failed, } } // Passed changes the status of the control from `false` to `true`. func (c *Control) Passed() { c.Status = Passed } // Report is a top-level structure for capturing information generated from an audit on a resource type Report struct { Type string `json:"type"` Title string `json:"title"` Controls []Control `json:"controls"` Data json.RawMessage `json:"data"` } // NewReport returns a new top-level report with a given title func NewReport(typ string, title string) Report { return Report{ Type: typ, Title: title, Controls: []Control{}, } } // Status returns whether a report passed all the controls it was assigned. func (r *Report) Status() string { for _, c := range r.Controls { if c.Status == Failed { return Failed } } return Passed } // AddControls appends controls to the report. If we only report failures, then controls that pass are not included in the report func (r *Report) AddControls(controls ...Control) { for _, c := range controls { if c.Status == Passed && *flagReportOnlyFailures { continue } r.Controls = append(r.Controls, c) } }
package config import ( "encoding/json" "errors" "testing" "github.com/prebid/go-gdpr/consentconstants" "github.com/prebid/prebid-server/openrtb_ext" "github.com/stretchr/testify/assert" ) func TestAccountGDPREnabledForChannelType(t *testing.T) { trueValue, falseValue := true, false tests := []struct { description string giveChannelType ChannelType giveGDPREnabled *bool giveWebGDPREnabled *bool giveWebGDPREnabledForIntegration *bool wantEnabled *bool }{ { description: "GDPR Web channel enabled, general GDPR disabled", giveChannelType: ChannelWeb, giveGDPREnabled: &falseValue, giveWebGDPREnabled: &trueValue, giveWebGDPREnabledForIntegration: nil, wantEnabled: &trueValue, }, { description: "GDPR Web channel disabled, general GDPR enabled", giveChannelType: ChannelWeb, giveGDPREnabled: &trueValue, giveWebGDPREnabled: &falseValue, giveWebGDPREnabledForIntegration: nil, wantEnabled: &falseValue, }, { description: "GDPR Web channel unspecified, general GDPR disabled", giveChannelType: ChannelWeb, giveGDPREnabled: &falseValue, giveWebGDPREnabled: nil, giveWebGDPREnabledForIntegration: nil, wantEnabled: &falseValue, }, { description: "GDPR Web channel unspecified, general GDPR enabled", giveChannelType: ChannelWeb, giveGDPREnabled: &trueValue, giveWebGDPREnabled: nil, giveWebGDPREnabledForIntegration: nil, wantEnabled: &trueValue, }, { description: "GDPR Web channel unspecified, general GDPR unspecified", giveChannelType: ChannelWeb, giveGDPREnabled: nil, giveWebGDPREnabled: nil, giveWebGDPREnabledForIntegration: nil, wantEnabled: nil, }, { description: "Inegration Enabled is set, and channel enabled isn't", giveChannelType: ChannelWeb, giveGDPREnabled: &falseValue, giveWebGDPREnabled: nil, giveWebGDPREnabledForIntegration: &trueValue, wantEnabled: &trueValue, }, { description: "Inegration Enabled is set, and channel enabled is set, channel should have precedence", giveChannelType: ChannelWeb, giveGDPREnabled: &falseValue, giveWebGDPREnabled: &trueValue, giveWebGDPREnabledForIntegration: &falseValue, wantEnabled: &trueValue, }, } for _, tt := range tests { account := Account{ GDPR: AccountGDPR{ Enabled: tt.giveGDPREnabled, ChannelEnabled: AccountChannel{ Web: tt.giveWebGDPREnabled, }, IntegrationEnabled: AccountChannel{ Web: tt.giveWebGDPREnabledForIntegration, }, }, } enabled := account.GDPR.EnabledForChannelType(tt.giveChannelType) if tt.wantEnabled == nil { assert.Nil(t, enabled, tt.description) } else { assert.NotNil(t, enabled, tt.description) assert.Equal(t, *tt.wantEnabled, *enabled, tt.description) } } } func TestAccountCCPAEnabledForChannelType(t *testing.T) { trueValue, falseValue := true, false tests := []struct { description string giveChannelType ChannelType giveCCPAEnabled *bool giveWebCCPAEnabled *bool giveWebCCPAEnabledForIntegration *bool wantEnabled *bool }{ { description: "CCPA Web channel enabled, general CCPA disabled", giveChannelType: ChannelWeb, giveCCPAEnabled: &falseValue, giveWebCCPAEnabled: &trueValue, giveWebCCPAEnabledForIntegration: nil, wantEnabled: &trueValue, }, { description: "CCPA Web channel disabled, general CCPA enabled", giveChannelType: ChannelWeb, giveCCPAEnabled: &trueValue, giveWebCCPAEnabled: &falseValue, giveWebCCPAEnabledForIntegration: nil, wantEnabled: &falseValue, }, { description: "CCPA Web channel unspecified, general CCPA disabled", giveChannelType: ChannelWeb, giveCCPAEnabled: &falseValue, giveWebCCPAEnabled: nil, giveWebCCPAEnabledForIntegration: nil, wantEnabled: &falseValue, }, { description: "CCPA Web channel unspecified, general CCPA enabled", giveChannelType: ChannelWeb, giveCCPAEnabled: &trueValue, giveWebCCPAEnabled: nil, giveWebCCPAEnabledForIntegration: nil, wantEnabled: &trueValue, }, { description: "CCPA Web channel unspecified, general CCPA unspecified", giveChannelType: ChannelWeb, giveCCPAEnabled: nil, giveWebCCPAEnabled: nil, giveWebCCPAEnabledForIntegration: nil, wantEnabled: nil, }, { description: "Inegration Enabled is set, and channel enabled isn't", giveChannelType: ChannelWeb, giveCCPAEnabled: &falseValue, giveWebCCPAEnabled: nil, giveWebCCPAEnabledForIntegration: &trueValue, wantEnabled: &trueValue, }, { description: "Inegration Enabled is set, and channel enabled is set, channel should have precedence", giveChannelType: ChannelWeb, giveCCPAEnabled: &falseValue, giveWebCCPAEnabled: &trueValue, giveWebCCPAEnabledForIntegration: &falseValue, wantEnabled: &trueValue, }, } for _, tt := range tests { account := Account{ CCPA: AccountCCPA{ Enabled: tt.giveCCPAEnabled, ChannelEnabled: AccountChannel{ Web: tt.giveWebCCPAEnabled, }, IntegrationEnabled: AccountChannel{ Web: tt.giveWebCCPAEnabledForIntegration, }, }, } enabled := account.CCPA.EnabledForChannelType(tt.giveChannelType) if tt.wantEnabled == nil { assert.Nil(t, enabled, tt.description) } else { assert.NotNil(t, enabled, tt.description) assert.Equal(t, *tt.wantEnabled, *enabled, tt.description) } } } func TestAccountChannelGetByChannelType(t *testing.T) { trueValue, falseValue := true, false tests := []struct { description string giveAMPEnabled *bool giveAppEnabled *bool giveVideoEnabled *bool giveWebEnabled *bool giveChannelType ChannelType wantEnabled *bool }{ { description: "AMP channel setting unspecified, returns nil", giveChannelType: ChannelAMP, wantEnabled: nil, }, { description: "AMP channel disabled, returns false", giveAMPEnabled: &falseValue, giveChannelType: ChannelAMP, wantEnabled: &falseValue, }, { description: "AMP channel enabled, returns true", giveAMPEnabled: &trueValue, giveChannelType: ChannelAMP, wantEnabled: &trueValue, }, { description: "App channel setting unspecified, returns nil", giveChannelType: ChannelApp, wantEnabled: nil, }, { description: "App channel disabled, returns false", giveAppEnabled: &falseValue, giveChannelType: ChannelApp, wantEnabled: &falseValue, }, { description: "App channel enabled, returns true", giveAppEnabled: &trueValue, giveChannelType: ChannelApp, wantEnabled: &trueValue, }, { description: "Video channel setting unspecified, returns nil", giveChannelType: ChannelVideo, wantEnabled: nil, }, { description: "Video channel disabled, returns false", giveVideoEnabled: &falseValue, giveChannelType: ChannelVideo, wantEnabled: &falseValue, }, { description: "Video channel enabled, returns true", giveVideoEnabled: &trueValue, giveChannelType: ChannelVideo, wantEnabled: &trueValue, }, { description: "Web channel setting unspecified, returns nil", giveChannelType: ChannelWeb, wantEnabled: nil, }, { description: "Web channel disabled, returns false", giveWebEnabled: &falseValue, giveChannelType: ChannelWeb, wantEnabled: &falseValue, }, { description: "Web channel enabled, returns true", giveWebEnabled: &trueValue, giveChannelType: ChannelWeb, wantEnabled: &trueValue, }, } for _, tt := range tests { accountChannel := AccountChannel{ AMP: tt.giveAMPEnabled, App: tt.giveAppEnabled, Video: tt.giveVideoEnabled, Web: tt.giveWebEnabled, } result := accountChannel.GetByChannelType(tt.giveChannelType) if tt.wantEnabled == nil { assert.Nil(t, result, tt.description) } else { assert.NotNil(t, result, tt.description) assert.Equal(t, *tt.wantEnabled, *result, tt.description) } } } func TestPurposeEnforced(t *testing.T) { True := true False := false tests := []struct { description string givePurposeConfigNil bool givePurpose1Enforced *bool givePurpose2Enforced *bool givePurpose consentconstants.Purpose wantEnforced bool wantEnforcedSet bool }{ { description: "Purpose config is nil", givePurposeConfigNil: true, givePurpose: 1, wantEnforced: true, wantEnforcedSet: false, }, { description: "Purpose 1 Enforced not set", givePurpose1Enforced: nil, givePurpose: 1, wantEnforced: true, wantEnforcedSet: false, }, { description: "Purpose 1 Enforced set to full enforcement", givePurpose1Enforced: &True, givePurpose: 1, wantEnforced: true, wantEnforcedSet: true, }, { description: "Purpose 1 Enforced set to no enforcement", givePurpose1Enforced: &False, givePurpose: 1, wantEnforced: false, wantEnforcedSet: true, }, { description: "Purpose 2 Enforced set to full enforcement", givePurpose2Enforced: &True, givePurpose: 2, wantEnforced: true, wantEnforcedSet: true, }, } for _, tt := range tests { accountGDPR := AccountGDPR{} if !tt.givePurposeConfigNil { accountGDPR.PurposeConfigs = map[consentconstants.Purpose]*AccountGDPRPurpose{ 1: { EnforcePurpose: tt.givePurpose1Enforced, }, 2: { EnforcePurpose: tt.givePurpose2Enforced, }, } } value, present := accountGDPR.PurposeEnforced(tt.givePurpose) assert.Equal(t, tt.wantEnforced, value, tt.description) assert.Equal(t, tt.wantEnforcedSet, present, tt.description) } } func TestPurposeEnforcementAlgo(t *testing.T) { tests := []struct { description string givePurposeConfigNil bool givePurpose1Algo TCF2EnforcementAlgo givePurpose2Algo TCF2EnforcementAlgo givePurpose consentconstants.Purpose wantAlgo TCF2EnforcementAlgo wantAlgoSet bool }{ { description: "Purpose config is nil", givePurposeConfigNil: true, givePurpose: 1, wantAlgo: TCF2UndefinedEnforcement, wantAlgoSet: false, }, { description: "Purpose 1 enforcement algo is undefined", givePurpose1Algo: TCF2UndefinedEnforcement, givePurpose: 1, wantAlgo: TCF2UndefinedEnforcement, wantAlgoSet: false, }, { description: "Purpose 1 enforcement algo set to basic", givePurpose1Algo: TCF2BasicEnforcement, givePurpose: 1, wantAlgo: TCF2BasicEnforcement, wantAlgoSet: true, }, { description: "Purpose 1 enforcement algo set to full", givePurpose1Algo: TCF2FullEnforcement, givePurpose: 1, wantAlgo: TCF2FullEnforcement, wantAlgoSet: true, }, { description: "Purpose 2 Enforcement algo set to basic", givePurpose2Algo: TCF2BasicEnforcement, givePurpose: 2, wantAlgo: TCF2BasicEnforcement, wantAlgoSet: true, }, } for _, tt := range tests { accountGDPR := AccountGDPR{} if !tt.givePurposeConfigNil { accountGDPR.PurposeConfigs = map[consentconstants.Purpose]*AccountGDPRPurpose{ 1: { EnforceAlgoID: tt.givePurpose1Algo, }, 2: { EnforceAlgoID: tt.givePurpose2Algo, }, } } value, present := accountGDPR.PurposeEnforcementAlgo(tt.givePurpose) assert.Equal(t, tt.wantAlgo, value, tt.description) assert.Equal(t, tt.wantAlgoSet, present, tt.description) } } func TestPurposeEnforcingVendors(t *testing.T) { tests := []struct { description string givePurposeConfigNil bool givePurpose1Enforcing *bool givePurpose2Enforcing *bool givePurpose consentconstants.Purpose wantEnforcing bool wantEnforcingSet bool }{ { description: "Purpose config is nil", givePurposeConfigNil: true, givePurpose: 1, wantEnforcing: true, wantEnforcingSet: false, }, { description: "Purpose 1 Enforcing not set", givePurpose1Enforcing: nil, givePurpose: 1, wantEnforcing: true, wantEnforcingSet: false, }, { description: "Purpose 1 Enforcing set to true", givePurpose1Enforcing: &[]bool{true}[0], givePurpose: 1, wantEnforcing: true, wantEnforcingSet: true, }, { description: "Purpose 1 Enforcing set to false", givePurpose1Enforcing: &[]bool{false}[0], givePurpose: 1, wantEnforcing: false, wantEnforcingSet: true, }, { description: "Purpose 2 Enforcing set to true", givePurpose2Enforcing: &[]bool{true}[0], givePurpose: 2, wantEnforcing: true, wantEnforcingSet: true, }, } for _, tt := range tests { accountGDPR := AccountGDPR{} if !tt.givePurposeConfigNil { accountGDPR.PurposeConfigs = map[consentconstants.Purpose]*AccountGDPRPurpose{ 1: { EnforceVendors: tt.givePurpose1Enforcing, }, 2: { EnforceVendors: tt.givePurpose2Enforcing, }, } } value, present := accountGDPR.PurposeEnforcingVendors(tt.givePurpose) assert.Equal(t, tt.wantEnforcing, value, tt.description) assert.Equal(t, tt.wantEnforcingSet, present, tt.description) } } func TestPurposeVendorExceptions(t *testing.T) { tests := []struct { description string givePurposeConfigNil bool givePurpose1ExceptionMap map[openrtb_ext.BidderName]struct{} givePurpose2ExceptionMap map[openrtb_ext.BidderName]struct{} givePurpose consentconstants.Purpose wantExceptionMap map[openrtb_ext.BidderName]struct{} wantExceptionMapSet bool }{ { description: "Purpose config is nil", givePurposeConfigNil: true, givePurpose: 1, // wantExceptionMap: map[openrtb_ext.BidderName]struct{}{}, wantExceptionMap: nil, wantExceptionMapSet: false, }, { description: "Nil - exception map not defined for purpose", givePurpose: 1, // wantExceptionMap: map[openrtb_ext.BidderName]struct{}{}, wantExceptionMap: nil, wantExceptionMapSet: false, }, { description: "Empty - exception map empty for purpose", givePurpose: 1, givePurpose1ExceptionMap: map[openrtb_ext.BidderName]struct{}{}, wantExceptionMap: map[openrtb_ext.BidderName]struct{}{}, wantExceptionMapSet: true, }, { description: "Nonempty - exception map with multiple entries for purpose", givePurpose: 1, givePurpose1ExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "index": {}}, wantExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "index": {}}, wantExceptionMapSet: true, }, { description: "Nonempty - exception map with multiple entries for different purpose", givePurpose: 2, givePurpose1ExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "index": {}}, givePurpose2ExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "openx": {}}, wantExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "openx": {}}, wantExceptionMapSet: true, }, } for _, tt := range tests { accountGDPR := AccountGDPR{} if !tt.givePurposeConfigNil { accountGDPR.PurposeConfigs = map[consentconstants.Purpose]*AccountGDPRPurpose{ 1: { VendorExceptionMap: tt.givePurpose1ExceptionMap, }, 2: { VendorExceptionMap: tt.givePurpose2ExceptionMap, }, } } value, present := accountGDPR.PurposeVendorExceptions(tt.givePurpose) assert.Equal(t, tt.wantExceptionMap, value, tt.description) assert.Equal(t, tt.wantExceptionMapSet, present, tt.description) } } func TestFeatureOneEnforced(t *testing.T) { tests := []struct { description string giveEnforce *bool wantEnforcedSet bool wantEnforced bool }{ { description: "Special feature 1 enforce not set", giveEnforce: nil, wantEnforcedSet: false, wantEnforced: true, }, { description: "Special feature 1 enforce set to true", giveEnforce: &[]bool{true}[0], wantEnforcedSet: true, wantEnforced: true, }, { description: "Special feature 1 enforce set to false", giveEnforce: &[]bool{false}[0], wantEnforcedSet: true, wantEnforced: false, }, } for _, tt := range tests { accountGDPR := AccountGDPR{ SpecialFeature1: AccountGDPRSpecialFeature{ Enforce: tt.giveEnforce, }, } value, present := accountGDPR.FeatureOneEnforced() assert.Equal(t, tt.wantEnforced, value, tt.description) assert.Equal(t, tt.wantEnforcedSet, present, tt.description) } } func TestFeatureOneVendorException(t *testing.T) { tests := []struct { description string giveExceptionMap map[openrtb_ext.BidderName]struct{} giveBidder openrtb_ext.BidderName wantVendorExceptionSet bool wantIsVendorException bool }{ { description: "Nil - exception map not defined", giveBidder: "appnexus", wantVendorExceptionSet: false, wantIsVendorException: false, }, { description: "Empty - exception map empty", giveExceptionMap: map[openrtb_ext.BidderName]struct{}{}, giveBidder: "appnexus", wantVendorExceptionSet: true, wantIsVendorException: false, }, { description: "One - bidder found in exception map containing one entry", giveExceptionMap: map[openrtb_ext.BidderName]struct{}{"appnexus": {}}, giveBidder: "appnexus", wantVendorExceptionSet: true, wantIsVendorException: true, }, { description: "Many - bidder found in exception map containing multiple entries", giveExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "index": {}}, giveBidder: "appnexus", wantVendorExceptionSet: true, wantIsVendorException: true, }, { description: "Many - bidder not found in exception map containing multiple entries", giveExceptionMap: map[openrtb_ext.BidderName]struct{}{"rubicon": {}, "appnexus": {}, "index": {}}, giveBidder: "openx", wantVendorExceptionSet: true, wantIsVendorException: false, }, } for _, tt := range tests { accountGDPR := AccountGDPR{ SpecialFeature1: AccountGDPRSpecialFeature{ VendorExceptionMap: tt.giveExceptionMap, }, } value, present := accountGDPR.FeatureOneVendorException(tt.giveBidder) assert.Equal(t, tt.wantIsVendorException, value, tt.description) assert.Equal(t, tt.wantVendorExceptionSet, present, tt.description) } } func TestPurposeOneTreatmentEnabled(t *testing.T) { tests := []struct { description string giveEnabled *bool wantEnabledSet bool wantEnabled bool }{ { description: "Purpose one treatment enabled not set", giveEnabled: nil, wantEnabledSet: false, wantEnabled: true, }, { description: "Purpose one treatment enabled set to true", giveEnabled: &[]bool{true}[0], wantEnabledSet: true, wantEnabled: true, }, { description: "Purpose one treatment enabled set to false", giveEnabled: &[]bool{false}[0], wantEnabledSet: true, wantEnabled: false, }, } for _, tt := range tests { accountGDPR := AccountGDPR{ PurposeOneTreatment: AccountGDPRPurposeOneTreatment{ Enabled: tt.giveEnabled, }, } value, present := accountGDPR.PurposeOneTreatmentEnabled() assert.Equal(t, tt.wantEnabled, value, tt.description) assert.Equal(t, tt.wantEnabledSet, present, tt.description) } } func TestPurposeOneTreatmentAccessAllowed(t *testing.T) { tests := []struct { description string giveAllowed *bool wantAllowedSet bool wantAllowed bool }{ { description: "Purpose one treatment access allowed not set", giveAllowed: nil, wantAllowedSet: false, wantAllowed: true, }, { description: "Purpose one treatment access allowed set to true", giveAllowed: &[]bool{true}[0], wantAllowedSet: true, wantAllowed: true, }, { description: "Purpose one treatment access allowed set to false", giveAllowed: &[]bool{false}[0], wantAllowedSet: true, wantAllowed: false, }, } for _, tt := range tests { accountGDPR := AccountGDPR{ PurposeOneTreatment: AccountGDPRPurposeOneTreatment{ AccessAllowed: tt.giveAllowed, }, } value, present := accountGDPR.PurposeOneTreatmentAccessAllowed() assert.Equal(t, tt.wantAllowed, value, tt.description) assert.Equal(t, tt.wantAllowedSet, present, tt.description) } } func TestModulesGetConfig(t *testing.T) { modules := AccountModules{ "acme": { "foo": json.RawMessage(`{"foo": "bar"}`), "foo.bar": json.RawMessage(`{"foo": "bar"}`), }, "acme.foo": { "baz": json.RawMessage(`{"foo": "bar"}`), }, } testCases := []struct { description string givenId string givenModules AccountModules expectedConfig json.RawMessage expectedError error }{ { description: "Returns module config if found by ID", givenId: "acme.foo", givenModules: modules, expectedConfig: json.RawMessage(`{"foo": "bar"}`), expectedError: nil, }, { description: "Returns module config if found by ID", givenId: "acme.foo.bar", givenModules: modules, expectedConfig: json.RawMessage(`{"foo": "bar"}`), expectedError: nil, }, { description: "Returns nil config if wrong ID provided", givenId: "invalid_id", givenModules: modules, expectedConfig: nil, expectedError: errors.New("ID must consist of vendor and module names separated by dot, got: invalid_id"), }, { description: "Returns nil config if no matching module exists", givenId: "acme.bar", givenModules: modules, expectedConfig: nil, expectedError: nil, }, { description: "Returns nil config if no matching module exists", givenId: "acme.foo.baz", givenModules: modules, expectedConfig: nil, expectedError: nil, }, { description: "Returns nil config if no module configs defined in account", givenId: "acme.foo", givenModules: nil, expectedConfig: nil, expectedError: nil, }, } for _, test := range testCases { t.Run(test.description, func(t *testing.T) { gotConfig, err := test.givenModules.ModuleConfig(test.givenId) assert.Equal(t, test.expectedError, err) assert.Equal(t, test.expectedConfig, gotConfig) }) } } func TestAccountChannelIsSet(t *testing.T) { trueBool := true falseBool := false testCases := []struct { name string givenAccountChannel *AccountChannel expected bool }{ { name: "AccountChannelSetAllFields", givenAccountChannel: &AccountChannel{AMP: &trueBool, App: &falseBool, Video: &falseBool, Web: &falseBool}, expected: true, }, { name: "AccountChannelNotSet", givenAccountChannel: &AccountChannel{}, expected: false, }, { name: "AccountChannelSetAmpOnly", givenAccountChannel: &AccountChannel{AMP: &trueBool}, expected: true, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.expected, test.givenAccountChannel.IsSet()) }) } } func TestAccountPriceFloorsValidate(t *testing.T) { tests := []struct { description string pf *AccountPriceFloors want []error }{ { description: "valid configuration", pf: &AccountPriceFloors{ EnforceFloorsRate: 100, MaxRule: 200, MaxSchemaDims: 10, }, }, { description: "Invalid configuration: EnforceFloorRate:110", pf: &AccountPriceFloors{ EnforceFloorsRate: 110, }, want: []error{errors.New("account_defaults.price_floors.enforce_floors_rate should be between 0 and 100")}, }, { description: "Invalid configuration: EnforceFloorRate:-10", pf: &AccountPriceFloors{ EnforceFloorsRate: -10, }, want: []error{errors.New("account_defaults.price_floors.enforce_floors_rate should be between 0 and 100")}, }, { description: "Invalid configuration: MaxRule:-20", pf: &AccountPriceFloors{ MaxRule: -20, }, want: []error{errors.New("account_defaults.price_floors.max_rules should be between 0 and 2147483647")}, }, { description: "Invalid configuration: MaxSchemaDims:100", pf: &AccountPriceFloors{ MaxSchemaDims: 100, }, want: []error{errors.New("account_defaults.price_floors.max_schema_dims should be between 0 and 20")}, }, } for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { var errs []error got := tt.pf.validate(errs) assert.ElementsMatch(t, got, tt.want) }) } }
package mediator import ( "context" ) type Pipeline struct { behaviours []BehaviorFunc pipeline PipelineFunc handlers map[string]RequestHandler } func New() *Pipeline { return &Pipeline{ handlers: make(map[string]RequestHandler), } } func (p *Pipeline) UseBehaviour(behaviour PipelineBehaviour) Builder { return p.Use(behaviour.Process) } func (p *Pipeline) Use(call func(context.Context, Message, NextFunc) (interface{}, error)) Builder { p.behaviours = append(p.behaviours, call) return p } func (p *Pipeline) RegisterHandler(req Message, h RequestHandler) Builder { key := req.Key() p.handlers[key] = h return p } func (p *Pipeline) Build() (*Mediator, error) { m := newMediator(*p) reverseApply(p.behaviours, m.pipe) return m, nil } func reverseApply(behaviours []BehaviorFunc, fn func(BehaviorFunc)) { for i := len(behaviours) - 1; i >= 0; i-- { fn(behaviours[i]) } }
package iotmaker_platform_IDraw import ( iotmakerPlatformTextMetrics "github.com/helmutkemper/iotmaker.santa_isabel_theater.platform.textMetrics" "github.com/helmutkemper/iotmaker.santa_isabel_theater.platform.webbrowser/browserMouse" "github.com/helmutkemper/iotmaker.santa_isabel_theater.platform.webbrowser/font" "github.com/helmutkemper/iotmaker.santa_isabel_theater.platform.webbrowser/javascript/canvas" "image/color" "time" ) // IDraw // en: Interface with drawing methods. Originally this interface was based on web // browsers canvas element. // documentation was based on w3school and https://developer.mozilla.org/ // // pt_br: Interface com os métodos de desenho. Originalmente esta interface teve como // base no elemento canvas do navegadores web. // Sua documentação foi baseada no w3school e o site https://developer.mozilla.org/ type IDraw interface { // BeginPath // en: Begins a path, or resets the current path // Tip: Use moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), and // arc(), to create paths. // Tip: Use the stroke() method to actually draw the path on the canvas. // // pt_br: Inicia ou reinicializa uma nova rota no desenho // Dica: Use moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), e // arc(), para criar uma nova rota no desenho // Dica: Use o método stroke() para desenhar a rota no elemento canvas BeginPath() // MoveTo // en: Moves the path to the specified point in the canvas, without creating a line // x: The x-coordinate of where to move the path to // y: The y-coordinate of where to move the path to // Tip: Use the stroke() method to actually draw the path on the canvas. // // pt_br: Move o caminho do desenho para o ponto dentro do elemento canvas, sem // inicializar uma linha // X: Coordenada x para onde o ponto vai ser deslocado // Y: Coordenada y para onde o ponto vai ser deslocado // Dica: Use o método stroke() para desenhar a rota no elemento canvas MoveTo(x, y interface{}) // ArcTo // en: Creates an arc/curve between two tangents // x0: The x-axis coordinate of the first control point. // y0: The y-axis coordinate of the first control point. // x1: The x-axis coordinate of the second control point. // y1: The y-axis coordinate of the second control point. // radius: The arc's radius. Must be non-negative. // // pt_br: Cria um arco/curva entre duas tangentes // x0: Eixo x da primeira coordenada de controle // y0: Eixo y da primeira coordenada de controle // x1: Eixo x da segunda coordenada de controle // y1: Eixo y da segunda coordenada de controle // // Example: // var c = document.getElementById("myCanvas"); // var ctx = c.getContext("2d"); // ctx.beginPath(); // ctx.moveTo(20, 20); // Create a starting point // ctx.lineTo(100, 20); // Create a horizontal line // ctx.arcTo(150, 20, 150, 70, 50); // Create an arc // ctx.lineTo(150, 120); // Continue with vertical line // ctx.stroke(); // Draw it ArcTo(x, y, radius, startAngle, endAngle interface{}) // LineTo // en: Adds a new point and creates a line from that point to the last specified // point in the canvas. (this method does not draw the line). // x: The x-coordinate of where to create the line to // y: The y-coordinate of where to create the line to // Tip: Use the stroke() method to actually draw the path on the canvas. // // pt_br: Adiciona um novo ponto e cria uma linha ligando o ponto ao último ponto // especificado no elemento canvas. (este método não desenha uma linha). // x: coordenada x para a criação da linha // y: coordenada y para a criação da linha // Dica: Use o método stroke() para desenhar a rota no elemento canvas LineTo(x, y interface{}) // ClosePath // en: Creates a path from the current point back to the starting point // Tip: Use the stroke() method to actually draw the path on the canvas. // Tip: Use the fill() method to fill the drawing (black is default). Use the // fillStyle property to fill with another color/gradient. // // pt_br: cria um caminho entre o último ponto especificado e o primeiro ponto // Dica: Use o método stroke() para desenhar a rota no elemento canvas // Dica: Use o método fill() para preencher o desenho (petro é a cor padrão). // Use a propriedade fillStyle para mudar a cor de preenchimento ou // adicionar um gradiente ClosePath(x, y interface{}) // Stroke // en: The stroke() method actually draws the path you have defined with all those // moveTo() and lineTo() methods. The default color is black. // Tip: Use the strokeStyle property to draw with another color/gradient. // // pt_br: O método stroke() desenha o caminho definido com os métodos moveTo() e // lineTo() usando a cor padrão, preta. // Dica: Use a propriedade strokeStyle para desenhar com outra cor ou usar um // gradiente Stroke() // SetLineWidth // en: Sets the current line width in pixels // Default value: 1 // JavaScript syntax: context.lineWidth = number; // // pt_br: Define a espessura da linha em pixels // Valor padrão: 1 // Sintaxe JavaScript: context.lineWidth = número // // Example: // var c = document.getElementById("myCanvas"); // var ctx = c.getContext("2d"); // ctx.lineWidth = 10; // ctx.strokeRect(20, 20, 80, 100); SetLineWidth(value interface{}) // GetLineWidth // en: Return the current line width in pixels // Default value: 1 // JavaScript syntax: var l = context.lineWidth; // // pt_br: Retorna a espessura da linha em pixels // Valor padrão: 1 // Sintaxe JavaScript: var l = context.lineWidth; // // Example: // var c = document.getElementById("myCanvas"); // var ctx = c.getContext("2d"); // ctx.lineWidth = 10; // ctx.strokeRect(20, 20, 80, 100); // var l = ctx.lineWidth; GetLineWidth() int // SetShadowBlur // en: Sets the blur level for shadows // Default value: 0 // // pt_br: Define o valor de borrão da sombra // Valor padrão: 0 SetShadowBlur(value interface{}) // GetShadowBlur // en: Return the blur level for shadows // Default value: 0 // // pt_br: Retorna o valor de borrão da sombra // Valor padrão: 0 GetShadowBlur() int // SetShadowColor // en: Sets the color to use for shadows // Note: Use the shadowColor property together with the shadowBlur property to // create a shadow. // Tip: Adjust the shadow by using the shadowOffsetX and shadowOffsetY // properties. // Default value: #000000 // // pt_br: Define a cor da sombra // Nota: Use a propriedade shadowColor em conjunto com a propriedade shadowBlur // para criar a sombra // Dica: Ajuste o local da sombra usando as propriedades shadowOffsetX e // shadowOffsetY // Valor padrão: #000000 SetShadowColor(value color.RGBA) // ShadowOffsetX // en: Sets the horizontal distance of the shadow from the shape // shadowOffsetX = 0 indicates that the shadow is right behind the shape. // shadowOffsetX = 20 indicates that the shadow starts 20 pixels to the right // (from the shape's left position). // shadowOffsetX = -20 indicates that the shadow starts 20 pixels to the left // (from the shape's left position). // Tip: To adjust the vertical distance of the shadow from the shape, use the // shadowOffsetY property. // Default value: 0 // // pt_br: Define a distância horizontal entre a forma e a sua sombra // shadowOffsetX = 0 indica que a forma e sua sombra estão alinhadas uma em // cima da outra. // shadowOffsetX = 20 indica que a forma e a sua sombra estão 20 pixels // afastadas a direita (em relação a parte mais a esquerda da forma) // shadowOffsetX = -20 indica que a forma e a sua sombra estão 20 pixels // afastadas a esquerda (em relação a parte mais a esquerda da forma) // Dica: Para ajustar a distância vertical, use a propriedade shadowOffsetY // Valor padrão: 0 ShadowOffsetX(value int) // ShadowOffsetY // en: Sets or returns the vertical distance of the shadow from the shape // The shadowOffsetY property sets or returns the vertical distance of the // shadow from the shape. // shadowOffsetY = 0 indicates that the shadow is right behind the shape. // shadowOffsetY = 20 indicates that the shadow starts 20 pixels below the // shape's top position. // shadowOffsetY = -20 indicates that the shadow starts 20 pixels above the // shape's top position. // Tip: To adjust the horizontal distance of the shadow from the shape, use the // shadowOffsetX property. // Default value: 0 // // pt_br: Define a distância vertical entre a forma e a sua sombra // shadowOffsetY = 0 indica que a forma e sua sombra estão alinhadas uma em // cima da outra. // shadowOffsetY = 20 indica que a forma e a sua sombra estão 20 pixels // afastadas para baixo (em relação a parte mais elevada da forma) // shadowOffsetY = -20 indica que a forma e a sua sombra estão 20 pixels // afastadas para cima (em relação a parte mais elevada da forma) // Dica: Para ajustar a distância horizontal, use a propriedade shadowOffsetX // Valor padrão: 0 ShadowOffsetY(value int) //AddColorStopPosition // en: Specifies the colors and stop positions in a gradient object // gradient: A gradient object created by CreateLinearGradient() or // CreateRadialGradient() methods // stopPosition: A value between 0.0 and 1.0 that represents the position // between start (0%) and end (100%) in a gradient // color: A color RGBA value to display at the stop position // // Note: You can call the addColorStopPosition() method multiple times to // change a gradient. If you omit this method for gradient objects, the // gradient will not be visible. You need to create at least one color stop to // have a visible gradient. // // pt_br: Especifica a cor e a posição final para a cor dentro do gradiente // gradient: Objeto de gradiente criado pelos métodos CreateLinearGradient() ou // CreateRadialGradient() // stopPosition: Um valor entre 0.0 e 1.0 que representa a posição entre o // início (0%) e o fim (100%) dentro do gradiente // color: Uma cor no formato RGBA para ser mostrada na posição determinada // // Nota: Você pode chamar o método AddColorStopPosition() várias vezes para // adicionar várias cores ao gradiente, porém, se você omitir o método, o // gradiente não será visivel. Você tem a obrigação de chamar o método pelo // menos uma vez com uma cor para que o gradiente seja visível. AddColorStopPosition(gradient interface{}, stop float64, color color.RGBA) // Fill // en: The fill() method fills the current drawing (path). The default color is // black. // Tip: Use the fillStyle property to fill with another color/gradient. // Note: If the path is not closed, the fill() method will add a line from the // last point to the start point of the path to close the path (like // closePath()), and then fill the path. // // pt_br: O método fill() preenche e pinta do desenho (caminho). A cor padrão é // preto. // Dica: Use a propriedade fillStyle para adicionar uma cor ou gradient. // Nota: Se o caminho não estiver fechado, o método fill() irá adicioná uma // linha do último ao primeiro ponto do caminho para fechar o caminho // (semelhante ao método closePath()) e só então irá pintar Fill() // CreateLinearGradient // en: This method of the Canvas 2D API creates a gradient along the line // connecting two given coordinates, starting at (x0, y0) point and ending at // (x1, y1) point // x0: The x-coordinate of the start point of the gradient // y0: The y-coordinate of the start point of the gradient // x1: The x-coordinate of the end point of the gradient // y1: The y-coordinate of the end point of the gradient // // The createLinearGradient() method creates a linear gradient object for be // used with methods AddColorStopPosition(), SetFillStyle() and // SetStrokeStyle(). // The gradient can be used to fill rectangles, circles, lines, text, etc. // Tip: Use this object as the value to the strokeStyle() or fillStyle() // methods // Tip: Use the addColorStopPosition() method to specify different colors, and // where to position the colors in the gradient object. // // pt_br: Este método do canvas 2D cria um gradiente ao longo de uma linha // conectando dois pontos, iniciando no ponto (x0, y0) e terminando no ponto // (x1, y1) // x0: Coordenada x do ponto inicial do gradiente // y0: Coordenada y do ponto inicial do gradiente // x1: Coordenada x do ponto final do gradiente // y1: Coordenada y do ponto final do gradiente // // O método CreateLinearGradient() cria um objeto de gradiente linear para ser // usado em conjunto com os métodos AddColorStopPosition(), SetFillStyle() e // SetStrokeStyle(). // O gradiente pode ser usado para preencher retângulos, circulos, linhas, // textos, etc. // Dica: Use este objeto como valor passados aos métodos strokeStyle() ou // fillStyle() // Dica: Use o método addColorStopPosition() para especificar diferentes cores // para o gradiente e a posição de cada cor CreateLinearGradient(x0, y0, x1, y1 interface{}) interface{} // CreateRadialGradient // en: Creates a radial gradient (to use on canvas content). The parameters // represent two circles, one with its center at (x0, y0) and a radius of r0, and // the other with its center at (x1, y1) with a radius of r1. // x0: The x-coordinate of the starting circle of the gradient // y0: The y-coordinate of the starting circle of the gradient // r0: The radius of the starting circle. Must be non-negative and finite. // (note: radius is a width, not a degrees angle) // x1: The x-coordinate of the ending circle of the gradient // y1: The y-coordinate of the ending circle of the gradient // r1: The radius of the ending circle. Must be non-negative and finite. // (note: radius is a width, not a degrees angle) // // pt_br: Este método cria um gradiente radial (para ser usado com o canvas 2D). Os // parâmetros representam dois círculos, um com o centro no ponto (x0, y0) e raio // r0, e outro com centro no ponto (x1, y1) com raio r1 // x0: Coordenada x do circulo inicial do gradiente // y0: Coordenada y do circulo inicial do gradiente // r0: Raio do círculo inicial. Deve ser um valor positivo e finito. (nota: o // raio é um comprimento e não um ângulo) // x1: Coordenada x do circulo final do gradiente // y1: Coordenada y do circulo final do gradiente // r1: Raio do círculo final. Deve ser um valor positivo e finito. (nota: o // raio é um comprimento e não um ângulo) CreateRadialGradient(x0, y0, r0, x1, y1, r1 interface{}) interface{} // SetFillStyle // en: Sets the color, gradient, or pattern used to fill the drawing // value: a valid JavaScript value or a color.RGBA{} struct // Default value: #000000 // // pt_br: Define a cor, gradiente ou padrão usado para preencher o desenho // value: um valor JavaScript valido ou um struct color.RGBA{} // Valor padrão: #000000 SetFillStyle(value interface{}) // SetStrokeStyle // en: Sets the color, gradient, or pattern used for strokes // value: a valid JavaScript value or a color.RGBA{} struct // Default value: #000000 // // pt_br: Define a cor, gradiente ou padrão usado para o contorno // value: um valor JavaScript valido ou um struct color.RGBA{} // Valor padrão: #000000 SetStrokeStyle(value interface{}) // en: Returns an ImageData map[x][y]color.RGBA that copies the pixel data for the // specified rectangle on a canvas // x: The x coordinate (in pixels) of the upper-left corner to start copy from // y: The y coordinate (in pixels) of the upper-left corner to start copy from // width: The width of the rectangular area you will copy // height: The height of the rectangular area you will copy // return: map[x(int)][y(int)]color.RGBA // Note: return x and y are NOT relative to the coordinate (0,0) on the // image, are relative to the coordinate (0,0) on the canvas // // Note: The ImageData object is not a picture, it specifies a part (rectangle) // on the canvas, and holds information of every pixel inside that rectangle. // // For every pixel in the map[x][y] there are four pieces of information, the // color.RGBA values: // R - The color red (from 0-255) // G - The color green (from 0-255) // B - The color blue (from 0-255) // A - The alpha channel (from 0-255; 0 is transparent and 255 is fully // visible) // // Tip: After you have manipulated the color/alpha information in the // map[x][y], you can copy the image data back onto the canvas with the // putImageData() method. // // pr_br: Retorna um mapa map[x][y]color.RGBA com parte dos dados da imagem contida // no retângulo especificado. // x: Coordenada x (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // y: Coordenada y (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // width: comprimento do retângulo a ser copiado // height: altura do retângulo a ser copiado // return: map[x(int)][y(int)]color.RGBA // Nota: x e y do retorno não são relativos a coordenada (0,0) da // imagem, são relativos a coordenada (0,0) do canvas // // Nota: Os dados da imagem não são uma figura, eles representam uma parte // retangular do canvas e guardam informações de cada pixel contido nessa área // // Para cada pixel contido no mapa há quatro peças de informação com valores no // formato de color.RGBA: // R - Cor vermelha (de 0-255) // G - Cor verde (de 0-255) // B - Cor azul (de 0-255) // A - Canal alpha (de 0-255; onde, 0 é transparente e 255 é totalmente // visível) // // Dica: Depois de manipular as informações de cor/alpha contidas no map[x][y], // elas podem ser colocadas de volta no canvas com o método putImageData(). GetImageData(x, y, width, height int) map[int]map[int]color.RGBA // GetImageDataJsValue // // English: // // Returns an ImageData js.Value that copies the pixel data for the specified rectangle on a canvas // // Input: // x: The x coordinate (in pixels) of the upper-left corner to start copy from // y: The y coordinate (in pixels) of the upper-left corner to start copy from // width: The width of the rectangular area you will copy // height: The height of the rectangular area you will copy // // Output: // data: js.Value // // Note: // * return x and y are NOT relative to the coordinate (0,0) on the image, are relative to the // coordinate (0,0) on the canvas; // * The ImageData object is not a picture, it specifies a part (rectangle) on the canvas, and // holds information of every pixel inside that rectangle. // // For every pixel in the map[x][y] there are four pieces of information, the color.RGBA values: // R - The color red (from 0-255) // G - The color green (from 0-255) // B - The color blue (from 0-255) // A - The alpha channel (from 0-255; 0 is transparent and 255 is fully visible) // // Tip: // * After you have manipulated the color/alpha information in the map[x][y], you can copy the image // data back onto the canvas with the putImageData() method. // // pr_br: Retorna um js.Value com parte dos dados da imagem contida no retângulo especificado. // // Entrada: // x: Coordenada x (em pixels) do canto superior esquerdo de onde os dados vão ser copiados; // y: Coordenada y (em pixels) do canto superior esquerdo de onde os dados vão ser copiados; // width: comprimento do retângulo a ser copiado; // height: altura do retângulo a ser copiado; // // Saída: // data: js.Value // // Nota: // * x e y do retorno não são relativos a coordenada (0,0) da imagem, são relativos a coordenada // (0,0) do canvas; // * Os dados da imagem não são uma figura, eles representam uma parte retangular do canvas e // guardam informações de cada pixel contido nessa área. // // Para cada pixel contido no mapa há quatro peças de informação com valores no formato de color.RGBA: // R - Cor vermelha (de 0-255) // G - Cor verde (de 0-255) // B - Cor azul (de 0-255) // A - Canal alpha (de 0-255; onde, 0 é transparente e 255 é totalmente visível) // // Dica: // * Depois de manipular as informações de cor/alpha contidas no map[x][y], elas podem ser // colocadas de volta no canvas com o método putImageData(). GetImageDataJsValue(x, y, width, height int) (data interface{}) // todo: documentation PutImageData(imgData interface{}, values ...int) // PutImageDataJsValue // // English: // // PutImageDataJsValue() method puts the image data (from a specified ImageData object) back onto the // canvas. // // Input: // imgData: specifies the ImageData object to put back onto the canvas; // x: the x-coordinate, in pixels, of the upper-left corner of where to place the image // on the canvas; // y: the y-coordinate, in pixels, of the upper-left corner of where to place the image // on the canvas; // dirtyX: optional. The x-coordinate, in pixels, of the upper-left corner of where to start // drawing the image. Default 0; // dirtyY: optional. The y-coordinate, in pixels, of the upper-left corner of where to start // drawing the image. Default 0; // dirtyWidth: optional. The width to use when drawing the image on the canvas; // Default: the width of the extracted image; // dirtyHeight: optional. The height to use when drawing the image on the canvas; // Default: the height of the extracted image. // // Tip: // * Read about the getImageDataJsValue() method that copies the pixel data for a specified // rectangle on a canvas; // * Read about the createImageJsValue() method that creates a new, blank ImageData object. // todo: português PutImageDataJsValue(data interface{}, values ...int) // todo: documentation GetImageDataAlphaChannelByCoordinate(data interface{}, x, y, width int) uint8 GetImageDataPixelByCoordinate(data interface{}, x, y, width int) color.RGBA //(x, y, width, height int) map[int]map[int]color.RGBA // GetImageDataAlphaChannelOnly // en: Returns an ImageData map[x][y]uint8 that copies the pixel alpha channel for // the specified rectangle on a canvas // x: The x coordinate (in pixels) of the upper-left corner to start copy from // y: The y coordinate (in pixels) of the upper-left corner to start copy from // width: The width of the rectangular area you will copy // height: The height of the rectangular area you will copy // return: map[x(int)][y(int)]uint8 // Note: return x and y are NOT relative to the coordinate (0,0) on the // image, are relative to the coordinate (0,0) on the canvas // // Note: The ImageData object is not a picture, it specifies a part (rectangle) // on the canvas, and holds information only for alpha channel of every pixel // inside that rectangle. // // For every pixel in the map[x][y] there are one piece of information, the // alpha channel uint8 value (from 0-255; 0 is transparent and 255 is fully // visible) // // Tip: After you have manipulated the color/alpha information in the // map[x][y], you can copy the image data back onto the canvas with the // putImageData() method. // // pr_br: Retorna um mapa map[x][y]uint8 com parte dos dados da imagem contida // no retângulo especificado. // x: Coordenada x (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // y: Coordenada y (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // width: comprimento do retângulo a ser copiado // height: altura do retângulo a ser copiado // return: map[x(int)][y(int)]uint8 // Nota: x e y do retorno não são relativos a coordenada (0,0) da // imagem, são relativos a coordenada (0,0) do canvas // // Nota: Os dados da imagem não são uma figura, eles representam uma parte // retangular do canvas e guardam informações apenas do canal alpha de cada // pixel contido nessa área. // // Para cada pixel contido no mapa há apenas uma peça da informação do canal // alpha com valores no formato uint8, com valoes de 0-255; onde, 0 é // transparente e 255 é totalmente visível // // Dica: Depois de manipular as informações de cor/alpha contidas no map[x][y], // elas podem ser colocadas de volta no canvas com o método putImageData(). GetImageDataAlphaChannelOnly(x, y, width, height int) map[int]map[int]uint8 // GetImageDataCollisionByAlphaChannelValue // en: Returns an ImageData map[x][y]bool that copies the pixel alpha channel for // the specified rectangle on a canvas // x: The x coordinate (in pixels) of the upper-left corner to start copy from // y: The y coordinate (in pixels) of the upper-left corner to start copy from // width: The width of the rectangular area you will copy // height: The height of the rectangular area you will copy // minimumAcceptableValue: (alpha channel < minimumAcceptableValue) true:false // return: map[x(int)][y(int)]bool // Note: return x and y are NOT relative to the coordinate (0,0) on the // image, are relative to the coordinate (0,0) on the canvas // // Note: The ImageData object is not a picture, it specifies a part (rectangle) // on the canvas, and holds information only for alpha channel of every pixel // inside that rectangle. // // For every pixel in the map[x][y] there are one piece of information, the // alpha channel bool value, visible or invisible // // Tip: After you have manipulated the color/alpha information in the // map[x][y], you can copy the image data back onto the canvas with the // putImageData() method. // // pr_br: Retorna um mapa map[x][y]bool com parte dos dados da imagem contida // no retângulo especificado. // x: Coordenada x (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // y: Coordenada y (em pixels) do canto superior esquerdo de onde os dados vão // ser copiados // width: comprimento do retângulo a ser copiado // height: altura do retângulo a ser copiado // minimumAcceptableValue: (canal alpha < minimumAcceptableValue) true : false // return: map[x(int)][y(int)]bool // Nota: x e y do retorno não são relativos a coordenada (0,0) da // imagem, são relativos a coordenada (0,0) do canvas // // Nota: Os dados da imagem não são uma figura, eles representam uma parte // retangular do canvas e guardam informações booleanas apenas do canal alpha // de cada pixel contido nessa área. // // Para cada pixel contido no mapa há apenas uma peça da informação do canal // alpha com valores no formato bool, visível ou invisível. // // Dica: Depois de manipular as informações de cor/alpha contidas no map[x][y], // elas podem ser colocadas de volta no canvas com o método putImageData(). GetImageDataCollisionByAlphaChannelValue(x, y, width, height int, minimumAcceptableValue uint8) map[int]map[int]bool // ClearRect // en: Clears the specified pixels within a given rectangle // x: The x-coordinate of the upper-left corner of the rectangle to clear // y: The y-coordinate of the upper-left corner of the rectangle to clear // width: The width of the rectangle to clear, in pixels // height: The height of the rectangle to clear, in pixels // // pt_br: Limpa todos os pixels de um determinado retângulo // x: Coordenada x da parte superior esquerda do retângulo a ser limpo // y: Coordenada y da parte superior esquerda do retângulo a ser limpo // width: Comprimento do retângulo a ser limpo // height: Altura do retângulo a ser limpo // ClearRect(x, y, width, height interface{}) // FillRect // en: Draws a "filled" rectangle // x: The x-coordinate of the upper-left corner of the rectangle // y: The y-coordinate of the upper-left corner of the rectangle // width: The width of the rectangle, in pixels // height: The height of the rectangle, in pixels // // Tip: Use the fillStyle property to set a color, gradient, or pattern used to // fill the drawing. // // pt_br: Desenha um retângulo preenchido com "tinta" // x: Coordenada x da parte superior esquerda do retângulo // y: Coordenada y da parte superior esquerda do retângulo // width: Comprimento do retângulo // height: Altura do retângulo // // Dica: Use a propriedade fillStile() para determinar a cor, gradiente ou // padrão a ser usado no reenchimento. FillRect(x, y, width, height int) // DrawImage // en: Draws an image, canvas, or video onto the canvas // image: Specifies the image, canvas, or video element to use // sx: [optional] The x coordinate where to start clipping // sy: [optional] The y coordinate where to start clipping // sWidth: [optional] The width of the clipped image // sHeight: [optional] The height of the clipped image // x: The x coordinate where to place the image on the canvas // y: The y coordinate where to place the image on the canvas // width: [optional] The width of the image to use (stretch or reduce the // image) // height: [optional] The height of the image to use (stretch or reduce the // image) // // Position the image on the canvas: // Golang Syntax: platform.DrawImage(img, x, y) // // Position the image on the canvas, and specify width and height of the image: // Golang Syntax: platform.DrawImage(img, x, y, width, height) // // Clip the image and position the clipped part on the canvas: // Golang Syntax: platform.drawImage(img, sx, sy, sWidth, sHeight, x, y, width, // height) // // pt_br: Desenha uma imagem, canvas ou vídeo no elemento canvas // image: Especifica a imagem, canvas ou vídeo a ser usado // sx: [opcional] Coordenada x de onde o corte vai começar // sy: [opcional] Coordenada y de onde o corte vai começar // sWidth: [opcional] largura do corte // sHeight: [opcional] altura do corte // x: Coordenada x do canvas de onde o corte vai ser colocado // y: Coordenada y do canvas de onde o corte vai ser colocado // width: [opcional] Novo comprimento da imagem // height: [opcional] Nova largura da imagem // // Posiciona a imagem no canvas // Golang Sintaxe: platform.DrawImage(img, x, y) // // Posiciona a imagem no canvas e determina um novo tamanho da imagem final // Golang Sintaxe: platform.DrawImage(img, x, y, width, height) // // Corta um pedaço da imagem e determina uma nova posição e tamanho para a // imagem final // Golang Sintaxe: platform.drawImage(img, sx, sy, sWidth, sHeight, x, y, // width, height) DrawImage(image interface{}, value ...interface{}) // todo: descrição aqui DrawImageMultiplesSprites(image interface{}, spriteWidth, spriteHeight, spriteFirstElementIndex, spriteLastElementIndex int, spriteChangeInterval time.Duration, x, y, width, height, clearRectX, clearRectY, clearRectWidth, clearRectHeight, lifeCycleLimit, lifeCycleRepeatLimit int, lifeCycleRepeatInterval time.Duration) // FillText // en: Draws "filled" text on the canvas // text: Specifies the text that will be written on the canvas // x: The x coordinate where to start painting the text (relative to the // canvas) // y: The y coordinate where to start painting the text (relative to the // canvas) // maxWidth: [Optional] The maximum allowed width of the text, in pixels // // pt_br: Desenha um texto "preenchido" no elemento canvas // text: Especifica o texto a ser escrito // x: coordenada x do texto a ser escrito (relativo ao elemento canvas) // y: coordenada x do texto a ser escrito (relativo ao elemento canvas) // maxWidth: [Opcional] Comprimento máximo do texto em pixels FillText(text string, x, y int, maxWidth ...int) // StrokeText // en: Draws text on the canvas with no fill // text: Specifies the text that will be written on the canvas // x: The x coordinate where to start painting the text (relative to the // canvas) // y: The y coordinate where to start painting the text (relative to the // canvas) // maxWidth: [Optional] The maximum allowed width of the text, in pixels // // pt_br: Desenha um texto no elemento canvas sem preenchimento // text: Especifica o texto a ser escrito // x: coordenada x do texto a ser escrito (relativo ao elemento canvas) // y: coordenada x do texto a ser escrito (relativo ao elemento canvas) // maxWidth: [Opcional] Comprimento máximo do texto em pixels StrokeText(text string, x, y int, maxWidth ...int) // Font // en: Sets the current font properties for text content // // pt_br: Define as propriedades da fonte atual Font(font font.Font) // MeasureText // en: Returns a struct TextMetrics that contains the width of the specified text // text: The text to be measured // // pt_br: Retorna o struct TextMetrics com os dados de comprimento do texto // text: Texto a ser medido MeasureText(text string) iotmakerPlatformTextMetrics.TextMetrics ResetFillStyle() ResetStrokeStyle() ResetShadow() ResetLineWidth() SetMouseCursor(cursor browserMouse.CursorType) AddEventListener(eventType interface{}, mouseMoveEvt interface{}) SetPixel(x, y int, pixel interface{}) MakePixel(pixelColor color.RGBA) interface{} CreateImageData(width, height interface{}, pixelColor color.RGBA) interface{} //todo: documentation NewCanvasWith2DContext(document interface{}, id string, width, height int) (canvas *canvas.Canvas) GetContext() interface{} // Save // en: Saves the state of the current context // // pt_br: Salva o estado atual do contexto atual Save() // Restore // en: Returns previously saved path state and attributes // // pt_br: Restaura o contexto e atributos previamente salvos Restore() }
package main import ( "fmt" "github.com/summerKK/leetcode-Go/algs4/cmd/1.3" ) /** 1.3.6 下面这段代码对队列 q 进行了什么操作? Stack<String> stack = new Stack<String>(); while (!q.isEmpty()) stack.push(q.dequeue()); while (!stack.isEmpty()) q.enqueue(stack.pop()); */ func main() { S := &__3.MyStack{} S.Init(0) Q := &__3.MyQueue{} Q.Enqueue(1) Q.Enqueue(2) Q.Enqueue(3) Q.Enqueue(4) for !Q.IsEmpty() { S.Push(Q.Dequeue()) } for !S.IsEmpty() { Q.Enqueue(S.Pop()) } for !Q.IsEmpty() { fmt.Println(Q.Dequeue()) } }
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "gopkg.in/bblfsh/client-go.v1" "gopkg.in/bblfsh/sdk.v1/uast" ) var ( serverAddr string filename string language string out string ) func main() { flag.StringVar(&serverAddr, "addr", ":9432", "bblfsh server endpoint") flag.StringVar(&filename, "file", "", "file to parse") flag.StringVar(&language, "lang", "", "source code language") flag.StringVar(&out, "out", "", "output") flag.Parse() bblfshClient, err := bblfsh.NewBblfshClient(serverAddr) if err != nil { log.Fatal(err) } content, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) } res, err := bblfshClient.NewParseRequest().Language(language).Content(string(content)).Do() if err != nil { log.Fatal(err) } snippetNodes := map[string][]uint32{} iterateIdentifiers(res.UAST, snippetNodes) data, err := json.MarshalIndent(snippetNodes, "", "\t") if err != nil { log.Fatal(err) } if out != "" { if err := ioutil.WriteFile(out, data, 0755); err != nil { log.Fatal(err) } } else { fmt.Println(string(data)) } } func iterateIdentifiers(u *uast.Node, snippetNodes map[string][]uint32) { for _, role := range u.Roles { if role == uast.Identifier { if u.Token != "" && u.StartPosition != nil { snippetNodes[u.Token] = append(snippetNodes[u.Token], u.StartPosition.Line) } } } for _, child := range u.Children { iterateIdentifiers(child, snippetNodes) } }
package cmd import ( "github.com/fugue/fugue-client/client/families" "github.com/spf13/cobra" ) // NewDeleteFamilyCommand returns a command that deletes a family func NewDeleteFamilyCommand() *cobra.Command { cmd := &cobra.Command{ Use: "family [family_id]", Short: "Deletes a family", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { client, auth := getClient() params := families.NewDeleteFamilyParams() params.FamilyID = args[0] _, err := client.Families.DeleteFamily(params, auth) CheckErr(err) }, } return cmd } func init() { deleteCmd.AddCommand(NewDeleteFamilyCommand()) }
package install import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" platform "kolihub.io/koli/pkg/apis/core/v1alpha1" ) func init() { platform.PlatformRegisteredRoles = []platform.PlatformRole{ platform.RoleAttachAllow, platform.RoleAutoScaleAllow, platform.RoleExecAllow, platform.RolePortForwardAllow, platform.RoleAddonManagement, } platform.PlatformRegisteredResources = &platform.ResourceList{ v1.ResourcePods: resource.Quantity{}, v1.ResourceConfigMaps: resource.Quantity{}, v1.ResourceSecrets: resource.Quantity{}, // TODO: vfuture // api.ResourcePersistentVolumeClaims: resource.Quantity{}, // api.ResourceRequestsCPU: resource.Quantity{}, // api.ResourceRequestsMemory: resource.Quantity{}, // ResourceLimitsCPU: resource.Quantity{}, // ResourceLimitsMemory: resource.Quantity{}, // ResourceRequestsStorage: resource.Quantity{}, } }
package main import "fmt" // nested struct || embedded struct type shapeProps struct { x int y int } // struct is a way to describe the data and data types. type shape struct { boldBorders bool area int shapeProps shapeProps // only "shapeProps" reduces "shapeProps shapeProps" AKA shorthand like so: // shapeProps } func main() { circle := shape{boldBorders: true, area: 100, shapeProps: shapeProps{x: 1, y: 5}} circle.printing() } // receiver function: func (key shape) printing() { fmt.Println(key) }
package request // AddCompanyRequest ... type AddCompanyRequest struct { CompanyName string `json:"companyName" validate:"required"` Logo string `json:"logo"` Description string `json:"description" ` Website string `json:"website"` Established string `json:"established"` NoOfEmployees int64 `json:"noOfEmployees"` Strength string `json:"strength"` Weakness string `json:"weakness"` } // UpdateCompanyRequest ... type UpdateCompanyRequest struct { CompanyName string `json:"companyName" validate:"required"` Logo string `json:"logo"` Description string `json:"description" ` Website string `json:"website"` Established string `json:"established"` NoOfEmployees int64 `json:"noOfEmployees"` Strength string `json:"strength"` Weakness string `json:"weakness"` } // AddProductRequest ... type AddProductRequest struct { CompanyCode string ` json:"companyID" validate:"required"` ProductName string ` json:"name" validate:"required"` ProductImage string ` json:"image"` ProductDescription string ` json:"description"` TargetMarket string ` json:"targetMarket"` ProductCategory string ` json:"category" validate:"required"` Price int ` json:"price" validate:"required"` Variant string ` json:"variant" validate:"required"` Notes string ` json:"notes"` } // UpdateProductRequest ... type UpdateProductRequest struct { CompanyCode string ` json:"companyID"` ProductName string ` json:"name"` ProductImage string ` json:"image"` ProductDescription string ` json:"description"` TargetMarket string ` json:"targetMarket"` ProductCategory string ` json:"category"` Price int ` json:"price"` Variant string ` json:"variant"` Notes string ` json:"notes"` } // AddPromotionRequest ... type AddPromotionRequest struct { CompanyCode string ` json:"companyID" validate:"required"` PromoTitle string ` json:"title" validate:"required"` PromoImage string ` json:"image"` PromoType string ` json:"type" validate:"required"` DisplayLocation string ` json:"displayLocation"` PromoStart string ` json:"start" validate:"required"` PromoEnd string ` json:"end"` IndefiniteEndDate int64 ` json:"indefiniteEndDate"` PromoDetail string ` json:"detail"` } // // ObjectPromoTypeVM ... // type ObjectPromoTypeVM struct { // Label string ` json:"label"` // Value string ` json:"value"` // } // UpdatePromotionRequest ... type UpdatePromotionRequest struct { CompanyCode string ` json:"companyID"` PromoTitle string ` json:"title"` PromoImage string ` json:"image"` PromoType string ` json:"type"` DisplayLocation string ` json:"displayLocation"` PromoStart string ` json:"start"` PromoEnd string ` json:"end"` IndefiniteEndDate int64 ` json:"indefiniteEndDate"` PromoDetail string ` json:"detail"` } // AddCategoryRequest ... type AddCategoryRequest struct { CategoryName string ` json:"categoryName" validate:"required"` } // UpdateCategoryRequest ... type UpdateCategoryRequest struct { CompanyCode string ` json:"companyCode"` } // AddDownloadRequest ... type AddDownloadRequest struct { DownloadOn string ` json:"downloadOn"` Type string ` json:"type"` NumberOfProductOrPromotion int ` json:"numberOfProductOrPromotion"` Start string ` json:"start"` End string ` json:"end"` URLRef string ` json:"urlRef"` Result string ` json:"result"` } // UpdateDownloadRequest ... type UpdateDownloadRequest struct { DownloadOn string ` json:"downloadOn"` Type string ` json:"type"` NumberOfProductOrPromotion string ` json:"numberOfProductOrPromotion"` Start string ` json:"start"` End string ` json:"end"` URLRef string ` json:"urlRef"` Result string ` json:"result"` }
package openrtb_ext // ExtImpTriplelift defines the contract for bidrequest.imp[i].ext.prebid.bidder.triplelift type ExtImpTriplelift struct { InvCode string `json:"inventoryCode"` Floor *float64 `json:"floor"` }
package common import ( "strings" "os/exec" "runtime" "fmt" ) func runInWindows(cmd string) (string, error) { result, err := exec.Command("cmd", "/c", cmd).Output() if err != nil { return "", err } return strings.TrimSpace(string(result)), err } func RunCommand(cmd string) (string, error) { if runtime.GOOS == "windows" { return runInWindows(cmd) } else { return runInLinux(cmd) } } func runInLinux(cmd string) (string, error) { fmt.Println("Running Linux cmd:" + cmd) result, err := exec.Command("/bin/sh", "-c", cmd).Output() if err != nil { return "", err } return strings.TrimSpace(string(result)), err } //根据进程名判断进程是否运行 func CheckProRunning(serverName string) (bool, error) { a := `ps aux | awk '/` + serverName + `/ && !/awk/ {print $2}'` pid, err := RunCommand(a) if err != nil { return false, err } return pid != "", nil } //根据进程名称获取进程ID func GetPid(serverName string) (string, error) { a := `ps aux | awk '/` + serverName + `/ && !/awk/ {print $2}'` pid, err := RunCommand(a) return pid , err }
package leetcode_go import ( "sort" ) func subsets(nums []int) [][]int { sort.Ints(nums) res := [][]int{[]int{}} for _, num := range nums { toAdd := [][]int{} for _, set := range res { new := append(append([]int{}, set...), num) toAdd = append(toAdd, new) } res = append(res, toAdd...) } return res }
/* * Sieve of Eratosthenes in Go * * some minor optimization, see comments in sieve() * each number cost 1 bit in isprime memory * * fast enough * * some bit manipulation, time enclapsed, etc. * * * SideNote: * * if you want super fast prime generator, check out * http://cr.yp.to/primegen.html * which uses a different (more advanced algorithm): 'Sieve of Atkin' * ref: http://cr.yp.to/papers/primesieves.pdf * It's very very fast and uses much less memory */ package main import ( "math" "time" "fmt" ) var isprime, prime []uint32 func set(p []uint32, k uint32) { p[k/32] |= 1 << (k & 31) } func clear(p []uint32, k uint32) { p[k/32] &^= 1 << (k & 31) } func bit(p []uint32, k uint32) uint32 { return (p[k/32] >> (k & 31)) & 1 } func sieve(max uint32) int { isprime = make([]uint32, max/32+1) // init 0 f := float64(max) prime = make([]uint32, int(2*f/math.Log(f))) // init: // 2 is the only even prime; mark all odd is prime set(isprime, 2) prime[0] = 2 for i := uint32(3); i < max; i += 2 { set(isprime, i) } r := 1 limit := uint32(math.Ceil(math.Sqrt(f))) // try odds for i := uint32(3); i < max; i += 2 { if bit(isprime, i) == 1 { prime[r] = i r++ // un-optimized version might be like: // for j := i + i; j < max; j += i { ... } if i > limit { continue } for j := i * i; j < max; j += 2 * i { clear(isprime, j) } } } return r } func main() { t := time.Nanoseconds() n := uint32(1e8) fmt.Printf("primepi(%d): %d\n", n, sieve(n)) fmt.Printf("takes %.3f seconds\n", float64(time.Nanoseconds()-t)/1e9) }
// Copyright 2019 The Berglas 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 berglas import ( "context" "encoding/base64" "fmt" "net/http" "cloud.google.com/go/storage" "github.com/sirupsen/logrus" "google.golang.org/api/googleapi" kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" ) // encryptAndWrite is a low-level function for encrypting and writing data. func (c *Client) encryptAndWrite( ctx context.Context, bucket, object, key string, plaintext []byte, generation, metageneration int64) (*Secret, error) { logger := c.Logger().WithFields(logrus.Fields{ "bucket": bucket, "object": object, "key": key, "generation": generation, "metageneration": metageneration, }) logger.Debug("encryptAndWrite.start") defer logger.Debug("encryptAndWrite.finish") // Generate a unique DEK and encrypt the plaintext locally (useful for large // pieces of data). logger.Debug("generating envelope") dek, ciphertext, err := envelopeEncrypt(plaintext) if err != nil { return nil, fmt.Errorf("failed to perform envelope encryption: %w", err) } // Encrypt the plaintext using a KMS key logger.Debug("encrypting envelope") kmsResp, err := c.kmsClient.Encrypt(ctx, &kmspb.EncryptRequest{ Name: key, Plaintext: dek, AdditionalAuthenticatedData: []byte(object), }) if err != nil { return nil, fmt.Errorf("failed to encrypt secret: %w", err) } encDEK := kmsResp.Ciphertext // Build the storage object contents. Contents will be of the format: // // b64(kms_encrypted_dek):b64(dek_encrypted_plaintext) blob := fmt.Sprintf("%s:%s", base64.StdEncoding.EncodeToString(encDEK), base64.StdEncoding.EncodeToString(ciphertext)) // If generation and metageneration are 0, then we should only create the // object if it does not exist. Otherwise, we should only perform an update if // the metagenerations match. var conds storage.Conditions if generation == 0 || metageneration == 0 { conds = storage.Conditions{ DoesNotExist: true, } } else { conds = storage.Conditions{ GenerationMatch: generation, MetagenerationMatch: metageneration, } } // Create the writer iow := c.storageClient. Bucket(bucket). Object(object). If(conds). NewWriter(ctx) iow.ObjectAttrs.CacheControl = CacheControl iow.ChunkSize = ChunkSize if iow.Metadata == nil { iow.Metadata = make(map[string]string) } iow.Metadata[MetadataIDKey] = "1" iow.Metadata[MetadataKMSKey] = kmsKeyTrimVersion(key) // Write logger.WithField("metadata", iow.Metadata).Debug("writing object to storage") if _, err := iow.Write([]byte(blob)); err != nil { return nil, fmt.Errorf("failed to save encrypted ciphertext to storage: %w", err) } // Close and flush logger.Debug("finalizing writer") if err := iow.Close(); err != nil { logger.WithError(err).Error("failed to finalize writer") if terr, ok := err.(*googleapi.Error); ok { switch terr.Code { case http.StatusNotFound: return nil, fmt.Errorf("bucket does not exist") case http.StatusPreconditionFailed: if conds.DoesNotExist { return nil, errSecretAlreadyExists } return nil, errSecretModified } } return nil, fmt.Errorf("failed to write to bucket: %w", err) } return secretFromAttrs(bucket, iow.Attrs(), plaintext), nil }
package appErrors import ( "net/http" ) type ErrorResponse struct { Status int `json:"status"` Message string `json:"message"` Details interface{} `json:"details,omitempty"` } func (e ErrorResponse) Error() string { return e.Message } func (e ErrorResponse) StatusCode() int { return e.Status } func Unauthorized(message string) ErrorResponse { if message == "" { message = "You are not authenticated to perform the requested action." } return ErrorResponse{ Status: http.StatusUnauthorized, Message: message, } } func IncorrectCredentials(message string) ErrorResponse { if message == "" { message = "Incorrect credentials." } return ErrorResponse{ Status: http.StatusUnauthorized, Message: message, } } func NotFound(message string) ErrorResponse { if message == "" { message = "Resource not found." } return ErrorResponse{ Status: http.StatusNotFound, Message: message, } } func AccessDenied(message string) ErrorResponse { if message == "" { message = "Access denied." } return ErrorResponse{ Status: http.StatusUnauthorized, Message: message, } } func BadInput(message string) ErrorResponse { if message == "" { message = "Bad input." } return ErrorResponse{ Status: http.StatusBadRequest, Message: message, } } func AlreadyExists(message string) ErrorResponse { if message == "" { message = "Resource already exists." } return ErrorResponse{ Status: http.StatusBadRequest, Message: message, } } func InternalServerError(message string) ErrorResponse { if message == "" { message = "Internal Server Error" } return ErrorResponse{ Status: http.StatusInternalServerError, Message: message, } }
package scraper type Scraper interface { Name() string Scrape() error Categories() []Category Products() []Product Validate() error HomepageURL() string Currency() string } type Category struct { Name string `json:"name"` URL string `json:"url"` } type Product struct { Name string `json:"name"` Price float64 `json:"price"` Currency string `json:"currency"` Image string `json:"image"` CategoryURL string `json:"category_url"` Description string `json:"description"` Rating float64 `json:"rating"` Brand string `json:"brand"` URL string `json:"url"` }
package loglevel const ( NotSet LogLevel = 0 Trace LogLevel = 10 Debug LogLevel = 20 Info LogLevel = 30 Warning LogLevel = 40 Error LogLevel = 50 Fatal LogLevel = 60 System LogLevel = 100 ) type LogLevel int func (l LogLevel) String() string { var name string switch l { case NotSet: name = "NOTSET" case Trace: name = "TRACE" case Debug: name = "DEBUG" case Info: name = "INFO" case Warning: name = "WARNING" case Error: name = "ERROR" } return name } // GetPrefix return prefix for this log level func (l LogLevel) GetPrefix() string { switch l { case NotSet: return "[NOTSET] " case Trace: return "[TRACE] " case Debug: return "[DEBUG] " case Info: return "[INFO] " case Warning: return "[WARN] " case Error: return "[ERROR] " case Fatal: return "[FATAL] " case System: return "[SYS] " default: return "[NOTSET] " } } // ConvertStringToLogLevel convert input string to log level func ConvertStringToLogLevel(logLevel string) LogLevel { var level LogLevel switch logLevel { case "NOTSET": level = NotSet case "TRACE": level = Trace case "DEBUG": level = Debug case "INFO": level = Info case "WARNING": level = Warning case "ERROR": level = Error case "FATAL": level = Fatal } return level }
package openhab import ( "bytes" "fmt" "net/http" "strings" ) type OpenHabCommunicator struct{ } func (*OpenHabCommunicator) ListItems() (*[]Item, error){ c := NewClient("") req, err := http.NewRequest("GET", fmt.Sprintf("%s/items", c.BaseURL), nil) if err != nil { return nil, err } res := [] Item{} if err := c.sendRequest(req, &res); err != nil { return nil, err } return &res, nil } func GetItemStateWithDefault(itemName, defaultValue string) (string){ state, err := GetItemState(itemName) if err != nil { return defaultValue } return state } func GetItemState(itemName string) (string, error){ c := NewClient("") req, err := http.NewRequest("GET", fmt.Sprintf("%s/items/%s/state", c.BaseURL, itemName), nil) if err != nil { return "", err } res, err := c.sendPlainRequest(req) if err != nil { return "", err } return res, nil } func IsLightActive( itemName string ) bool{ state := GetLightState(itemName) if len(state) != 3 { return false } if state[2] == "0" { return false } else { return true } } func SetLightStates( itemNames []string, activate bool ){ if len(itemNames) == 0 { return } value := "0" if activate { value = "60" } for _, itemName := range itemNames { changeBrightness( itemName, value ) } } func changeBrightness(itemName string, value string) { c := NewClient("") req, err := http.NewRequest("POST", fmt.Sprintf("%s/items/%s", c.BaseURL, itemName), bytes.NewBufferString(fmt.Sprintf("30,60,%s", value))) if err != nil { return } c.sendPlainRequest(req) } func GetLightState( itemName string ) []string{ c := NewClient("") req, err := http.NewRequest("GET", fmt.Sprintf("%s/items/%s/state", c.BaseURL, itemName), nil) if err != nil { return []string{} } res, _ := c.sendPlainRequest(req) return strings.Split(res, ",") } func SetTemp( targetTemp, itemName string ){ c := NewClient("") req, err := http.NewRequest("POST", fmt.Sprintf("%s/items/%s_4_SetTemperature", c.BaseURL, itemName), bytes.NewBufferString(targetTemp)) if err != nil { return } c.sendPlainRequest(req) } func SetTemps( targetTemp string, itemNames []string){ if len(itemNames) == 0 { return } for _, itemName := range itemNames { SetTemp(targetTemp, itemName) } }
package memio import ( "io" "unicode/utf8" ) // String grants a string Read-Only methods. type String string // Read satisfies the io.Reader interface func (s *String) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } if len(*s) == 0 { return 0, io.EOF } n := copy(p, *s) *s = (*s)[n:] return n, nil } // WriteTo satisfies the io.WriterTo interface func (s *String) WriteTo(w io.Writer) (int64, error) { if len(*s) == 0 { return 0, io.EOF } n, err := io.WriteString(w, string(*s)) *s = (*s)[n:] return int64(n), err } // ReadByte satisfies the io.ByteReader interface func (s *String) ReadByte() (byte, error) { if len(*s) == 0 { return 0, io.EOF } b := (*s)[0] *s = (*s)[1:] return b, nil } // ReadRune satisfies the io.RuneReader interface func (s *String) ReadRune() (rune, int, error) { if len(*s) == 0 { return 0, 0, io.EOF } r, n := utf8.DecodeRuneInString(string(*s)) *s = (*s)[n:] return r, n, nil } // Peek reads the next n bytes without advancing the position func (s *String) Peek(n int) ([]byte, error) { if n > len(*s) { return []byte(*s), io.EOF } return []byte((*s)[:n]), nil } // Close satisfies the io.Closer interface func (s *String) Close() error { *s = "" return nil }
/* Let's conclude this section by writing one more program. This program will perform the same operations on each element of a slice and return the result. For example if we want to multiply all integers in a slice by 5 and return the output, it can be easily done using first class functions. These kind of functions which operate on every element of a collection are called map functions. I have provided the program below. It is self explanatory. */ package main import "fmt" func iMap(s []int, f func(int) int) []int { var r []int for _, v := range s { r = append(r, f(v)) } return r } func main() { a := []int{5, 6, 7, 8, 9} r := iMap(a, func(n int) int { return n * 5 }) fmt.Println(r) }
package lang import ( "testing" ) func TestPeekTokenIsNot(t *testing.T) { expectTokenToMatch := func(source string, tests ...tokType) { p := makeParser("", source) got := p.peekTokenIsNot(tests[0], tests[1:]...) if got != false { t.Errorf("Expected %t, got %t\n", false, got) } } expectTokenToNotMatch := func(source string, tests ...tokType) { p := makeParser("", source) got := p.peekTokenIsNot(tests[0], tests[1:]...) if got != true { t.Errorf("Expected %t, got %t\n", false, got) } } expectTokenToMatch("abc", tokIdent) expectTokenToMatch("abc", tokNumber, tokIdent) expectTokenToMatch("123", tokNumber, tokIdent) expectTokenToMatch("", tokEOF, tokError) expectTokenToMatch("#", tokEOF, tokError) expectTokenToNotMatch("abc", tokEOF, tokError) } func TestExpectNextToken(t *testing.T) { p := makeParser("", "foo 123") tok, err := p.expectNextToken(tokIdent, "expected an identifier") if err != nil { t.Errorf("Expected no error, got %s\n", err) } else if tok.Type != tokIdent { t.Errorf("Expected '%s', got '%s'\n", tokIdent, tok.Type) } p = makeParser("", "123 foo") tok, err = p.expectNextToken(tokIdent, "expected an identifier") exp := "(1:1) expected an identifier" if err != nil { if err.Error() != exp { t.Errorf("Expected '%s', got '%s'\n", exp, err) } } else if tok.Type != tokIdent { t.Errorf("Expected an error, got '%s'\n", tok.Type) } } func TestRegisterPrecedence(t *testing.T) { parser := makeParser("", "") parser.registerPrecedence(tokIdent, precSum) got := parser.precedenceTable[tokIdent] if got != precSum { t.Errorf("Expected %v, got %v\n", precSum, got) } } func TestRegisterPrefix(t *testing.T) { parser := makeParser("", "") parser.registerPrefix(tokIdent, parseIdent) if _, exists := parser.prefixParseFuncs[tokIdent]; exists == false { t.Error("Expected prefix parse function, got nothing") } } func TestRegisterPostfix(t *testing.T) { parser := makeParser("", "") parser.registerPostfix(tokPlus, parseInfix, precSum) if _, exists := parser.postfixParseFuncs[tokPlus]; exists == false { t.Error("Expected postfix parse function, got nothing") } level, exists := parser.precedenceTable[tokPlus] if (exists == false) || (level != precSum) { t.Errorf("Expected Plus precedence to be %v, got %v\n", precSum, level) } } func TestPeekPrecedence(t *testing.T) { parser := makeParser("", "+*") parser.registerPrecedence(tokPlus, precSum) level := parser.peekPrecedence() if level != precSum { t.Errorf("Expected Plus precedence to be %v, got %v\n", precSum, level) } parser.lexer.next() level = parser.peekPrecedence() if level != precLowest { t.Errorf("Expected Star precedence to be %v, got %v\n", precLowest, level) } } func TestParse(t *testing.T) { prog, errs := ParseString("let a := 123; let b := 456;") var err error = nil if len(errs) > 0 { err = errs[0] } expectNoParserErrors(t, "(let a 123)\n(let b 456)", prog, err) expectStart(t, prog, 1, 1) } func TestParseProgram(t *testing.T) { p := makeParser("", "let a := 123; let b := 456;") loadGrammar(p) prog, err := parseProgram(p) expectNoParserErrors(t, "(let a 123)\n(let b 456)", prog, err) expectStart(t, prog, 1, 1) p = makeParser("", "") loadGrammar(p) prog, err = parseProgram(p) expectNoParserErrors(t, "", prog, err) expectStart(t, prog, 1, 1) p = makeParser("", `use "foo"; use "bar";`) loadGrammar(p) prog, err = parseProgram(p) expectNoParserErrors(t, "(use \"foo\")\n(use \"bar\")", prog, err) expectStart(t, prog, 1, 1) p = makeParser("", `pub let a := 123;`) loadGrammar(p) prog, err = parseProgram(p) expectNoParserErrors(t, "(pub (let a 123))", prog, err) expectStart(t, prog, 1, 1) p = makeParser("", "let a = 123; let b := 456;") loadGrammar(p) prog, err = parseProgram(p) expectParserError(t, "(1:7) expected :=", prog, err) } func TestParseStmt(t *testing.T) { expectStmt := func(source string, ast string, fn func(*parser) (Stmt, error)) { parser := makeParser("", source) loadGrammar(parser) stmt, err := fn(parser) expectNoParserErrors(t, ast, stmt, err) expectStart(t, stmt, 1, 1) } expectStmtError := func(source string, msg string, fn func(*parser) (Stmt, error)) { parser := makeParser("", source) loadGrammar(parser) stmt, err := fn(parser) expectParserError(t, msg, stmt, err) } expectStmt("if a { let a := 456; };", "(if a {\n (let a 456)})", parseGeneralStmt) expectStmt("let a := 123;", "(let a 123)", parseGeneralStmt) expectStmt("return 123;", "(return 123)", parseNonTopLevelStmt) expectStmtError("123 + 456", "(1:1) expected start of statement", parseStmt) expectStmtError("123 + 456", "(1:1) expected start of statement", parseTopLevelStmt) expectStmtError("123 + 456", "(1:1) expected start of statement", parseNonTopLevelStmt) expectStmtError("return 123;", "(1:1) return statements must be inside a function", parseTopLevelStmt) expectStmtError(`use 'foo';`, "(1:1) use statements must be outside any other statement", parseStmt) } func TestParseStmtBlock(t *testing.T) { expectStmtBlock := func(source string, ast string) { parser := makeParser("", source) loadGrammar(parser) block, err := parseStmtBlock(parser) expectNoParserErrors(t, ast, block, err) expectStart(t, block, 1, 1) } expectStmtBlockError := func(source string, msg string) { parser := makeParser("", source) loadGrammar(parser) block, err := parseStmtBlock(parser) expectParserError(t, msg, block, err) } expectStmtBlock("{ let a := 123; }", "{\n (let a 123)}") expectStmtBlockError("let a := 123; }", "(1:1) expected left brace") expectStmtBlockError("{ let a := 123 }", "(1:16) expected semicolon") expectStmtBlockError("{ let a := 123;", "(1:15) expected right brace") } func TestParseUseStmt(t *testing.T) { good := func(source string, ast string) { t.Helper() p := makeParser("", source) loadGrammar(p) stmt, err := parseUseStmt(p) expectNoParserErrors(t, ast, stmt, err) expectStart(t, stmt, 1, 1) } bad := func(source string, msg string) { t.Helper() p := makeParser("", source) loadGrammar(p) stmt, err := parseUseStmt(p) expectParserError(t, msg, stmt, err) } good(`use "foo";`, `(use "foo")`) good(`use "bar.plaid";`, `(use "bar.plaid")`) good(`use "foo" (a);`, `(use "foo" (a))`) good(`use "foo" (a, b);`, `(use "foo" (a b))`) good(`use "foo" (a, b,);`, `(use "foo" (a b))`) bad(`ues "foo";`, "(1:1) expected USE keyword") bad(`use 123;`, "(1:5) expected string literal") bad(`use "foo"`, "(1:9) expected semicolon") } func TestParseUseFilter(t *testing.T) { bad := func(source string, msg string) { t.Helper() p := makeParser("", source) loadGrammar(p) _, err := parseUseFilters(p) expectParserError(t, msg, nil, err) } bad(`a)`, `(1:1) expected left paren`) bad(`(`, `(1:1) expected right paren`) bad(`(123`, `(1:2) expected right paren`) bad(`(a b)`, `(1:4) expected right paren`) } func TestParsePubStmt(t *testing.T) { good := func(source string, ast string) { t.Helper() p := makeParser("", source) loadGrammar(p) stmt, err := parsePubStmt(p) expectNoParserErrors(t, ast, stmt, err) expectStart(t, stmt, 1, 1) } bad := func(source string, msg string) { t.Helper() p := makeParser("", source) loadGrammar(p) stmt, err := parsePubStmt(p) expectParserError(t, msg, stmt, err) } good(`pub let a := 123;`, `(pub (let a 123))`) good(`pub let x := "abc";`, `(pub (let x "abc"))`) bad(`pbu let a := 123;`, "(1:1) expected PUB keyword") bad(`pub a := 123;`, "(1:5) expected LET keyword") } func TestParseIfStmt(t *testing.T) { expectIf := func(source string, ast string) { p := makeParser("", source) loadGrammar(p) stmt, err := parseIfStmt(p) expectNoParserErrors(t, ast, stmt, err) expectStart(t, stmt, 1, 1) } expectIfError := func(source string, msg string) { p := makeParser("", source) loadGrammar(p) stmt, err := parseIfStmt(p) expectParserError(t, msg, stmt, err) } expectIf("if true {};", "(if true {})") expectIf("if true { let a := 123; };", "(if true {\n (let a 123)})") expectIfError("iff true { let a := 123; };", "(1:1) expected IF keyword") expectIfError("if let { let a := 123; };", "(1:4) unexpected symbol") expectIfError("if true { let a := 123 };", "(1:24) expected semicolon") expectIfError("if true { let a := 123; }", "(1:25) expected semicolon") } func TestParseDeclarationStmt(t *testing.T) { p := makeParser("", "let a := 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err := parseDeclarationStmt(p) expectNoParserErrors(t, "(let a 123)", stmt, err) expectStart(t, stmt, 1, 1) p = makeParser("", "a := 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseDeclarationStmt(p) expectParserError(t, "(1:1) expected LET keyword", stmt, err) p = makeParser("", "let 0 := 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseDeclarationStmt(p) expectParserError(t, "(1:5) expected identifier", stmt, err) p = makeParser("", "let a = 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseDeclarationStmt(p) expectParserError(t, "(1:7) expected :=", stmt, err) p = makeParser("", "let a :=;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseDeclarationStmt(p) expectParserError(t, "(1:9) unexpected symbol", stmt, err) p = makeParser("", "let a := 123") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseDeclarationStmt(p) expectParserError(t, "(1:12) expected semicolon", stmt, err) } func TestParseReturnStmt(t *testing.T) { p := makeParser("", "return;") stmt, err := parseReturnStmt(p) expectNoParserErrors(t, "(return)", stmt, err) expectStart(t, stmt, 1, 1) p = makeParser("", "return 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseReturnStmt(p) expectNoParserErrors(t, "(return 123)", stmt, err) p = makeParser("", "123;") stmt, err = parseReturnStmt(p) expectParserError(t, "(1:1) expected RETURN keyword", stmt, err) p = makeParser("", "return") stmt, err = parseReturnStmt(p) expectParserError(t, "(1:6) expected semicolon", stmt, err) p = makeParser("", "return let := 123;") p.registerPrefix(tokNumber, parseNumber) stmt, err = parseReturnStmt(p) expectParserError(t, "(1:8) unexpected symbol", stmt, err) } func TestParseExprStmt(t *testing.T) { p := makeParser("", "a := 123;") loadGrammar(p) stmt, err := parseExprStmt(p) expectNoParserErrors(t, "(= a 123)", stmt, err) expectStart(t, stmt, 1, 1) p = makeParser("", "callee(1, 2);") loadGrammar(p) stmt, err = parseExprStmt(p) expectNoParserErrors(t, "(callee (1 2))", stmt, err) expectStart(t, stmt, 1, 1) p = makeParser("", "a := 123") loadGrammar(p) stmt, err = parseExprStmt(p) expectParserError(t, "(1:8) expected semicolon", stmt, err) p = makeParser("", "let a := 123") loadGrammar(p) stmt, err = parseExprStmt(p) expectParserError(t, "(1:1) unexpected symbol", stmt, err) p = makeParser("", "2 + 2") loadGrammar(p) stmt, err = parseExprStmt(p) expectParserError(t, "(1:1) expected start of statement", stmt, err) } func TestParseTypeSig(t *testing.T) { expectTypeNote(t, parseTypeNote, "Int", "Int") expectTypeNote(t, parseTypeNote, "[Int]", "[Int]") expectTypeNote(t, parseTypeNote, "Int?", "Int?") expectTypeNote(t, parseTypeNote, "Int??", "Int??") expectTypeNote(t, parseTypeNote, "Int???", "Int???") expectTypeNote(t, parseTypeNote, "[Int?]", "[Int?]") expectTypeNote(t, parseTypeNote, "[Int?]?", "[Int?]?") expectTypeNote(t, parseTypeNote, "[Int]?", "[Int]?") expectTypeNote(t, parseTypeNote, "([Int]?, Bool)", "([Int]? Bool)") expectTypeNote(t, parseTypeNote, "() => [Int]?", "() => [Int]?") expectTypeNote(t, parseTypeNote, "() => Void", "() => Void") expectTypeNoteError(t, parseTypeNote, "[?]", "(1:2) unexpected symbol") expectTypeNoteError(t, parseTypeNote, `[@]`, "(1:2) unexpected symbol") expectTypeNoteError(t, parseTypeNote, "[Int", "(1:4) expected right bracket") expectTypeNoteError(t, parseTypeNote, "?", "(1:1) unexpected symbol") } func TestParseTypeIdent(t *testing.T) { expectTypeNote(t, parseTypeNoteIdent, "Int", "Int") expectTypeNote(t, parseTypeNoteIdent, "Any", "Any") expectTypeNoteError(t, parseTypeNoteIdent, "123", "(1:1) expected identifier") } func TestParseTypeList(t *testing.T) { expectTypeNote(t, parseTypeNoteList, "[Int]", "[Int]") expectTypeNoteError(t, parseTypeNoteList, "Int]", "(1:1) expected left bracket") expectTypeNoteError(t, parseTypeNoteList, "[?]", "(1:2) unexpected symbol") } func TestParseTypeOptional(t *testing.T) { expectTypeOpt := func(fn typeNoteParser, source string, ast string) { p := makeParser("", source) loadGrammar(p) sig, err := fn(p) expectNoParserErrors(t, sig.String(), sig, err) sig, err = parseTypeNoteOptional(p, sig) expectNoParserErrors(t, ast, sig, err) } expectTypeOptError := func(fn typeNoteParser, source string, msg string) { p := makeParser("", source) loadGrammar(p) sig, err := fn(p) expectNoParserErrors(t, sig.String(), sig, err) sig, err = parseTypeNoteOptional(p, sig) expectParserError(t, msg, sig, err) } expectTypeOpt(parseTypeNoteIdent, "Int?", "Int?") expectTypeOpt(parseTypeNoteList, "[Int]?", "[Int]?") expectTypeOptError(parseTypeNoteIdent, "Int", "(1:3) expected question mark") } func TestParseTypeTuple(t *testing.T) { expectTypeNote(t, parseTypeNoteTuple, "()", "()") expectTypeNote(t, parseTypeNoteTuple, "(Int)", "(Int)") expectTypeNote(t, parseTypeNoteTuple, "(Int, Int)", "(Int Int)") expectTypeNote(t, parseTypeNoteTuple, "(Int, Int,)", "(Int Int)") expectTypeNoteError(t, parseTypeNoteTuple, "Int)", "(1:1) expected left paren") expectTypeNoteError(t, parseTypeNoteTuple, "(123)", "(1:2) unexpected symbol") expectTypeNoteError(t, parseTypeNoteTuple, "(Int", "(1:4) expected right paren") } func TestParseTypeFunction(t *testing.T) { expectTypeNote(t, parseTypeNoteTuple, "()=>Nil", "() => Nil") expectTypeNote(t, parseTypeNoteTuple, "(a, b, c)=>[Int]", "(a b c) => [Int]") expectTypeNote(t, parseTypeNoteTuple, "(a, b, c,)=>[Int]", "(a b c) => [Int]") expectTypeNoteError(t, parseTypeNoteTuple, "() => 123", "(1:7) unexpected symbol") p := makeParser("", "= > Int") tuple := TypeNoteTuple{nop, []TypeNote{}} sig, err := parseTypeNoteFunction(p, tuple) expectParserError(t, "(1:1) expected arrow", sig, err) } func TestParseExpr(t *testing.T) { p := makeParser("", "+a") p.registerPrefix(tokPlus, parsePrefix) p.registerPrefix(tokIdent, parseIdent) expr, err := parseExpr(p, precLowest) expectNoParserErrors(t, "(+ a)", expr, err) p = makeParser("", "+") p.registerPrefix(tokPlus, parsePrefix) p.registerPrefix(tokIdent, parseIdent) expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:1) unexpected symbol", expr, err) p = makeParser("", "a + b + c") p.registerPostfix(tokPlus, parseInfix, precSum) p.registerPrefix(tokIdent, parseIdent) expr, err = parseExpr(p, precLowest) expectNoParserErrors(t, "(+ (+ a b) c)", expr, err) p = makeParser("", "a + b * c") p.registerPostfix(tokPlus, parseInfix, precSum) p.registerPostfix(tokStar, parseInfix, precProduct) p.registerPrefix(tokIdent, parseIdent) expr, err = parseExpr(p, precLowest) expectNoParserErrors(t, "(+ a (* b c))", expr, err) p = makeParser("", "a +") p.registerPostfix(tokPlus, parseInfix, precSum) p.registerPrefix(tokIdent, parseIdent) expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:3) unexpected symbol", expr, err) } func TestParseFunction(t *testing.T) { p := makeParser("", "fn ():Void {}") expr, err := parseFunction(p) expectNoParserErrors(t, "(fn ():Void {})", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "fn ():Void {}") expr, err = parseFunction(p) expectNoParserErrors(t, "(fn ():Void {})", expr, err) p = makeParser("", "fn ():Int {}") expr, err = parseFunction(p) expectNoParserErrors(t, "(fn ():Int {})", expr, err) p = makeParser("", "fn ():[Int?]? {}") expr, err = parseFunction(p) expectNoParserErrors(t, "(fn ():[Int?]? {})", expr, err) p = makeParser("", "fn (a:Int):Void { let x := 123; }") loadGrammar(p) expr, err = parseFunction(p) expectNoParserErrors(t, "(fn (a:Int):Void {\n (let x 123)})", expr, err) p = makeParser("", "func (a) { let x := 123; }") expr, err = parseFunction(p) expectParserError(t, "(1:1) expected FN keyword", expr, err) p = makeParser("", "fn (,) { let x := 123; }") expr, err = parseFunction(p) expectParserError(t, "(1:5) expected identifier", expr, err) p = makeParser("", "fn (): { let x := 123; }") expr, err = parseFunction(p) expectParserError(t, "(1:8) unexpected symbol", expr, err) p = makeParser("", "fn ():Void { let x = 123; }") expr, err = parseFunction(p) expectParserError(t, "(1:20) expected :=", expr, err) } func TestParseFunctionParams(t *testing.T) { expectParams := func(prog string, exp string) { p := makeParser("", prog) params, err := parseFunctionParams(p) if err != nil { t.Fatalf("Expected no errors, got '%s'\n", err) } got := "(" for _, param := range params { got += " " + param.String() } got += " )" if exp != got { t.Errorf("Expected %s, got %s\n", exp, got) } } expectParamError := func(prog string, msg string) { p := makeParser("", prog) params, err := parseFunctionParams(p) if err == nil { got := "(" for _, param := range params { got += " " + param.String() } got += " )" t.Errorf("Expected an error, got %s\n", got) } else if err.Error() != msg { t.Errorf("Expected '%s', got '%s'\n", msg, err) } } expectParams("()", "( )") expectParams("(a : Int)", "( a:Int )") expectParams("(a : Int,)", "( a:Int )") expectParams("(a : Int,b:Bool)", "( a:Int b:Bool )") expectParams("(a : Int, b:Bool)", "( a:Int b:Bool )") expectParams("(a : Int, b:Bool?)", "( a:Int b:Bool? )") expectParams("(a : [Int]?, b:Bool?)", "( a:[Int]? b:Bool? )") expectParamError("(,)", "(1:2) expected identifier") expectParamError("(123)", "(1:2) expected identifier") expectParamError("(a:Int,,)", "(1:8) expected identifier") expectParamError("(a)", "(1:3) expected colon between parameter name and type") expectParamError("a:Int)", "(1:1) expected left paren") expectParamError("(a:Int", "(1:6) expected right paren") } func TestParseFunctionParam(t *testing.T) { p := makeParser("", "a:Int") param, err := parseFunctionParam(p) expectNoParserErrors(t, "a:Int", param, err) expectStart(t, param, 1, 1) p = makeParser("", "0:Int") param, err = parseFunctionParam(p) expectParserError(t, "(1:1) expected identifier", param, err) p = makeParser("", "a:456") param, err = parseFunctionParam(p) expectParserError(t, "(1:3) unexpected symbol", param, err) } func TestParseFunctionReturnSig(t *testing.T) { p := makeParser("", ": Int") sig, err := parseFunctionReturnSig(p) expectNoParserErrors(t, "Int", sig, err) p = makeParser("", "Void") sig, err = parseFunctionReturnSig(p) expectParserError(t, "(1:1) expected colon between parameters and return type", sig, err) p = makeParser("", ": 456") sig, err = parseFunctionReturnSig(p) expectParserError(t, "(1:3) unexpected symbol", sig, err) } func TestParseInfix(t *testing.T) { parser := makeParser("", "a + b") parser.registerPostfix(tokPlus, parseInfix, precSum) parser.registerPrefix(tokIdent, parseIdent) var left Expr var expr Expr var err error if left, err = parseIdent(parser); err != nil { t.Fatalf("Expected no errors, got %v\n", err) } expr, err = parseInfix(parser, left) expectNoParserErrors(t, "(+ a b)", expr, err) expectStart(t, expr, 1, 1) parser = makeParser("", "a +") parser.registerPostfix(tokPlus, parseInfix, precSum) parser.registerPrefix(tokIdent, parseIdent) if left, err = parseIdent(parser); err != nil { t.Fatalf("Expected no errors, got %v\n", err) } expr, err = parseInfix(parser, left) expectParserError(t, "(1:3) unexpected symbol", expr, err) } func TestParseList(t *testing.T) { good := func(source string, exp string) { t.Helper() p := makeParser("", source) loadGrammar(p) expr, err := parseList(p) expectNoParserErrors(t, exp, expr, err) expectStart(t, expr, 1, 1) } bad := func(source string, exp string) { t.Helper() p := makeParser("", source) loadGrammar(p) expr, err := parseList(p) expectParserError(t, exp, expr, err) } good("[]", "[ ]") good("[a]", "[ a ]") good("[a,]", "[ a ]") good("[a,b]", "[ a b ]") good("[ a, b, c]", "[ a b c ]") bad("a, b]", "(1:1) expected left bracket") bad("[ let ]", "(1:3) unexpected symbol") bad("[a, b", "(1:5) expected right bracket") } func TestParseSubscript(t *testing.T) { p := makeParser("", "abc[0]") loadGrammar(p) ident, _ := parseIdent(p) expr, err := parseSubscript(p, ident) expectNoParserErrors(t, "abc[0]", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "abc]") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseSubscript(p, ident) expectParserError(t, "(1:4) expect left bracket", expr, err) p = makeParser("", "abc[]") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseSubscript(p, ident) expectParserError(t, "(1:5) expected index expression", expr, err) p = makeParser("", "abc[let]") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseSubscript(p, ident) expectParserError(t, "(1:5) unexpected symbol", expr, err) p = makeParser("", "abc[0") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseSubscript(p, ident) expectParserError(t, "(1:5) expect right bracket", expr, err) } func TestParseAccessExpr(t *testing.T) { good := func(source string, exp string) { t.Helper() p := makeParser("", source) loadGrammar(p) expr, err := parseExpr(p, precLowest) expectNoParserErrors(t, exp, expr, err) } bad := func(source string, msg string) { t.Helper() p := makeParser("", source) loadGrammar(p) left, _ := parseExpr(p, precDispatch) expr, err := parseAccess(p, left) expectParserError(t, msg, expr, err) } good("a.b", "(a).b") good("a.b.c", "((a).b).c") good("a + b.c", "(+ a (b).c)") good("a.b + c", "(+ (a).b c)") good("a.b(c)", "((a).b (c))") good("a(b).c", "((a (b))).c") good("a[b].c", "(a[b]).c") good("a.b[c]", "(a).b[c]") bad("a b", "(1:3) expect dot") bad("a.", "(1:2) unexpected symbol") } func TestParseDispatchExpr(t *testing.T) { p := makeParser("", "callee()") loadGrammar(p) ident, _ := parseIdent(p) expr, err := parseDispatch(p, ident) expectNoParserErrors(t, "(callee ())", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "callee(1, 2, 3)") loadGrammar(p) expr, err = parseExpr(p, precLowest) expectNoParserErrors(t, "(callee (1 2 3))", expr, err) p = makeParser("", "callee)") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseDispatch(p, ident) expectParserError(t, "(1:7) expected left paren", expr, err) p = makeParser("", "callee(let") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseDispatch(p, ident) expectParserError(t, "(1:8) unexpected symbol", expr, err) p = makeParser("", "callee(123") loadGrammar(p) ident, _ = parseIdent(p) expr, err = parseDispatch(p, ident) expectParserError(t, "(1:10) expected right paren", expr, err) } func TestParseAssignExpr(t *testing.T) { p := makeParser("", "a := 123") loadGrammar(p) expr, err := parseExpr(p, precLowest) expectNoParserErrors(t, "(= a 123)", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "foo() := 123") loadGrammar(p) expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:1) left hand must be an identifier", expr, err) p = makeParser("", "a :=") loadGrammar(p) expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:4) unexpected symbol", expr, err) } func TestParsePostfix(t *testing.T) { parser := makeParser("", "a+") parser.registerPostfix(tokPlus, parsePostfix, precPostfix) parser.registerPrefix(tokIdent, parseIdent) var left Expr var expr Expr var err error if left, err = parseIdent(parser); err != nil { t.Fatalf("Expected no errors, got %v\n", err) } expr, err = parsePostfix(parser, left) expectNoParserErrors(t, "(+ a)", expr, err) expectStart(t, expr, 1, 1) } func TestParsePrefix(t *testing.T) { parser := makeParser("", "+a") parser.registerPrefix(tokPlus, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err := parsePrefix(parser) expectNoParserErrors(t, "(+ a)", expr, err) expectStart(t, expr, 1, 1) parser = makeParser("", "+") parser.registerPrefix(tokPlus, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err = parsePrefix(parser) expectParserError(t, "(1:1) unexpected symbol", expr, err) } func TestParseGroup(t *testing.T) { parser := makeParser("", "(a)") parser.registerPrefix(tokParenL, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err := parseGroup(parser) expectNoParserErrors(t, "a", expr, err) expectStart(t, expr, 1, 2) parser = makeParser("", "a)") parser.registerPrefix(tokParenL, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err = parseGroup(parser) expectParserError(t, "(1:1) expected left paren", expr, err) parser = makeParser("", "(") parser.registerPrefix(tokParenL, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err = parseGroup(parser) expectParserError(t, "(1:1) unexpected symbol", expr, err) parser = makeParser("", "(a") parser.registerPrefix(tokParenL, parsePrefix) parser.registerPrefix(tokIdent, parseIdent) expr, err = parseGroup(parser) expectParserError(t, "(1:2) expected right paren", expr, err) } func TestParseSelf(t *testing.T) { parser := makeParser("", "self") expr, err := parseSelf(parser) expectNoParserErrors(t, "self", expr, err) expectStart(t, expr, 1, 1) parser = makeParser("", "selfx") expr, err = parseSelf(parser) expectParserError(t, "(1:1) expected self", expr, err) } func TestParseIdent(t *testing.T) { parser := makeParser("", "abc") expr, err := parseIdent(parser) expectNoParserErrors(t, "abc", expr, err) expectStart(t, expr, 1, 1) parser = makeParser("", "123") expr, err = parseIdent(parser) expectParserError(t, "(1:1) expected identifier", expr, err) } func TestParseNumber(t *testing.T) { parser := makeParser("", "123") expr, err := parseNumber(parser) expectNoParserErrors(t, "123", expr, err) expectStart(t, expr, 1, 1) parser = makeParser("", "abc") expr, err = parseNumber(parser) expectParserError(t, "(1:1) expected number literal", expr, err) loc := Loc{Line: 1, Col: 1} expr, err = evalNumber(parser, token{Type: tokNumber, Lexeme: "abc", Loc: loc}) expectParserError(t, "(1:1) malformed number literal", expr, err) } func TestParseString(t *testing.T) { p := makeParser("", `"foo"`) expr, err := parseString(p) expectNoParserErrors(t, `"foo"`, expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "123") expr, err = parseString(p) expectParserError(t, "(1:1) expected string literal", expr, err) p = makeParser("", "\"foo\n\"") expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:5) unclosed string", expr, err) p = makeParser("", "\"foo") expr, err = parseExpr(p, precLowest) expectParserError(t, "(1:4) unclosed string", expr, err) } func TestParseBoolean(t *testing.T) { p := makeParser("", "true") expr, err := parseBoolean(p) expectNoParserErrors(t, "true", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "false") expr, err = parseBoolean(p) expectNoParserErrors(t, "false", expr, err) expectStart(t, expr, 1, 1) p = makeParser("", "flase") expr, err = parseBoolean(p) expectParserError(t, "(1:1) expected boolean literal", expr, err) loc := Loc{Line: 1, Col: 1} expr, err = evalBoolean(p, token{Type: tokBoolean, Lexeme: "ture", Loc: loc}) expectParserError(t, "(1:1) malformed boolean literal", expr, err) } type typeNoteParser func(p *parser) (TypeNote, error) func expectTypeNote(t *testing.T, fn typeNoteParser, source string, ast string) { t.Helper() p := makeParser("", source) loadGrammar(p) sig, err := fn(p) expectNoParserErrors(t, ast, sig, err) expectStart(t, sig, 1, 1) } func expectTypeNoteError(t *testing.T, fn typeNoteParser, source string, msg string) { t.Helper() p := makeParser("", source) loadGrammar(p) sig, err := fn(p) expectParserError(t, msg, sig, err) } func expectNoParserErrors(t *testing.T, ast string, node ASTNode, err error) { t.Helper() if err != nil { t.Fatalf("Expected no errors, got '%s'\n", err) } else { expectAST(t, ast, node) } } func expectParserError(t *testing.T, msg string, node ASTNode, err error) { t.Helper() if err == nil { t.Errorf("Expected an error, got %s\n", node) } else if err.Error() != msg { t.Errorf("Expected '%s', got '%s'\n", msg, err) } } func expectAST(t *testing.T, ast string, got ASTNode) { t.Helper() if ast != got.String() { t.Errorf("Expected '%s', got '%s'\n", ast, got) } } func expectStart(t *testing.T, node ASTNode, line int, col int) { t.Helper() got := node.Start() exp := Loc{Line: line, Col: col} if exp.String() != got.String() { t.Errorf("Expected %s, got %s\n", exp, got) } }
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "path" ) type Builder struct { TopologyPath string EnvironmentPath string DeploymentPath string Topology Topology Environment Environment } func NewBuilder(topologyPath string, environmentPath string) *Builder { return &Builder{ TopologyPath: topologyPath, EnvironmentPath: environmentPath, } } func (b *Builder) LoadTopology() (topology *Topology, err error) { topologyContents, err := ioutil.ReadFile(b.TopologyPath) if err != nil { return nil, err } err = json.Unmarshal(topologyContents, &b.Topology) if err != nil { err = errors.New(fmt.Sprintf("Topology failed to unmarshal: %s", err)) return nil, err } return &b.Topology, nil } func (b *Builder) LoadEnvironment() (environment *Environment, err error) { environmentContents, err := ioutil.ReadFile(b.EnvironmentPath) if err != nil { return nil, err } err = json.Unmarshal(environmentContents, &b.Environment) if err != nil { err = errors.New(fmt.Sprintf("Environment failed to unmarshal: %s", err)) return nil, err } return &b.Environment, nil } func (b *Builder) Load() (err error) { _, err = b.LoadEnvironment() if err != nil { return nil } _, err = b.LoadTopology() return err } func (b *Builder) MakeBuilder(deploymentID string) (platformBuilder PlatformBuilder, err error) { var platform string deployment := b.Environment.Deployments[deploymentID] // check to make sure platform is the same across the nodes of the deployment for nodeIdx, _ := range deployment.Nodes { nodeId := deployment.Nodes[nodeIdx] node, nodeExists := b.Topology.Nodes[nodeId] if !nodeExists { errString := fmt.Sprintf("no node named %s as found in deployment %s", nodeId, deploymentID) return nil, errors.New(errString) } if platform != "" && node.Processor.Platform != platform { errString := fmt.Sprintf("mismatched platforms: %s vs %s for deployment id %s", platform, node.Processor.Platform, deploymentID) return nil, errors.New(errString) } else { platform = node.Processor.Platform } } switch platform { case "node.js": platformBuilder = &NodeJsPlatformBuilder{ DeploymentID: deploymentID, Deployment: deployment, Topology: b.Topology, Environment: b.Environment, } default: errString := fmt.Sprintf("unknown platform %s", platform) return nil, errors.New(errString) } return platformBuilder, nil } func (b *Builder) BuildDeployment(deploymentID string) (err error) { platformBuilder, err := b.MakeBuilder(deploymentID) if err != nil { return err } b.DeploymentPath = path.Join("build", b.Environment.Tier, deploymentID) err = os.Mkdir(b.DeploymentPath, 0755) if err != nil { return err } err = platformBuilder.BuildSource() if err != nil { return err } return nil } func (b *Builder) Build() error { _, err := b.LoadTopology() if err != nil { return err } _, err = b.LoadEnvironment() if err != nil { return err } // create build directory if it doesn't exist os.Mkdir("build", 0755) tierDir := path.Join("build", b.Environment.Tier) // if it exists, remove old build for this tier os.RemoveAll(tierDir) err = os.Mkdir(tierDir, 0755) if err != nil { return err } var deployAllScript string for deploymentID := range b.Environment.Deployments { err = b.BuildDeployment(deploymentID) if err != nil { return err } deployAllScript += fmt.Sprintf("cd %s && ./deploy-stage && cd ..\n", deploymentID) } ioutil.WriteFile(path.Join(tierDir, "deploy-all"), []byte(deployAllScript), 0755) return nil }
package mci import ( "database/sql" "fmt" "os" "path/filepath" "strings" "time" "github.com/bingoohuang/gonet" "github.com/bingoohuang/gou/pbe" "github.com/bingoohuang/sqlx" "github.com/jinzhu/gorm" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) func (s Settings) resetMySQCluster() error { s.currentHost = localhostIPv4 resetSqls := s.resetSlaveSqls() return s.execSqls(resetSqls) } func (s Settings) createMySQCluster() ([]MySQLNode, error) { nodes := s.createInitSqls() if err := s.fixMySQLConf(nodes); err != nil { return nodes, err } if !s.Debug { // 所有节点都做root向master1的root授权 if err := s.prepareCluster(nodes); err != nil { return nodes, err } } if IsLocalAddr(s.Master1Addr) && !s.Debug { if err := s.master1LocalProcess(nodes); err != nil { return nodes, err } } return nodes, nil } func (s Settings) master1LocalProcess(nodes []MySQLNode) error { backupServers := []string{s.Master2Addr} backupServers = append(backupServers, s.SlaveAddrs...) if err := s.backupTables(backupServers); err != nil { return err } if err := s.createClusters(nodes); err != nil { return err } if err := s.copyMaster1Data(backupServers); err != nil { return err } if err := s.resetMaster(nodes); err != nil { return err } return s.startSlaves(nodes) } func (s Settings) fixMySQLConf(nodes []MySQLNode) error { processed := 0 for _, node := range nodes { if !IsLocalAddr(node.Addr) { continue } processed++ if err := s.fixMySQLConfServerID(node.ServerID); err != nil { return err } if err := s.fixAutoIncrementOffset(node.AutoIncrementOffset); err != nil { return err } if err := s.fixServerUUID(); err != nil { return err } if err := ExecuteBash("MySQLRestartShell", s.MySQLRestartShell, 0); err != nil { return err } } if processed == 0 { logrus.Infof("CreateMySQLCluster bypassed, neither master nor slave for host %v", gonet.ListIps()) } return nil } func (s Settings) createClusters(nodes []MySQLNode) error { for _, node := range nodes { s.currentHost = node.Addr if err := s.execSqls(node.Sqls); err != nil { return err } } return nil } func (s Settings) startSlaves(nodes []MySQLNode) error { for _, node := range nodes { s.currentHost = node.Addr if err := s.execSqls([]string{"start slave"}); err != nil { return err } } return nil } func (s Settings) resetMaster(nodes []MySQLNode) error { for _, node := range nodes { s.currentHost = node.Addr if err := s.execSqls([]string{"reset master"}); err != nil { return err } } return nil } func (s Settings) backupTables(servers []string) error { for _, server := range servers { s.currentHost = server if _, err := s.renameTables(s.NoBackup); err != nil { return err } } return nil } func (s Settings) prepareCluster(nodes []MySQLNode) error { s.currentHost = localhostIPv4 return s.execSqls([]string{ fmt.Sprintf("SET GLOBAL server_id=%d", s.findLocalServerID(nodes)), "STOP SLAVE", "RESET SLAVE ALL", fmt.Sprintf(`DROP USER IF EXISTS '%s'@'%s'`, s.User, s.Master1Addr), fmt.Sprintf(`CREATE USER '%s'@'%s' IDENTIFIED BY '%s'`, s.User, s.Master1Addr, s.Password), fmt.Sprintf(`GRANT ALL PRIVILEGES ON *.* TO '%s'@'%s' WITH GRANT OPTION`, s.User, s.Master1Addr), // DROP USER IF EXISTS 'root'@'%'; CREATE USER 'root'@'%' IDENTIFIED BY 'C2D747DB89F6_a'; // GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; }) } func (s Settings) findLocalServerID(nodes []MySQLNode) int { for _, node := range nodes { if IsLocalAddr(node.Addr) { return node.ServerID } } return 0 } // MustOpenDB must open the db. // nolint:gomnd func (s Settings) MustOpenDB() *sql.DB { pwd, err := pbe.Ebp(s.Password) if err != nil { panic(err) } ds := "" host := s.currentHost net := "tcp" // 不是连接本机MySQL,设置net名称,指定IP出口 if IsLocalAddr(s.Master1Addr) && !IsLocalAddr(host) { net = "master1" } if gonet.IsIPv6(host) { ds = fmt.Sprintf("%s:%s@%s([%s]:%d)/", s.User, pwd, net, host, s.Port) } else { ds = fmt.Sprintf("%s:%s@%s(%s:%d)/", s.User, pwd, net, host, s.Port) } ds += `?` + s.MySQLDSNParams logrus.Infof("s.Master1Addr %s, host:%s, ds: %s", s.Master1Addr, ds, host) // 只有主1连接其他MySQL时,才设置 if IsLocalAddr(s.Master1Addr) { viper.Set("mysqlNet", "master1") viper.Set("bindAddress", s.Master1Addr) logrus.Infof("bindAddress %s", s.Master1Addr) } sqlMore := sqlx.NewSQLMore("mysql", ds) if !s.NoLog { logrus.Debugf("DSN: %s", sqlMore.EnhancedURI) } db := sqlMore.Open() db.SetMaxOpenConns(1) db.SetMaxIdleConns(1) db.SetConnMaxLifetime(60 * time.Second) return db } // MustOpenGormDB must open the db. func (s Settings) MustOpenGormDB() *gorm.DB { gdb, _ := gorm.Open("mysql", s.MustOpenDB()) return gdb } func (s Settings) renameTables(noBackup bool) (int, error) { db := s.MustOpenGormDB() defer db.Close() return RenameTables(db, noBackup) } func (s Settings) execSqls(sqls []string) error { if s.Debug { fmt.Print(strings.Join(sqls, ";\n")) return nil } db := s.MustOpenDB() defer db.Close() for _, sqlStr := range sqls { r := sqlx.ExecSQL(db, sqlStr, 0, "") if r.Error != nil { return fmt.Errorf("exec sql %s error %w", sqlStr, r.Error) } logrus.Infof("SQL:%s, %+v", sqlStr, r) } return nil } // MySQLNode means the information of MySQLNode in the cluster. type MySQLNode struct { Addr string AutoIncrementOffset int ServerID int Sqls []string } func (s Settings) createInitSqls() []MySQLNode { replPwd, err := pbe.Ebp(s.ReplPassword) if err != nil { panic(err) } m := make([]MySQLNode, 2+len(s.SlaveAddrs)) // nolint:gomnd const offset = 10000 // 0-4294967295, https://dev.mysql.com/doc/refman/5.7/en/replication-options.html m[0] = MySQLNode{ Addr: s.Master1Addr, AutoIncrementOffset: 1, ServerID: offset + 1, Sqls: s.initSlaveSqls(s.Master2Addr, replPwd), } m[1] = MySQLNode{ Addr: s.Master2Addr, AutoIncrementOffset: 2, ServerID: offset + 2, // nolint:gomnd Sqls: s.initSlaveSqls(s.Master1Addr, replPwd), } for seq, slaveAddr := range s.SlaveAddrs { m[2+seq] = MySQLNode{ Addr: slaveAddr, AutoIncrementOffset: seq + 3, ServerID: offset + seq + 3, // nolint:gomnd Sqls: s.initSlaveSqls(s.Master2Addr, replPwd), } } return m } const ( deleteUsers = "DELETE FROM mysql.user WHERE user='%s'" createUser = "CREATE USER '%s'@'%s' IDENTIFIED BY '%s'" grantSlave = "GRANT REPLICATION SLAVE ON *.* TO '%s'@'%s' IDENTIFIED BY '%s'" changeMaster = `CHANGE MASTER TO master_host='%s',master_port=%d,master_user='%s',` + `master_password='%s',master_auto_position=1` ) // https://dev.mysql.com/doc/refman/5.7/en/reset-slave.html // RESET SLAVE makes the slave forget its replication position in the master's binary log. // This statement is meant to be used for a clean start: It clears the master info // and relay log info repositories, deletes all the relay log files, // and starts a new relay log file. It also resets to 0 the replication delay specified // with the MASTER_DELAY option to CHANGE MASTER TO. // https://stackoverflow.com/a/32148683 // RESET SLAVE will leave behind master.info file with "default" values in such a way // that SHOW SLAVE STATUS will still give output. So if you have slave monitoring on this host, //after it becomes the master, you would still get alarms that are checking for 'Slave_IO_Running: Yes' // // RESET SLAVE ALL wipes slave info clean away, deleting master.info and // SHOW SLAVE STATUS will report "Empty Set (0.00)" func (s Settings) initSlaveSqls(masterTo, replPwd string) []string { sqls := []string{fmt.Sprintf(deleteUsers, s.ReplUsr), "FLUSH PRIVILEGES"} args := []interface{}{s.ReplUsr, "%", replPwd} sqls = append(sqls, fmt.Sprintf(createUser, args...), fmt.Sprintf(grantSlave, args...)) return append(sqls, fmt.Sprintf(changeMaster, masterTo, s.Port, s.ReplUsr, replPwd)) } func (s Settings) resetSlaveSqls() []string { return []string{ fmt.Sprintf(deleteUsers, s.ReplUsr), "STOP SLAVE", "RESET SLAVE ALL", fmt.Sprintf(`DROP USER IF EXISTS '%s'@'%s'`, s.User, s.Master1Addr), "FLUSH PRIVILEGES", } } func (s *Settings) fixServerUUID() error { if s.Debug { fmt.Println("fix fixServerUUID") return nil } if values, err := SearchFileContent(s.MySQLCnf, `(?i)datadir\s*=\s*(.+)`); err != nil { logrus.Warnf("SearchFileContent error: %v", err) return err } else if len(values) > 0 { autoCnf := filepath.Join(strings.TrimSpace(values[0]), "auto.cnf") logrus.Infof("remove auto.cnf %s", autoCnf) return os.Remove(autoCnf) } // nolint:goerr113 return fmt.Errorf("unable to find datadir in %s", s.MySQLCnf) } func (s Settings) fixMySQLConfServerID(serverID int) error { if s.Debug { fmt.Println("fix server-id =", serverID) return nil } if err := ReplaceFileContent(s.MySQLCnf, `(?i)server[-_]id\s*=\s*(\d+)`, fmt.Sprintf("%d", serverID)); err != nil { return fmt.Errorf("fixMySQLConfServerID %s error %w", s.MySQLCnf, err) } return nil } // fixAutoIncrementOffset fix auto_increment_offset. func (s Settings) fixAutoIncrementOffset(offset int) error { if s.Debug { fmt.Println("fix increment-offset =", offset) return nil } if err := ReplaceFileContent(s.MySQLCnf, `(?i)auto[-_]increment[-_]offset\s*=\s*(\d+)`, fmt.Sprintf("%d", offset)); err != nil { return fmt.Errorf("fixAutoIncrementOffset %s error %w", s.MySQLCnf, err) } return nil }
package main; import ( "os" "fmt" "path" "strings" "bpmerror" ) type LsCommand struct { BpmModuleName string } func (cmd *LsCommand) Name() string { return "ls" } func (cmd *LsCommand) IndentAndPrintTree(indentLevel int, mytext string){ text := "|" for i := 0; i < indentLevel; i++ { text = "| " + text; } fmt.Println(text + mytext) } func (cmd *LsCommand) IndentAndPrint(indentLevel int, mytext string){ text := " " for i := 0; i < indentLevel; i++ { text = " " + text; } fmt.Println(text + mytext) } func (cmd *LsCommand) PrintDependencies(bpm BpmData, indentLevel int) { // Sort the dependency keys so the dependencies always print in the same order sortedKeys := bpm.GetSortedKeys(); for _, itemName := range sortedKeys { item := bpm.Dependencies[itemName] if itemName == bpm.Name { fmt.Println("Warning: Ignoring self dependency for", itemName) continue } if item.Url == "" { fmt.Println("Error: No url specified for " + itemName) } if item.Commit == "" { fmt.Println("Error: No commit specified for " + itemName) } cmd.IndentAndPrintTree(indentLevel, "") workingPath,_ := os.Getwd(); itemPath := path.Join(Options.BpmCachePath, itemName) itemClonePath := path.Join(workingPath, itemPath, item.Commit) localPath := path.Join(Options.BpmCachePath, itemName, Options.LocalModuleName) if PathExists(localPath) { itemClonePath = localPath; cmd.IndentAndPrintTree(indentLevel, "--" + itemName + " @ [Local]") } else if !PathExists(itemClonePath) { cmd.IndentAndPrintTree(indentLevel, "--" + itemName + " @ " + item.Commit + " [MISSING]") continue } else { cmd.IndentAndPrintTree(indentLevel, "--" + itemName + " @ " + item.Commit + " [Installed]") } // Recursively get dependencies in the current dependency moduleBpm := BpmData{}; moduleBpmFilePath := path.Join(itemClonePath, Options.BpmFileName) err := moduleBpm.LoadFile(moduleBpmFilePath); if err != nil { cmd.IndentAndPrint(indentLevel, "Error: Could not load the bpm.json file for dependency " + itemName) continue } if strings.TrimSpace(moduleBpm.Name) == "" { msg := "Error: There must be a name field in the bpm.json for " + itemName cmd.IndentAndPrint(indentLevel, msg) continue } if strings.TrimSpace(moduleBpm.Version) == "" { msg := "Error: There must be a version field in the bpm for" + itemName cmd.IndentAndPrint(indentLevel, msg) continue } cmd.PrintDependencies(moduleBpm, indentLevel + 1) } return; } func (cmd *LsCommand) Execute() (error) { err := Options.DoesBpmFileExist(); if err != nil { return err; } bpm := BpmData{}; err = bpm.LoadFile(Options.BpmFileName); if err != nil { return bpmerror.New(err, "Error: There was a problem loading the bpm.json file") } if !bpm.HasDependencies() { fmt.Println("There are no dependencies. Done.") return nil; } fmt.Println("") fmt.Println(bpm.Name) cmd.PrintDependencies(bpm, 0) fmt.Println("") return nil; }
package endpoint import ( "github.com/gin-gonic/gin" "hospital-go/config" "hospital-go/model" "hospital-go/util" "net/http" ) type Auth struct { Email string `json:"email"` Password string `json:"password"` } func Login(c *gin.Context) { var json Auth if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // Record Not Found var user model.User if config.DB.First(&user, "email = ? ", json.Email).RecordNotFound() == true { c.JSON(http.StatusUnauthorized, gin.H{"message": "Email Not Found"}) return } isMatch := util.CheckPasswordHash(json.Password, user.Password) if isMatch != true { c.JSON(http.StatusUnauthorized, gin.H{"message": "Wrong Password"}) return } token, err := util.GenerateToken(json.Email, json.Password) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"token": token}) }
// Copyright (C) 2018 Satoshi Konno. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package echonet import ( "fmt" ) const ( DeviceOperatingStatus = ObjectOperatingStatus DeviceInstallationLocation = 0x81 DeviceStandardVersion = 0x82 DeviceIdentificationNumber = 0x83 DeviceMeasuredInstantaneousPowerConsumption = 0x84 DeviceMeasuredCumulativePowerConsumption = 0x85 DeviceManufacturerFaultCode = 0x86 DeviceCurrentLimitSetting = 0x87 DeviceFaultStatus = 0x88 DeviceFaultDescription = 0x89 DeviceManufacturerCode = ObjectManufacturerCode DeviceBusinessFacilityCode = 0x8B DeviceProductCode = 0x8C DeviceProductionNumber = 0x8D DeviceProductionDate = 0x8E DevicePowerSavingOperationSetting = 0x8F DeviceRemoteControlSetting = 0x93 DeviceCurrentTimeSetting = 0x97 DeviceCurrentDateSetting = 0x98 DevicePowerLimitSetting = 0x99 DeviceCumulativeOperatingTime = 0x9A DeviceAnnoPropertyMap = ObjectAnnoPropertyMap DeviceSetPropertyMap = ObjectSetPropertyMap DeviceGetPropertyMap = ObjectGetPropertyMap ) const ( DeviceInstallationLocationSize = 1 DeviceStandardVersionSize = 4 DeviceIdentificationNumberSize = 9 DeviceMeasuredInstantaneousPowerConsumptionSize = 2 DeviceMeasuredCumulativePowerConsumptionSize = 4 DeviceManufacturerFaultCodeSize = 255 DeviceCurrentLimitSettingSize = 1 DeviceFaultStatusSize = 1 DeviceFaultDescriptionSize = 2 DeviceManufacturerCodeSize = ObjectManufacturerCodeSize DeviceBusinessFacilityCodeSize = 3 DeviceProductCodeSize = 12 DeviceProductionNumberSize = 12 DeviceProductionDateSize = 4 DevicePowerSavingOperationSettingSize = 1 DeviceRemoteControlSettingSize = 1 DeviceCurrentTimeSettingSize = 2 DeviceCurrentDateSettingSize = 4 DevicePowerLimitSettingSize = 2 DeviceCumulativeOperatingTimeSize = 5 DeviceAnnoPropertyMapSize = ObjectAnnoPropertyMapMaxSize DeviceSetPropertyMapSize = ObjectSetPropertyMapMaxSize DeviceGetPropertyMapSize = ObjectGetPropertyMapMaxSize ) const ( DeviceOperatingStatusOn = ObjectOperatingStatusOn DeviceOperatingStatusOff = ObjectOperatingStatusOff DeviceVersionAppendixA = 'A' DeviceVersionAppendixB = 'B' DeviceVersionAppendixC = 'C' DeviceVersionAppendixD = 'D' DeviceVersionAppendixE = 'E' DeviceVersionAppendixF = 'F' DeviceVersionAppendixG = 'G' DeviceVersionUnknown = 0 DeviceDefaultVersionAppendix = DeviceVersionAppendixG DeviceFaultOccurred = 0x41 DeviceNoFaultOccurred = 0x42 DeviceInstallationLocationUnknown = 0x00 DeviceManufacturerUnknown = ObjectManufacturerUnknown ) const ( errorDeviceInvalidDeviceStandardVersion = "Invalid Device Standard Version (%s)" ) // Device represents an instance for a device object of Echonet. type Device struct { *SuperObject } // NewDevice returns a new device Object. func NewDevice() *Device { dev := &Device{ SuperObject: NewSuperObject(), } dev.addDeviceMandatoryProperties() return dev } // addDeviceMandatoryProperties sets mandatory properties for device object. func (dev *Device) addDeviceMandatoryProperties() error { // Operation Status dev.CreateProperty(ObjectOperatingStatus, PropertyAttributeReadAnno) dev.SetOperatingStatus(true) // Installation Location dev.CreateProperty(DeviceInstallationLocation, PropertyAttributeReadAnno) dev.SetInstallationLocation(DeviceInstallationLocationUnknown) // Standard Version Infomation dev.CreateProperty(DeviceStandardVersion, PropertyAttributeRead) dev.SetStandardVersion(DeviceDefaultVersionAppendix) // Fault Status dev.CreateProperty(DeviceFaultStatus, PropertyAttributeReadAnno) dev.SetFaultStatus(false) // Manufacture Code dev.CreateProperty(DeviceManufacturerCode, PropertyAttributeRead) dev.SetManufacturerCode(DeviceManufacturerUnknown) return nil } // SetInstallationLocation sets a installation location to the device. func (dev *Device) SetInstallationLocation(locByte byte) error { return dev.SetPropertyByteData(DeviceInstallationLocation, locByte) } // GetInstallationLocation return the installation location of the device. func (dev *Device) GetInstallationLocation() (byte, error) { return dev.GetPropertyByteData(DeviceInstallationLocation) } // SetStandardVersion sets a standard version to the device. func (dev *Device) SetStandardVersion(ver byte) error { verBytes := []byte{0x00, 0x00, ver, 0x00} return dev.SetPropertyData(DeviceStandardVersion, verBytes) } // GetStandardVersion return the standard version of the device. func (dev *Device) GetStandardVersion() (byte, error) { verBytes, err := dev.GetPropertyData(DeviceStandardVersion) if err != nil { return 0, err } if len(verBytes) <= DeviceStandardVersionSize { return 0, fmt.Errorf(errorDeviceInvalidDeviceStandardVersion, string(verBytes)) } return verBytes[2], nil } // SetFaultStatus sets a fault status to the device. func (dev *Device) SetFaultStatus(stats bool) error { statsByte := byte(DeviceNoFaultOccurred) if stats { statsByte = DeviceFaultOccurred } return dev.SetPropertyByteData(DeviceFaultStatus, statsByte) } // GetFaultStatus return the fault status of the device. func (dev *Device) GetFaultStatus() (bool, error) { statsByte, err := dev.GetPropertyByteData(DeviceFaultStatus) if err != nil { return false, err } if statsByte == DeviceFaultOccurred { return true, nil } return false, nil }
package v1alpha1 import ( "fmt" "github.com/kotalco/kotal/apis/shared" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // SwarmSpec defines the desired state of Swarm type SwarmSpec struct { // Nodes is swarm nodes // +kubebuilder:validation:MinItems=1 Nodes []Node `json:"nodes"` } // Node is ipfs node type Node struct { // Name is node name Name string `json:"name"` // ID is node peer ID ID string `json:"id"` // PrivateKey is node private key PrivateKey string `json:"privateKey"` // Profiles is a list of profiles to apply Profiles []Profile `json:"profiles,omitempty"` // Resources is node compute and storage resources shared.Resources `json:"resources,omitempty"` } // SwarmAddress returns node swarm address func (n *Node) SwarmAddress(ip string) string { // TODO: replace hardcoded 4001 port with node swarm port return fmt.Sprintf("/ip4/%s/tcp/4001/p2p/%s", ip, n.ID) } // StatefulSetName returns name to be used by node stateful func (n *Node) StatefulSetName(swarm string) string { return fmt.Sprintf("%s-%s", swarm, n.Name) } // PVCName returns name to be used by node pvc func (n *Node) PVCName(swarm string) string { return n.StatefulSetName(swarm) // same as stateful name } // ConfigName returns name to be used by node config map func (n *Node) ConfigName(swarm string) string { return n.StatefulSetName(swarm) // same as stateful name } // ServiceName returns name to be used by node service func (n *Node) ServiceName(swarm string) string { return n.StatefulSetName(swarm) // same as stateful name } // Labels to be used by node resources func (n *Node) Labels(swarm string) map[string]string { return map[string]string{ "name": "node", "instance": n.Name, "swarm": swarm, } } // SwarmStatus defines the observed state of Swarm type SwarmStatus struct { // NodesCount is number of nodes in this swarm NodesCount int `json:"nodesCount,omitempty"` } // +kubebuilder:object:root=true // +kubebuilder:subresource:status // Swarm is the Schema for the swarms API // +kubebuilder:printcolumn:name="Nodes",type=integer,JSONPath=".status.nodesCount" type Swarm struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec SwarmSpec `json:"spec,omitempty"` Status SwarmStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // SwarmList contains a list of Swarm type SwarmList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Swarm `json:"items"` } func init() { SchemeBuilder.Register(&Swarm{}, &SwarmList{}) }
package main import "fmt" func main() { fmt.Println("myString"[2]) //puedes coger el indice de una string, y te devolvera su valor numerico fmt.Println(string("myString"[2])) // lo mismo que antes pero convertido a string fmt.Println("쯼"[0]) //este caracter esta compuesto por 3 bytes, [236 175 188], si imprimimos el 0 nos dara 236 fmt.Println("쯼쯼"[5]) // [236(0) 175(1) 188(2) 236(3) 175(4) 188(5) imprimira 188] }
package common // Checksum will calculate the checksum of a byte slice. func Checksum(b []byte) uint16 { sum := uint32(0) for ; len(b) >= 2; b = b[2:] { b0 := uint32(b[0]) b1 := uint32(b[1]) sum += (b0 << 8) | b1 } if len(b) > 0 { sum += uint32(b[0]) << 8 } for sum > 0xFFFF { sum = (sum >> 16) + (sum & 0xFFFF) } csum := ^uint16(sum) if csum == 0 { csum = 0xFFFF } return csum }
package main import ( "bytes" "context" "crypto/sha512" "errors" "flag" "fmt" "io" "net/url" "os" "sync" "github.com/folbricht/desync" ) const untarUsage = `desync untar <catar> <target> Extracts a directory tree from a catar file or an index file.` func untar(ctx context.Context, args []string) error { var ( readIndex bool n int storeLocations = new(multiArg) stores []desync.Store cacheLocation string ) flags := flag.NewFlagSet("untar", flag.ExitOnError) flags.Usage = func() { fmt.Fprintln(os.Stderr, untarUsage) flags.PrintDefaults() } flags.BoolVar(&readIndex, "i", false, "Read index file (caidx), not catar") flags.Var(storeLocations, "s", "casync store location, can be multiples (with -i)") flags.StringVar(&cacheLocation, "c", "", "use local store as cache (with -i)") flags.IntVar(&n, "n", 10, "number of goroutines (with -i)") flags.Parse(args) if flags.NArg() < 2 { return errors.New("Not enough arguments. See -h for help.") } if flags.NArg() > 2 { return errors.New("Too many arguments. See -h for help.") } input := flags.Arg(0) targetDir := flags.Arg(1) f, err := os.Open(input) if err != nil { return err } defer f.Close() // If we got a catar file unpack that and exit if !readIndex { return desync.UnTar(ctx, f, targetDir) } // Apparently the input must be an index, read it whole index, err := desync.IndexFromReader(f) if err != nil { return err } // Go through each store passed in the command line, initialize them, and // build a list for _, location := range storeLocations.list { loc, err := url.Parse(location) if err != nil { return fmt.Errorf("Unable to parse store location %s : %s", location, err) } var s desync.Store switch loc.Scheme { case "ssh": r, err := desync.NewRemoteSSHStore(loc, n) if err != nil { return err } defer r.Close() s = r case "http", "https": s, err = desync.NewRemoteHTTPStore(loc) if err != nil { return err } case "": s, err = desync.NewLocalStore(loc.Path) if err != nil { return err } default: return fmt.Errorf("Unsupported store access scheme %s", loc.Scheme) } stores = append(stores, s) } // Combine all stores into one router var s desync.Store = desync.NewStoreRouter(stores...) // See if we want to use a local store as cache, if so, attach a cache to // the router if cacheLocation != "" { cache, err := desync.NewLocalStore(cacheLocation) if err != nil { return err } cache.UpdateTimes = true s = desync.NewCache(s, cache) } return untarIndex(ctx, targetDir, index, s, n) } func untarIndex(ctx context.Context, dst string, index desync.Index, s desync.Store, n int) error { type requestJob struct { chunk desync.IndexChunk // requested chunk data chan ([]byte) // channel for the (decompressed) chunk } var ( // stop bool wg sync.WaitGroup mu sync.Mutex pErr error req = make(chan requestJob) assemble = make(chan chan []byte, n) ) ctx, cancel := context.WithCancel(ctx) defer cancel() // Helper function to record and deal with any errors in the goroutines recordError := func(err error) { mu.Lock() defer mu.Unlock() if pErr == nil { pErr = err } cancel() } // Use a pipe as input to untar and write the chunks into that (in the right // order of course) r, w := io.Pipe() // Workers - getting chunks from the store for i := 0; i < n; i++ { wg.Add(1) go func() { for r := range req { // Pull the (compressed) chunk from the store b, err := s.GetChunk(r.chunk.ID) if err != nil { recordError(err) continue } // Since we know how big the chunk is supposed to be, pre-allocate a // slice to decompress into db := make([]byte, r.chunk.Size) // The the chunk is compressed. Decompress it here db, err = desync.Decompress(db, b) if err != nil { recordError(err) continue } // Verify the checksum of the chunk matches the ID sum := sha512.Sum512_256(db) if sum != r.chunk.ID { recordError(fmt.Errorf("unexpected sha512/256 %s for chunk id %s", sum, r.chunk.ID)) continue } // Might as well verify the chunk size while we're at it if r.chunk.Size != uint64(len(db)) { recordError(fmt.Errorf("unexpected size for chunk %s", r.chunk.ID)) continue } r.data <- db close(r.data) } wg.Done() }() } // Feeder - requesting chunks from the workers go func() { loop: for _, c := range index.Chunks { // See if we're meant to stop select { case <-ctx.Done(): break loop default: } data := make(chan []byte, 1) req <- requestJob{chunk: c, data: data} // request the chunk assemble <- data // and hand over the data channel to the assembler } close(req) wg.Wait() // wait for the workers to stop close(assemble) // tell the assembler we're done }() // Assember - push the chunks into the pipe that untar reads from go func() { for data := range assemble { b := <-data if _, err := io.Copy(w, bytes.NewReader(b)); err != nil { recordError(err) } } w.Close() // No more chunks to come, stop the untar }() // Run untar in the main go routine if err := desync.UnTar(ctx, r, dst); err != nil { return err } return pErr }
/* Copyright 2019 Adobe All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. */ package maker import ( "strings" ) type Vars map[string]string func (i *Vars) String() string { return "" } func (i *Vars) Set(value string) error { if i == nil { *i = make(Vars) } parts := strings.SplitN(value, "=", 2) if len(parts) == 2 { (*i)[parts[0]] = parts[1] } else { (*i)[parts[0]] = "1" } return nil }
package main import ( "fmt" "time" ) //We often want to execute Go code // at some point in the future, or repeatedly at some interval. func main() { //Timers represent a single event in the future. You tell the timer how long you want to wait, timer1 := time.NewTimer(2 * time.Second) <-timer1.C fmt.Println("Timer 1 expired") timer2 := time.NewTimer(time.Second) go func() { <-timer2.C fmt.Println("Timer 2 expired") }() // Stop() can cancel the timer before it expires. stop2 := timer2.Stop() if stop2 { fmt.Println("Timer 2 stopped") } }
package struct_utils import ( "regexp" "strings" "github.com/chenwj93/utils" "fmt" ) var reg =`delete[\s]+from[\s]+([-_a-zA-Z0-9]+)[\s]+|delete[\s]+([-_a-zA-Z0-9]+)[\s]+|update[\s]+([-_a-zA-Z0-9]+)[\s]+|insert[\s]+into[\s]+([-_a-zA-Z0-9]+)[\s]+|insert[\s]+([-_a-zA-Z0-9]+)[\s]+` var r *regexp.Regexp func init() { r = regexp.MustCompile(reg) } func SelectTable(sql string) string{ index := r.FindStringSubmatchIndex(strings.ToLower(sql)) if len(index) == 0 { return utils.EMPTY_STRING } fmt.Println(index) for i := 2; i < len(index); i += 2 { if index[i] != -1 && index[i+1] != -1{ return sql[index[i]:index[i+1]] } } return utils.EMPTY_STRING }
package processd import ( "net/http" "strings" "github.com/felixge/fgprof" "github.com/gorilla/mux" "github.com/minotar/imgd/pkg/skind" "github.com/minotar/imgd/pkg/util/route_helpers" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) // routes registers all the routes func (p *Processd) routes() { p.Server.HTTP.Path("/debug/fgprof").Handler(fgprof.Handler()) p.Server.HTTP.Path("/healthcheck").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }) RegisterProcessingRoutes(p.Server.HTTP, p.SkinLookupWrapper, p.ProcessRoutes) } func RegisterProcessingRoutes(m *mux.Router, skinWrapper skind.SkinWrapper, processRoutes map[string]skind.SkinProcessor) { uuidCounter := requestedUserType.MustCurryWith(prometheus.Labels{"type": "UUID"}) dashedCounter := requestedUserType.MustCurryWith(prometheus.Labels{"type": "DashedUUID"}) usernameCounter := requestedUserType.MustCurryWith(prometheus.Labels{"type": "Username"}) usernamePath := route_helpers.UsernamePath uuidPath := route_helpers.UUIDPath extPath := route_helpers.ExtensionPath widPath := route_helpers.WidthPath for resource, processor := range processRoutes { handler := skinWrapper(processor) usernameHandler := promhttp.InstrumentHandlerCounter(usernameCounter, handler) uuidHandler := promhttp.InstrumentHandlerCounter(uuidCounter, handler) resPath := "/{resource:" + strings.ToLower(resource) + "}/" sr := m.PathPrefix(resPath).Subrouter() // Username sr.Path(usernamePath + extPath).Handler(usernameHandler).Name(resource) sr.Path(usernamePath + "/" + widPath + extPath).Handler(usernameHandler).Name(resource) // UUID sr.Path(uuidPath + extPath).Handler(uuidHandler).Name(resource) sr.Path(uuidPath + "/" + widPath + extPath).Handler(uuidHandler).Name(resource) // Dashed Redirect route_helpers.SubRouteDashedRedirect(sr, dashedCounter) } }
// 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 layout is used to find parts of the application package to load or run. // It can use the running executable directory, or other supplied locations, and find // files targeted to a specific abi. package layout
package main import ( "database/sql" "flag" "fmt" "gopkg.in/cheggaaa/pb.v1" "io/ioutil" "log" "net/http" "strings" "sync" ) var ( url = flag.String("url", "https://loripsum.net/api/10000/long/plaintext", "URL") count = flag.Int("count", 1000, "fill requests count") ) const ( INSERT_QUERY = ` begin; insert into items (fts) values (to_tsvector('%s')); commit; ` ) func getter(wg *sync.WaitGroup, chm chan int) { var err error var db *sql.DB defer wg.Done() db, err = openTestConn() if err != nil { log.Fatal(err) } defer db.Close() for range chm { resp, err := http.Get(*url) if err != nil { log.Println("Request error:", err) break } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() sql := fmt.Sprintf(INSERT_QUERY, strings.Replace(string(body), "\n", "", -1)) makeQuery(db, sql) } } func getTexts() { var wg sync.WaitGroup chm := make(chan int, 1) for i := 0; i < *connections; i++ { wg.Add(1) go getter(&wg, chm) } bar := pb.StartNew(*count) for i := 0; i < *count; i++ { chm <- i bar.Increment() } close(chm) log.Printf("Inserted %d texts\n", *count) wg.Wait() }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package cryptohome import ( "context" "time" uda "chromiumos/system_api/user_data_auth_proto" cryptohomecommon "chromiumos/tast/common/cryptohome" "chromiumos/tast/common/hwsec" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/cryptohome" hwseclocal "chromiumos/tast/local/hwsec" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: AuthSessionUnlock, Desc: "Check session unlock via AuthSession", Contacts: []string{ "emaxx@chromium.org", "cryptohome-core@google.com", }, Attr: []string{"group:mainline", "informational"}, Params: []testing.Param{{ Name: "with_vk", Fixture: "vkAuthSessionFixture", }, { Name: "with_uss", Fixture: "ussAuthSessionFixture", }}, }) } func AuthSessionUnlock(ctx context.Context, s *testing.State) { const ( ownerName = "owner@bar.baz" userName = "foo@bar.baz" userPassword = "secret" userPasswordAfterUpdate = "i-forgot-secret" secondUserName = "doo@bar.baz" secondPassword = "different-secret" passwordLabel = "online-password" ) ctxForCleanUp := ctx ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second) defer cancel() cmdRunner := hwseclocal.NewCmdRunner() client := hwsec.NewCryptohomeClient(cmdRunner) helper, err := hwseclocal.NewHelper(cmdRunner) if err != nil { s.Fatal("Failed to create hwsec local helper: ", err) } daemonController := helper.DaemonController() // verifyPassword will create a verify-only session that will ensure that // the given user cannot authenticate with the given "wrong" passwords and // can authenticate with the correct one. It will return an error on // failure and nil on success. verifyPassword := func(user, password, badPassword, otherUsersPassword string) error { return client.WithAuthSession(ctx, user, false /*isEphemeral*/, uda.AuthIntent_AUTH_INTENT_VERIFY_ONLY, func(authSessionID string) error { var authReply *uda.AuthenticateAuthFactorReply if _, err := client.AuthenticateAuthFactor(ctx, authSessionID, passwordLabel, badPassword); err == nil { return errors.New("authenticated user with the wrong password") } if _, err := client.AuthenticateAuthFactor(ctx, authSessionID, passwordLabel, otherUsersPassword); err == nil { return errors.New("authenticated user with the other user's password which should have failed") } if authReply, err = client.AuthenticateAuthFactor(ctx, authSessionID, passwordLabel, password); err != nil { return errors.Wrap(err, "failed to authenticate user") } if err := cryptohomecommon.ExpectContainsAuthIntent( authReply.AuthorizedFor, uda.AuthIntent_AUTH_INTENT_VERIFY_ONLY, ); err != nil { return errors.Wrap(err, "unexpected AuthSession authorized intents") } return nil }) } // Wait for cryptohomed to become available if needed. if err := daemonController.Ensure(ctx, hwsec.CryptohomeDaemon); err != nil { s.Fatal("Failed to ensure cryptohomed: ", err) } // Clean up old state or mounts for the test user, if any exists. if err := client.UnmountAll(ctx); err != nil { s.Fatal("Failed to unmount vaults for preparation: ", err) } if err := cryptohome.RemoveVault(ctx, userName); err != nil { s.Fatal("Failed to remove old vault for preparation: ", err) } if err := cryptohome.RemoveVault(ctx, secondUserName); err != nil { s.Fatal("Failed to remove old vault for preparation: ", err) } // Create and mount the user with a password auth factor. if err := client.WithAuthSession(ctx, userName, false /*isEphemeral*/, uda.AuthIntent_AUTH_INTENT_DECRYPT, func(authSessionID string) error { if err := client.CreatePersistentUser(ctx, authSessionID); err != nil { return errors.Wrap(err, "failed to create persistent user") } if err := client.PreparePersistentVault(ctx, authSessionID, false /*ecryptfs*/); err != nil { return errors.Wrap(err, "failed to prepare new persistent vault") } if err := client.AddAuthFactor(ctx, authSessionID, passwordLabel, userPassword); err != nil { return errors.Wrap(err, "failed to add initial user password") } return nil }); err != nil { s.Fatal("Failed to create and set up the user: ", err) } defer cryptohome.RemoveVault(ctxForCleanUp, userName) // Create and mount the user with a second password auth factor. if err := client.WithAuthSession(ctx, secondUserName, false /*isEphemeral*/, uda.AuthIntent_AUTH_INTENT_DECRYPT, func(authSessionID string) error { if err := client.CreatePersistentUser(ctx, authSessionID); err != nil { return errors.Wrap(err, "failed to create persistent user") } if err := client.PreparePersistentVault(ctx, authSessionID, false /*ecryptfs*/); err != nil { return errors.Wrap(err, "failed to prepare new persistent vault") } if err := client.AddAuthFactor(ctx, authSessionID, passwordLabel, secondPassword); err != nil { return errors.Wrap(err, "failed to add initial user password") } return nil }); err != nil { s.Fatal("Failed to create and set up the second user: ", err) } defer cryptohome.RemoveVault(ctxForCleanUp, secondUserName) // Verify that the user passwords can be used to authenticate. if err := verifyPassword(userName, userPassword, userPasswordAfterUpdate, secondPassword); err != nil { s.Fatal("Failed to authenticate first user with initial password: ", err) } if err := verifyPassword(secondUserName, secondPassword, userPasswordAfterUpdate, userPassword); err != nil { s.Fatal("Failed to authenticate second user: ", err) } // Change the user's password. if err := client.WithAuthSession(ctx, userName, false /*isEphemeral*/, uda.AuthIntent_AUTH_INTENT_DECRYPT, func(authSessionID string) error { var authReply *uda.AuthenticateAuthFactorReply if authReply, err = client.AuthenticateAuthFactor(ctx, authSessionID, passwordLabel, userPassword); err != nil { return errors.Wrap(err, "failed to authenticate user") } if err := cryptohomecommon.ExpectContainsAuthIntent( authReply.AuthorizedFor, uda.AuthIntent_AUTH_INTENT_DECRYPT, ); err != nil { return errors.Wrap(err, "unexpected AuthSession authorized intents") } if err := client.UpdatePasswordAuthFactor(ctx, authSessionID, passwordLabel, passwordLabel, userPasswordAfterUpdate); err != nil { return errors.Wrap(err, "failed to update password") } return nil }); err != nil { s.Fatal("Failed to change the user password: ", err) } // Verify the new password can be used to authenticate. if err := verifyPassword(userName, userPasswordAfterUpdate, userPassword, secondPassword); err != nil { s.Fatal("Failed to authenticate with changed password: ", err) } }
package leetcode func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { if len(nums) <= 1 { return false } if k <= 0 { return false } n := len(nums) for i := 0; i < n; i++ { count := 0 for j := i + 1; j < n && count < k; j++ { if abs(nums[i]-nums[j]) <= t && j != i { return true } count++ } } return false }
package main // Leetcode 129. (medium) func sumNumbers(root *TreeNode) int { return recursiveSumNumbers(root, 0, 0) } func recursiveSumNumbers(root *TreeNode, cur int, res int) int { if root == nil { return res } cur = cur*10 + root.Val if root.Left == nil && root.Right == nil { res = res + cur } else { res = recursiveSumNumbers(root.Left, cur, res) res = recursiveSumNumbers(root.Right, cur, res) } cur = (cur - root.Val) / 10 return res }
package s_logger import ( "github.com/stretchr/testify/assert" "sync" "testing" ) func TestName(t *testing.T) { logger := New() logger.Info("Info") logger.Error("Error") defer logger.Sync() assert.NotEmpty(t, logger, "日志信息不能为空") } func TestMultiSingle(t *testing.T) { logger := New() times := 1024 for i := 0; i < times; i++ { logger.Infow("测试打印日志", "name", "name") } } func TestMultiOpen(t *testing.T) { waitGroup := sync.WaitGroup{} waitGroup.Add(2) go func() { logger := New() times := 1024 for i := 0; i < times; i++ { logger.Infow("1111111111", "name", "name") } waitGroup.Done() }() go func() { logger := New() times := 1024 for i := 0; i < times; i++ { logger.Infow("2222222222", "name", "name") } waitGroup.Done() }() waitGroup.Wait() }
package music_test import ( "git.ronaksoftware.com/blip/server/internal/tools" testEnv "git.ronaksoftware.com/blip/server/pkg" "git.ronaksoftware.com/blip/server/pkg/music" . "github.com/smartystreets/goconvey/convey" "testing" "time" ) /* Creation Time: 2020 - Feb - 01 Created by: (ehsan) Maintainers: 1. Ehsan N. Moosa (E2) Auditor: Ehsan N. Moosa (E2) Copyright Ronak Software Group 2018 */ func TestSearch(t *testing.T) { testEnv.InitMultiCrawlers(10, time.Second*10, 8181) time.Sleep(time.Second * 2) cursorID := tools.RandomID(12) keyword := "Song 1" Convey("Search By Text", t, func(c C) { Convey("Start Search (Consume All)", func(c C) { searchCtx := music.StartSearch(cursorID, keyword) for s := range searchCtx.SongChan() { c.So(s, ShouldNotBeNil) } }) Convey("Resume Search (After Consume All)", func(c C) { searchCtx := music.ResumeSearch(cursorID) c.So(searchCtx, ShouldBeNil) }) Convey("Start Search (Partial Consume)", func(c C) { searchCtx := music.StartSearch(cursorID, keyword) c.So(searchCtx, ShouldNotBeNil) songX := <-searchCtx.SongChan() c.So(songX, ShouldNotBeNil) }) Convey("Resume Search (After Partial Consume)", func(c C) { searchCtx := music.ResumeSearch(cursorID) c.So(searchCtx, ShouldNotBeNil) for s := range searchCtx.SongChan() { c.So(s, ShouldNotBeNil) } }) }) }
package stack type ErrorStack struct { Err error Cause string } func (es *ErrorStack) Error() string { return es.Err.Error() + es.Cause }
// /** // * Created using VSCode // * User : Sean // * Simple web crawler example file to test how to query web pages and the displayed data // */ // package main // /* // useful urls // https://www.devdungeon.com/content/web-scraping-go // https://tour.golang.org/concurrency/10 // http://edmundmartin.com/writing-a-web-crawler-in-golang/ // https://jdanger.com/build-a-web-crawler-in-go.html // */ // import ( // "fmt" // "io" // "io/ioutil" // "log" // "net/http" // "os" // "strings" // "time" // ) // func main() { // // Create HTTP client with timeout // client := &http.Client{ // Timeout: 30 * time.Second, // } // // Make request using timeout client! // response, err := client.Get("https://www.devdungeon.com/") // if err != nil { // log.Fatal(err) // } // defer response.Body.Close() // // Create output file if you want to store the site in a file // // outFile, err := os.Create("output.html") // // if err != nil { // // log.Fatal(err) // // } // // defer outFile.Close() // // Get the response body as a string // dataInBytes, err := ioutil.ReadAll(response.Body) // pageContent := string(dataInBytes) // // Find a substr // titleStartIndex := strings.Index(pageContent, "Clearance") // if titleStartIndex == -1 { // fmt.Println("No matching content found") // os.Exit(0) // } // // Copy data from the response to standard output // n, err := io.Copy(os.Stdout, response.Body) // if err != nil { // log.Fatal(err) // } // log.Println("Number of bytes copied to STDOUT:", n) // } // func retrieve(uri string) { // This func(tion) takes a parameter and the // // format for a function parameter definition is // // to say what the name of the parameter is and then // // the type. // // So here we're expecting to be given a // // string that we'll refer to as 'uri' // resp, err := http.Get(uri) // if err != nil { // This is the way error handling typically works in Go. // return // It's a bit verbose but it works. // } // defer resp.Body.Close() // Important: we need to close the resource we opened // // (the TCP connection to some web server and our reference // // to the stream of data it sends us). // // `defer` delays an operation until the function ends. // // It's basically the same as if you'd moved the code // // you're deferring to the very last line of the func. // body, _ := ioutil.ReadAll(resp.Body) // I'm assigning the err to _ 'cause // // I don't care about it but Go will whine // fmt.Println(string(body)) // if I name it and don't use it // }
// Copyright (C) 2021 Storj Labs, Inc. // See LICENSE for copying information. package rpctest import ( "context" "storj.io/common/rpc/rpcpool" "storj.io/drpc" ) // MessageHook is a function which may be called before and after an rpc call. type MessageHook func(rpc string, message drpc.Message, err error) // MessageInterceptor is a drpc.Conn which wraps an original connection with more functionality. type MessageInterceptor struct { delegate rpcpool.RawConn RequestHook MessageHook ResponseHook MessageHook } // NewMessageInterceptor creates a MessageInterceptor, a connection which delegates all the call to the specific drpc.Conn. func NewMessageInterceptor(conn rpcpool.RawConn) MessageInterceptor { return MessageInterceptor{ delegate: conn, } } // Close closes underlying dprc connection. func (l *MessageInterceptor) Close() error { return l.delegate.Close() } // Closed returns a channel that is closed if the underlying connection is definitely closed. func (l *MessageInterceptor) Closed() <-chan struct{} { return l.delegate.Closed() } // Unblocked returns the unblocked channel from the delegate. func (l *MessageInterceptor) Unblocked() <-chan struct{} { return l.delegate.Unblocked() } // Invoke the underlying connection but call the RequestHook/ResponseHook before and after. // When the Invoker is set it will be invoked instead of the original connection. func (l *MessageInterceptor) Invoke(ctx context.Context, rpc string, enc drpc.Encoding, in, out drpc.Message) error { var err error if l.RequestHook != nil { l.RequestHook(rpc, in, nil) } err = l.delegate.Invoke(ctx, rpc, enc, in, out) if l.ResponseHook != nil { l.ResponseHook(rpc, out, err) } return err } // NewStream creates a new wrapped stream. func (l *MessageInterceptor) NewStream(ctx context.Context, rpc string, enc drpc.Encoding) (drpc.Stream, error) { stream, err := l.delegate.NewStream(ctx, rpc, enc) if err != nil { return stream, err } return &interceptedStream{ delegate: stream, rpc: rpc, requestHook: l.RequestHook, responseHook: l.ResponseHook, }, nil } type interceptedStream struct { delegate drpc.Stream requestHook MessageHook responseHook MessageHook rpc string } // Context returns the context from the underlying stream. func (d *interceptedStream) Context() context.Context { return d.delegate.Context() } // MsgSend sends the Message to the underlying remote OR calls the configured Invoker if defined. // In both cases the RequestHook is called before. func (d *interceptedStream) MsgSend(msg drpc.Message, enc drpc.Encoding) error { var err error if d.requestHook != nil { d.requestHook(d.rpc, msg, err) } err = d.delegate.MsgSend(msg, enc) return err } // MsgRecv receives a Message from the underlying wrapped remote. // The configured responseHook is executed before return. func (d *interceptedStream) MsgRecv(msg drpc.Message, enc drpc.Encoding) error { err := d.delegate.MsgRecv(msg, enc) if d.responseHook != nil { d.responseHook(d.rpc, msg, err) } return err } // CloseSend signals to the remote that we will no longer send any messages. func (d *interceptedStream) CloseSend() error { return d.delegate.CloseSend() } // Close closes the stream. func (d *interceptedStream) Close() error { return d.delegate.Close() }
package metricstore_test import ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "strconv" "sync" "time" "github.com/cloudfoundry/metric-store-release/src/pkg/leanstreams" "github.com/cloudfoundry/metric-store-release/src/pkg/metricstore" "github.com/cloudfoundry/metric-store-release/src/pkg/persistence/transform" rpc "github.com/cloudfoundry/metric-store-release/src/pkg/rpc/metricstore_v1" metrictls "github.com/cloudfoundry/metric-store-release/src/pkg/tls" "github.com/gogo/protobuf/proto" "github.com/prometheus/common/expfmt" . "github.com/cloudfoundry/metric-store-release/src/pkg/matchers" "github.com/cloudfoundry/metric-store-release/src/pkg/testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) // Sentinel to detect build failures early var __ *metricstore.MetricStore var storagePath = "/tmp/metric-store-node" var _ = Describe("MetricStore", func() { type testContext struct { addr string ingressAddr string healthPort string gatewayAddr string gatewayHealthPort string metricStoreProcess *gexec.Session gatewayProcess *gexec.Session tlsConfig *tls.Config } var start = func(tc *testContext) { caCert := testing.Cert("metric-store-ca.crt") cert := testing.Cert("metric-store.crt") key := testing.Cert("metric-store.key") tlsConfig, err := metrictls.NewMutualTLSConfig(caCert, cert, key, "metric-store") if err != nil { fmt.Printf("ERROR: invalid mutal TLS config: %s\n", err) } tc.tlsConfig = tlsConfig tc.metricStoreProcess = testing.StartGoProcess( "github.com/cloudfoundry/metric-store-release/src/cmd/metric-store", []string{ "ADDR=" + tc.addr, "INGRESS_ADDR=" + tc.ingressAddr, "HEALTH_PORT=" + tc.healthPort, "STORAGE_PATH=" + storagePath, "RETENTION_PERIOD_IN_DAYS=1", "CA_PATH=" + caCert, "CERT_PATH=" + cert, "KEY_PATH=" + key, "METRIC_STORE_SERVER_CA_PATH=" + caCert, "METRIC_STORE_SERVER_CERT_PATH=" + cert, "METRIC_STORE_SERVER_KEY_PATH=" + key, }, ) tc.gatewayProcess = testing.StartGoProcess( "github.com/cloudfoundry/metric-store-release/src/cmd/gateway", []string{ "ADDR=" + tc.gatewayAddr, "HEALTH_PORT=" + tc.gatewayHealthPort, "METRIC_STORE_ADDR=" + tc.addr, "CA_PATH=" + caCert, "CERT_PATH=" + cert, "KEY_PATH=" + key, "PROXY_CERT_PATH=" + cert, "PROXY_KEY_PATH=" + key, }, ) testing.WaitForHealthCheck(tc.healthPort) testing.WaitForServer(tc.gatewayAddr) } var stop = func(tc *testContext) { tc.metricStoreProcess.Kill() tc.gatewayProcess.Kill() Eventually(tc.metricStoreProcess.Exited).Should(BeClosed()) Eventually(tc.gatewayProcess.Exited).Should(BeClosed()) } var perform = func(tc *testContext, operation func(*testContext)) { wg := &sync.WaitGroup{} wg.Add(1) go func() { defer GinkgoRecover() defer wg.Done() operation(tc) }() wg.Wait() } var setup = func() (*testContext, func()) { tc := &testContext{} tc.addr = fmt.Sprintf("localhost:%d", testing.GetFreePort()) tc.ingressAddr = fmt.Sprintf("localhost:%d", testing.GetFreePort()) tc.healthPort = strconv.Itoa(testing.GetFreePort()) tc.gatewayAddr = fmt.Sprintf("localhost:%d", testing.GetFreePort()) tc.gatewayHealthPort = strconv.Itoa(testing.GetFreePort()) perform(tc, start) return tc, func() { perform(tc, stop) os.RemoveAll(storagePath) } } type testInstantQuery struct { Query string TimeInSeconds string } var makeInstantQuery = func(tc *testContext, query testInstantQuery) (*http.Response, error) { queryUrl, err := url.Parse("api/v1/query") Expect(err).ToNot(HaveOccurred()) queryString := queryUrl.Query() queryString.Set("query", query.Query) queryString.Set("time", query.TimeInSeconds) queryUrl.RawQuery = queryString.Encode() return testing.MakeTLSReq(tc.gatewayAddr, queryUrl.String()) } type testRangeQuery struct { Query string StartInSeconds string EndInSeconds string StepDuration string } var makeRangeQuery = func(tc *testContext, query testRangeQuery) (*http.Response, error) { queryUrl, err := url.Parse("api/v1/query_range") Expect(err).ToNot(HaveOccurred()) queryString := queryUrl.Query() queryString.Set("query", query.Query) queryString.Set("start", query.StartInSeconds) queryString.Set("end", query.EndInSeconds) queryString.Set("step", query.StepDuration) queryUrl.RawQuery = queryString.Encode() return testing.MakeTLSReq(tc.gatewayAddr, queryUrl.String()) } type testSeriesQuery struct { Match []string StartInSeconds string EndInSeconds string } var makeSeriesQuery = func(tc *testContext, query testSeriesQuery) (*http.Response, error) { queryUrl, err := url.Parse("api/v1/series") Expect(err).ToNot(HaveOccurred()) queryString := queryUrl.Query() for _, match := range query.Match { queryString.Add("match[]", match) } queryString.Set("start", query.StartInSeconds) queryString.Set("end", query.EndInSeconds) queryUrl.RawQuery = queryString.Encode() return testing.MakeTLSReq(tc.gatewayAddr, queryUrl.String()) } type testPoint struct { Name string TimeInMilliseconds int64 Value float64 Labels map[string]string } type testLabelValuesResult struct { Status string `json:"status"` Data []string `json:"data"` } var writePoints = func(tc *testContext, points []testPoint) { var rpcPoints []*rpc.Point metricNameCounts := make(map[string]int) for _, point := range points { timestamp := transform.MillisecondsToNanoseconds(point.TimeInMilliseconds) rpcPoints = append(rpcPoints, &rpc.Point{ Name: point.Name, Value: point.Value, Timestamp: timestamp, Labels: point.Labels, }) metricNameCounts[point.Name]++ } cfg := &leanstreams.TCPClientConfig{ MaxMessageSize: 65536, Address: tc.ingressAddr, TLSConfig: tc.tlsConfig, } remoteConnection, err := leanstreams.DialTCP(cfg) Expect(err).ToNot(HaveOccurred()) defer remoteConnection.Close() payload, err := proto.Marshal(&rpc.SendRequest{ Batch: &rpc.Points{ Points: rpcPoints, }, }) Expect(err).ToNot(HaveOccurred()) _, err = remoteConnection.Write(payload) Expect(err).ToNot(HaveOccurred()) Eventually(func() bool { resp, _ := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/__name__/values") jsonBytes, _ := ioutil.ReadAll(resp.Body) var result testLabelValuesResult json.Unmarshal(jsonBytes, &result) return len(result.Data) == len(metricNameCounts) }, 3).Should(BeTrue()) } It("deletes shards with old data when Metric Store starts", func() { tc, cleanup := setup() defer cleanup() now := time.Now() Eventually(func() []string { writePoints( tc, []testPoint{ { Name: "metric_name_old", TimeInMilliseconds: 1000, }, { Name: "metric_name_new", TimeInMilliseconds: now.UnixNano() / int64(time.Millisecond), }, }, ) resp, err := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/__name__/values") if err != nil { return nil } jsonBytes, _ := ioutil.ReadAll(resp.Body) var result testLabelValuesResult json.Unmarshal(jsonBytes, &result) return result.Data }, 5).Should(ConsistOf([]string{ "metric_name_old", "metric_name_new", })) stop(tc) start(tc) Eventually(func() error { _, err := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/__name__/values") return err }, 5).Should(Succeed()) Eventually(func() []string { resp, err := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/__name__/values") Expect(err).ToNot(HaveOccurred()) jsonBytes, _ := ioutil.ReadAll(resp.Body) var result testLabelValuesResult json.Unmarshal(jsonBytes, &result) return result.Data }, 1).Should(ConsistOf([]string{ "metric_name_new", })) }) Context("when using HTTP", func() { Context("when a instant query is made", func() { It("returns metrics from a simple query", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name", Value: 99, TimeInMilliseconds: 1500, Labels: map[string]string{ "source_id": "1", }, }, }, ) resp, err := makeInstantQuery(tc, testInstantQuery{ Query: "metric_name", TimeInSeconds: "2", }) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status":"success", "data": { "resultType":"vector", "result": [ { "metric": { "__name__": "metric_name", "source_id": "1" }, "value": [ 2.000, "99" ] } ] } }`)) }) }) Context("when a range query is made", func() { It("returns metrics from a simple query", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name", Value: 99, TimeInMilliseconds: 1500, Labels: map[string]string{ "source_id": "1", }, }, { Name: "metric_name", Value: 93, TimeInMilliseconds: 1700, Labels: map[string]string{ "source_id": "1", }, }, { Name: "metric_name", Value: 88, TimeInMilliseconds: 3800, Labels: map[string]string{ "source_id": "1", }, }, { Name: "metric_name", Value: 99, TimeInMilliseconds: 3500, Labels: map[string]string{ "source_id": "2", }, }, }, ) resp, err := makeRangeQuery(tc, testRangeQuery{ Query: "metric_name", StartInSeconds: "1", EndInSeconds: "5", StepDuration: "2", }) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status":"success", "data": { "resultType":"matrix", "result": [ { "metric": { "__name__": "metric_name", "source_id": "1" }, "values": [[3,"93"], [5,"88"]] }, { "metric": { "__name__": "metric_name", "source_id": "2" }, "values": [[5,"99"]] } ] } }`)) }) }) }) Context("when a labels query is made", func() { It("returns labels from Metric Store", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name_0", TimeInMilliseconds: 1, Labels: map[string]string{ "source_id": "1", "user_agent": "phil", }, }, { Name: "metric_name_1", TimeInMilliseconds: 2, Labels: map[string]string{ "source_id": "2", "content_length": "42", }, }, }, ) resp, err := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/labels") Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status":"success", "data":["__name__", "source_id"] }`)) }) }) Context("when a label values query is made", func() { It("returns values for a label name", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name_0", TimeInMilliseconds: 1, Labels: map[string]string{ "source_id": "1", "user_agent": "100", }, }, { Name: "metric_name_1", TimeInMilliseconds: 2, Labels: map[string]string{ "source_id": "10", "user_agent": "200", }, }, { Name: "metric_name_2", TimeInMilliseconds: 3, Labels: map[string]string{ "source_id": "10", "user_agent": "100", }, }, }, ) resp, err := testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/source_id/values") Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(Or( MatchJSON(`{ "status":"success", "data":["1", "10"] }`), MatchJSON(`{ "status":"success", "data":["10", "1"] }`), )) resp, err = testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/user_agent/values") Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err = ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status":"success", "data":[] }`)) resp, err = testing.MakeTLSReq(tc.gatewayAddr, "api/v1/label/__name__/values") Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err = ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status":"success", "data":["metric_name_0", "metric_name_1", "metric_name_2"] }`)) }) }) Context("when a series query is made", func() { It("returns metrics from a simple query", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name", Value: 99, TimeInMilliseconds: 1500, Labels: map[string]string{ "source_id": "1", }, }, }, ) resp, err := makeSeriesQuery(tc, testSeriesQuery{ Match: []string{"metric_name"}, StartInSeconds: "1", EndInSeconds: "2", }) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) body, err := ioutil.ReadAll(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(body).To(MatchJSON(`{ "status": "success", "data": [ { "__name__": "metric_name", "source_id": "1" } ] }`)) }) }) It("exposes metrics in prometheus format", func() { tc, cleanup := setup() defer cleanup() writePoints( tc, []testPoint{ { Name: "metric_name", TimeInMilliseconds: 1000, }, }, ) resp, err := http.Get(fmt.Sprintf("http://localhost:%s/metrics", tc.healthPort)) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) var parser expfmt.TextParser parsed, err := parser.TextToMetricFamilies(resp.Body) Expect(err).ToNot(HaveOccurred()) Expect(parsed).To(ContainCounterMetric("metric_store_ingress", float64(1))) }) })
package topic import ( "net/http" "gin_bbs/app/helpers" userModel "gin_bbs/app/models/user" "github.com/gin-gonic/gin" ) // UploadImage 上传图片 func UploadImage(c *gin.Context, currentUser *userModel.User) { data := gin.H{ "success": false, "msg": "上传失败", "file_path": "", } // 是否有上传文件 file, _ := c.FormFile("upload_file") if file != nil { path, err := helpers.SaveImage(file, "topics", currentUser.GetIDstring(), 1024) if err == nil { data = gin.H{ "success": true, "msg": "上传成功", "file_path": path, } } } c.JSON(http.StatusOK, data) }
package service import ( "encoding/json" "fmt" "log" "net/http" "time" "github.com/GeorgeMac/pontoon/build" "github.com/GeorgeMac/pontoon/jobs" "github.com/GeorgeMac/pontoon/monitor" "github.com/gorilla/mux" ) const BUILD_TIMEOUT time.Duration = 2 * time.Minute type Service struct { queue *jobs.JobQueue fact *build.BuildJobFactory store *jobs.Store router *mux.Router } func NewService(queue *jobs.JobQueue, fact *build.BuildJobFactory) (s *Service) { s = &Service{ queue: queue, fact: fact, router: mux.NewRouter(), store: jobs.NewStore(), } s.router.Methods("POST").Subrouter().HandleFunc("/jobs", s.submit) s.router.Methods("GET").Subrouter().HandleFunc("/jobs", s.list) s.router.Methods("POST").Subrouter().HandleFunc("/jobs/{id}", s.build) s.router.Methods("GET").Subrouter().HandleFunc("/jobs/{id}", s.job) return } func (s *Service) ServeHTTP(w http.ResponseWriter, req *http.Request) { s.router.ServeHTTP(w, req) } type BuildRequest struct { Name string `json:"name"` Url string `json:"url"` } type BuildResponse struct { Msg string `json:"message"` Status string `json:"status"` } func (s *Service) job(w http.ResponseWriter, req *http.Request) { id, ok := mux.Vars(req)["id"] if !ok { w.WriteHeader(http.StatusBadRequest) return } if err := json.NewEncoder(w).Encode(s.store.FullReport(id)); err != nil { w.WriteHeader(http.StatusInternalServerError) } } func (s *Service) list(w http.ResponseWriter, req *http.Request) { if err := json.NewEncoder(w).Encode(s.store.List()); err != nil { w.WriteHeader(http.StatusInternalServerError) } } func (s *Service) build(w http.ResponseWriter, req *http.Request) { id, ok := mux.Vars(req)["id"] if !ok { w.WriteHeader(http.StatusBadRequest) return } job, err := s.store.Get(id) if err != nil { w.WriteHeader(http.StatusNotFound) json.NewEncoder(w).Encode(&BuildResponse{ Msg: fmt.Sprintf("Build with name %s is missing", id), Status: monitor.UNKNOWN.String(), }) return } // push the job in to the build queue s.queue.Push(job) } func (s *Service) submit(w http.ResponseWriter, req *http.Request) { request := BuildRequest{} if err := json.NewDecoder(req.Body).Decode(&request); err != nil { w.WriteHeader(http.StatusBadRequest) log.Println(err.Error()) return } // get a build job from the factory bj, err := s.fact.NewJob(request.Name, request.Url) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err.Error()) return } // wrap in a jobs.Job job := jobs.NewJob(bj) if st := s.store.Report(request.Name); st.Status != "UNKNOWN" { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(&BuildResponse{ Msg: fmt.Sprintf("Build with name %s already exists", request.Name), Status: st.Status, }) return } if err := s.store.Put(request.Name, job); err != nil { w.WriteHeader(http.StatusInternalServerError) log.Println(err.Error()) return } }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package network import ( "context" "regexp" "time" "chromiumos/tast/common/hermesconst" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/faillog" "chromiumos/tast/local/chrome/uiauto/nodewith" "chromiumos/tast/local/chrome/uiauto/ossettings" "chromiumos/tast/local/chrome/uiauto/role" "chromiumos/tast/local/hermes" "chromiumos/tast/local/input" "chromiumos/tast/local/stork" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: CellularESimInstall, LacrosStatus: testing.LacrosVariantUnneeded, Desc: "Tests the add eSIM profile via activation code flow in the success and failure cases", Contacts: []string{ "hsuregan@google.com", "cros-connectivity@google.com@google.com", }, SoftwareDeps: []string{"chrome"}, Attr: []string{"group:cellular", "cellular_unstable", "cellular_sim_test_esim"}, Fixture: "cellular", Timeout: 9 * time.Minute, }) } func CellularESimInstall(ctx context.Context, s *testing.State) { euicc, slot, err := hermes.GetEUICC(ctx, true) if err != nil { s.Fatal("Failed to get test euicc: ", err) } // Remove any existing profiles on test euicc if err := euicc.DBusObject.Call(ctx, hermesconst.EuiccMethodResetMemory, 1).Err; err != nil { s.Fatal("Failed to reset test euicc: ", err) } defer euicc.DBusObject.Call(ctx, hermesconst.EuiccMethodResetMemory, 1) s.Log("Reset test euicc completed") if err := euicc.DBusObject.Call(ctx, hermesconst.EuiccMethodUseTestCerts, true).Err; err != nil { s.Fatal("Failed to set use test cert on eUICC: ", err) } s.Log("Set to use test cert on euicc completed") // Start a Chrome instance that will fetch policies from the FakeDMS. chromeOpts := []chrome.Option{ chrome.EnableFeatures("UseStorkSmdsServerAddress"), } if slot == 1 { s.Log("Append CellularUseSecondEuicc feature flag") chromeOpts = append(chromeOpts, chrome.EnableFeatures("CellularUseSecondEuicc")) } cr, err := chrome.New(ctx, chromeOpts...) if err != nil { s.Fatal("Chrome login failed: ", err) } defer cr.Close(ctx) tconn, err := cr.TestAPIConn(ctx) if err != nil { s.Fatal("Failed to connect Test API: ", err) } defer faillog.DumpUITreeOnError(ctx, s.OutDir(), s.HasError, tconn) mdp, err := ossettings.OpenMobileDataSubpage(ctx, tconn, cr) if err != nil { s.Fatal("Failed to open mobile data subpage: ", err) } if err := waitUntilRefreshProfileCompletes(ctx, tconn); err != nil { s.Fatal("Failed to wait until refresh profile complete: ", err) } activationCode, cleanupFunc, err := stork.FetchStorkProfile(ctx) if err != nil { s.Fatal("Failed to fetch Stork profile: ", err) } defer cleanupFunc(ctx) s.Log("Fetched Stork profile with activation code: ", activationCode) // Use an incorrect activation code. var couldNotInstallProfileText = nodewith.NameContaining("Couldn't install eSIM profile").Role(role.StaticText) var incorrectActivationCode = string(activationCode) + "wrong" if err := addESimWithActivationCode(ctx, tconn, incorrectActivationCode); err != nil { s.Fatal("Failed to add esim profile with incorrect activation code: ", err) } if err := uiauto.Combine("Exit add cellular eSIM flow after using incorrect activation code", mdp.WithTimeout(3*time.Minute).WaitUntilExists(couldNotInstallProfileText), mdp.LeftClick(ossettings.DoneButton.Focusable()), )(ctx); err != nil { s.Fatal("Incorrect activation code user journey fails: ", err) } // Use a correct activation code. var networkAddedText = nodewith.NameContaining("Network added").Role(role.StaticText) if err := addESimWithActivationCode(ctx, tconn, string(activationCode)); err != nil { s.Fatal("Failed to add esim profile with correct activation code: ", err) } if err := uiauto.Combine("Exit add cellular eSIM flow after using correct activation code", mdp.WithTimeout(3*time.Minute).WaitUntilExists(networkAddedText), mdp.LeftClick(ossettings.DoneButton.Focusable()), )(ctx); err != nil { s.Fatal("Correct activation code user journey fails: ", err) } if err := verifyTestESimProfile(ctx, tconn); err != nil { s.Fatal("Failed to verify newly installed stork profile: ", err) } } func waitUntilRefreshProfileCompletes(ctx context.Context, tconn *chrome.TestConn) error { ui := uiauto.New(tconn).WithTimeout(1 * time.Minute) refreshProfileText := nodewith.NameContaining("This may take a few minutes").Role(role.StaticText) if err := ui.WithTimeout(5 * time.Second).WaitUntilExists(refreshProfileText)(ctx); err == nil { if err := ui.WithTimeout(time.Minute).WaitUntilGone(refreshProfileText)(ctx); err != nil { return errors.Wrap(err, "failed to wait until refresh profile complete") } } return nil } func addESimWithActivationCode(ctx context.Context, tconn *chrome.TestConn, activationCode string) error { if err := waitUntilRefreshProfileCompletes(ctx, tconn); err != nil { return errors.Wrap(err, "failed to wait until refresh profile complete") } kb, err := input.Keyboard(ctx) if err != nil { return errors.Wrap(err, "failed to open the keyboard") } defer kb.Close() ui := uiauto.New(tconn).WithTimeout(1 * time.Minute) if err := ui.LeftClick(ossettings.AddCellularButton.Focusable())(ctx); err != nil { return errors.Wrap(err, "failed to click the Add Cellular Button") } var setupNewProfile = nodewith.NameContaining("Set up new profile").Role(role.Button).Focusable() if err := ui.WithTimeout(30 * time.Second).WaitUntilExists(setupNewProfile)(ctx); err == nil { if err := ui.LeftClick(setupNewProfile)(ctx); err != nil { return errors.Wrap(err, "failed to click set up new profile button") } } var activationCodeInput = nodewith.NameRegex(regexp.MustCompile("Activation code")).Focusable().First() if err := ui.WithTimeout(30 * time.Second).WaitUntilExists(activationCodeInput)(ctx); err != nil { return errors.Wrap(err, "failed to find activation code input field") } if err := ui.LeftClick(activationCodeInput)(ctx); err != nil { return errors.Wrap(err, "failed to find activation code input field") } if err := kb.Type(ctx, "LPA:"+activationCode); err != nil { return errors.Wrap(err, "could not type activation code") } if err := ui.LeftClick(ossettings.NextButton.Focusable())(ctx); err != nil { return errors.Wrap(err, "could not click Next button") } return nil } func verifyTestESimProfile(ctx context.Context, tconn *chrome.TestConn) error { if err := waitUntilRefreshProfileCompletes(ctx, tconn); err != nil { return errors.Wrap(err, "failed to wait until refresh profile complete") } ui := uiauto.New(tconn).WithTimeout(3 * time.Second) managedTestProfile := nodewith.NameRegex(regexp.MustCompile("^Network [0-9] of [0-9],.*")) // testProfileDetailButton is the finder for the "Test Profile" detail subpage arrow button in the mobile data page UI. var testProfileDetailButton = nodewith.ClassName("subpage-arrow").Role(role.Button).Ancestor(managedTestProfile.First()) if err := ui.WithTimeout(time.Minute).WaitUntilExists(testProfileDetailButton)(ctx); err != nil { return errors.Wrap(err, "failed to find the newly installed test profile") } if err := ui.LeftClick(testProfileDetailButton)(ctx); err != nil { return errors.Wrap(err, "failed to left click Test Profile detail button") } return nil }
/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <yazgazan@gmail.com> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. * Guillaume de Sagazan * ---------------------------------------------------------------------------- */ package main import ( "bufio" "flag" "fmt" "io" "os" "time" ) var start = time.Now() var last = time.Now() func getTimeStr(relative, delta bool, format string) string { if relative { return time.Since(start).String() } if delta { s := time.Since(last).String() last = time.Now() return s } return time.Now().Format(format) } func main() { relative := flag.Bool("relative", false, "log time relative to start") delta := flag.Bool("delta", false, "log time relative to last line") format := flag.String("format", "Mon Jan 2 15:04:05", "date format (see https://golang.org/pkg/time/#Time.Format)") flag.Parse() r := bufio.NewReader(os.Stdin) for { line, _, err := r.ReadLine() if err != nil { if err != io.EOF { fmt.Printf("got error %+v\n", err) } return } fmt.Printf("%s: %s\n", getTimeStr(*relative, *delta, *format), line) } }
// SPDX-License-Identifier: MIT package node import ( "reflect" "testing" "github.com/issue9/assert/v3" ) func TestParseValue(t *testing.T) { a := assert.New(t, false) v := ParseValue(reflect.ValueOf(intTag{})) a.Equal(v.Name, "number"). Equal(v.Usage, "usage-number"). False(v.Omitempty) v = ParseValue(reflect.ValueOf(struct{}{})) a.Nil(v) v = ParseValue(reflect.ValueOf(&struct { Value int `apidoc:"-"` }{})) a.Nil(v) a.Panic(func() { v = ParseValue(reflect.ValueOf(1)) }) }
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // This file was generated by swaggo/swag at // 2018-04-06 08:50:46.765267888 +0900 JST m=+0.025988291 package docs import ( "github.com/swaggo/swag" ) var doc = `{ "swagger": "2.0", "info": { "version": "1.0.0", "title": "Implement Data Caching Service using micro service architecture and deploy minikube environment using docker and Kubernetes tools.", "termsOfService": "http://swagger.io/terms/", "contact": { "name": "Swagger API Team", "email": "apiteam@swagger.io", "url": "http://swagger.io" }, "license": { "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" } }, "host": "localhost", "basePath": "/", "schemes": [ "http" ], "consumes": [ "application/json" ], "produces": [ "application/json" ], "paths": { "/readFromCache": { "get": { "description": "Returns the data from cache with provided pagination.\n", "operationId": "readFromCache", "parameters": [{ "name": "ID", "in": "query", "description": "ID to filter by", "required": false, "type": "string" }, { "name": "offset", "in": "query", "description": "starting point of results to return", "required": false, "type": "integer", "format": "int64" }, { "name": "limit", "in": "query", "description": "maximum number of results to return", "required": false, "type": "integer", "format": "int64" } ], "responses": { "200": { "description": "Persons from cache", "schema": { "type": "array", "items": { "$ref": "#/definitions/Person" } } } } } }, "/getFromDBAndStoreInCache": { "get": { "description": "Stores the data in persistance DB into Redis Cache.\n", "operationId": "getFromDBAndStoreInCache", "responses": { "200": { "description": "Stores people details from DB into cache" } } } } }, "definitions": { "Person": { "type": "object", "properties": { "_id": { "type": "string" }, "firstname": { "type": "string" }, "lastname": { "type": "string" } } } } }` type s struct{} func (s *s) ReadDoc() string { return doc } func init() { swag.Register(swag.Name, &s{}) }
package main import "fmt" func main() { var i = 3 var j = 20 movij( &i , &j ) fmt.Println(i,j) } func movij( i , j ...*int) { var mid int mid = *i *i = *j *j = mid }
package lib import "github.com/gabrielperezs/goreactor/reactorlog" // Input is the interface for the Input plugins type Input interface { // Put(m Msg) error //Delete(m Msg) error Done(m Msg, status bool) // Input was processed and don't need to keep it as pending Stop() // Stop accepting input Exit() // Exit from the loop } // Output is the interface for the Output plugins type Output interface { MatchConditions(a Msg) error Run(rl reactorlog.ReactorLog, a Msg) error Exit() } // LogStreams is the inteface to send logs to stram services type LogStream interface { Send(b []byte) Exit() }
package main import "strings" /* /home/../../sub/./ */ func simplifyPath(path string) string { dirs := strings.Split(path, "/") var canonicalPath []string for _, d := range dirs { if d == "" || d == "." { continue } if d == ".." { if len(canonicalPath) > 0 { canonicalPath = canonicalPath[:len(canonicalPath)-1] } continue } canonicalPath = append(canonicalPath, d) } return "/" + strings.Join(canonicalPath, "/") }
package main import "fmt" func main() { // Unsigned integer types: var x uint8 = 0 var x uint16 = 0 var x uint32 = 0 var x uint64 = 0 // Signed integer types: var x int8 = -1 // aka "byte" var x int32 = -1 // aka "rune" var x int64 = -1 // Floating point types: var x float32 = 1.0 // "single precision" var x float64 = 1.0 // "double precision" // Complex types: var x complex64 = 1 + 1i var x complex128 = 1 + 1i // Booleans: var x bool = true var x bool = false // Strings: var x string = "string" // Machine dependent units: var x int = -1 var x uint = 0 var x uintptr }
package main /* int fortytwo(void); #include "main.h" int mul(int, int); */ import "C" import "unsafe" func main() { println("fortytwo:", C.fortytwo()) println("add:", C.add(C.int(3), 5)) var x C.myint = 3 println("myint:", x, C.myint(5)) println("myint size:", int(unsafe.Sizeof(x))) var y C.longlong = -(1 << 40) println("longlong:", y) println("global:", C.global) var ptr C.intPointer var n C.int = 15 ptr = C.intPointer(&n) println("15:", *ptr) C.store(25, &n) println("25:", *ptr) cb := C.binop_t(C.add) println("callback 1:", C.doCallback(20, 30, cb)) cb = C.binop_t(C.mul) println("callback 2:", C.doCallback(20, 30, cb)) // more globals println("bool:", C.globalBool, C.globalBool2 == true) println("float:", C.globalFloat) println("double:", C.globalDouble) println("complex float:", C.globalComplexFloat) println("complex double:", C.globalComplexDouble) println("complex long double:", C.globalComplexLongDouble) } //export mul func mul(a, b C.int) C.int { return a * b }
package odoo import ( "fmt" ) // BaseImportTestsModelsChar represents base_import.tests.models.char model. type BaseImportTestsModelsChar struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` CreateDate *Time `xmlrpc:"create_date,omptempty"` CreateUid *Many2One `xmlrpc:"create_uid,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` Value *String `xmlrpc:"value,omptempty"` WriteDate *Time `xmlrpc:"write_date,omptempty"` WriteUid *Many2One `xmlrpc:"write_uid,omptempty"` } // BaseImportTestsModelsChars represents array of base_import.tests.models.char model. type BaseImportTestsModelsChars []BaseImportTestsModelsChar // BaseImportTestsModelsCharModel is the odoo model name. const BaseImportTestsModelsCharModel = "base_import.tests.models.char" // Many2One convert BaseImportTestsModelsChar to *Many2One. func (btmc *BaseImportTestsModelsChar) Many2One() *Many2One { return NewMany2One(btmc.Id.Get(), "") } // CreateBaseImportTestsModelsChar creates a new base_import.tests.models.char model and returns its id. func (c *Client) CreateBaseImportTestsModelsChar(btmc *BaseImportTestsModelsChar) (int64, error) { ids, err := c.CreateBaseImportTestsModelsChars([]*BaseImportTestsModelsChar{btmc}) if err != nil { return -1, err } if len(ids) == 0 { return -1, nil } return ids[0], nil } // CreateBaseImportTestsModelsChar creates a new base_import.tests.models.char model and returns its id. func (c *Client) CreateBaseImportTestsModelsChars(btmcs []*BaseImportTestsModelsChar) ([]int64, error) { var vv []interface{} for _, v := range btmcs { vv = append(vv, v) } return c.Create(BaseImportTestsModelsCharModel, vv) } // UpdateBaseImportTestsModelsChar updates an existing base_import.tests.models.char record. func (c *Client) UpdateBaseImportTestsModelsChar(btmc *BaseImportTestsModelsChar) error { return c.UpdateBaseImportTestsModelsChars([]int64{btmc.Id.Get()}, btmc) } // UpdateBaseImportTestsModelsChars updates existing base_import.tests.models.char records. // All records (represented by ids) will be updated by btmc values. func (c *Client) UpdateBaseImportTestsModelsChars(ids []int64, btmc *BaseImportTestsModelsChar) error { return c.Update(BaseImportTestsModelsCharModel, ids, btmc) } // DeleteBaseImportTestsModelsChar deletes an existing base_import.tests.models.char record. func (c *Client) DeleteBaseImportTestsModelsChar(id int64) error { return c.DeleteBaseImportTestsModelsChars([]int64{id}) } // DeleteBaseImportTestsModelsChars deletes existing base_import.tests.models.char records. func (c *Client) DeleteBaseImportTestsModelsChars(ids []int64) error { return c.Delete(BaseImportTestsModelsCharModel, ids) } // GetBaseImportTestsModelsChar gets base_import.tests.models.char existing record. func (c *Client) GetBaseImportTestsModelsChar(id int64) (*BaseImportTestsModelsChar, error) { btmcs, err := c.GetBaseImportTestsModelsChars([]int64{id}) if err != nil { return nil, err } if btmcs != nil && len(*btmcs) > 0 { return &((*btmcs)[0]), nil } return nil, fmt.Errorf("id %v of base_import.tests.models.char not found", id) } // GetBaseImportTestsModelsChars gets base_import.tests.models.char existing records. func (c *Client) GetBaseImportTestsModelsChars(ids []int64) (*BaseImportTestsModelsChars, error) { btmcs := &BaseImportTestsModelsChars{} if err := c.Read(BaseImportTestsModelsCharModel, ids, nil, btmcs); err != nil { return nil, err } return btmcs, nil } // FindBaseImportTestsModelsChar finds base_import.tests.models.char record by querying it with criteria. func (c *Client) FindBaseImportTestsModelsChar(criteria *Criteria) (*BaseImportTestsModelsChar, error) { btmcs := &BaseImportTestsModelsChars{} if err := c.SearchRead(BaseImportTestsModelsCharModel, criteria, NewOptions().Limit(1), btmcs); err != nil { return nil, err } if btmcs != nil && len(*btmcs) > 0 { return &((*btmcs)[0]), nil } return nil, fmt.Errorf("base_import.tests.models.char was not found with criteria %v", criteria) } // FindBaseImportTestsModelsChars finds base_import.tests.models.char records by querying it // and filtering it with criteria and options. func (c *Client) FindBaseImportTestsModelsChars(criteria *Criteria, options *Options) (*BaseImportTestsModelsChars, error) { btmcs := &BaseImportTestsModelsChars{} if err := c.SearchRead(BaseImportTestsModelsCharModel, criteria, options, btmcs); err != nil { return nil, err } return btmcs, nil } // FindBaseImportTestsModelsCharIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindBaseImportTestsModelsCharIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(BaseImportTestsModelsCharModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindBaseImportTestsModelsCharId finds record id by querying it with criteria. func (c *Client) FindBaseImportTestsModelsCharId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(BaseImportTestsModelsCharModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("base_import.tests.models.char was not found with criteria %v and options %v", criteria, options) }
// This file is part of CycloneDX GoMod // // 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. // // SPDX-License-Identifier: Apache-2.0 // Copyright (c) OWASP Foundation. All Rights Reserved. package sbom import ( "crypto/md5" // #nosec G501 "crypto/sha1" // #nosec G505 "crypto/sha256" "crypto/sha512" "fmt" "hash" "io" "os" "strings" "golang.org/x/crypto/sha3" cdx "github.com/CycloneDX/cyclonedx-go" "github.com/CycloneDX/cyclonedx-gomod/internal/gocmd" "github.com/CycloneDX/cyclonedx-gomod/internal/gomod" "github.com/CycloneDX/cyclonedx-gomod/internal/version" "github.com/rs/zerolog/log" ) func BuildDependencyGraph(modules []gomod.Module) []cdx.Dependency { depGraph := make([]cdx.Dependency, 0) for _, module := range modules { if module.Replace != nil { module = *module.Replace } cdxDependant := cdx.Dependency{Ref: module.PackageURL()} if module.Dependencies != nil { cdxDependencies := make([]cdx.Dependency, len(module.Dependencies)) for i := range module.Dependencies { if module.Dependencies[i].Replace != nil { cdxDependencies[i] = cdx.Dependency{Ref: module.Dependencies[i].Replace.PackageURL()} } else { cdxDependencies[i] = cdx.Dependency{Ref: module.Dependencies[i].PackageURL()} } } if len(cdxDependencies) > 0 { cdxDependant.Dependencies = &cdxDependencies } } depGraph = append(depGraph, cdxDependant) } return depGraph } func BuildToolMetadata() (*cdx.Tool, error) { toolExePath, err := os.Executable() if err != nil { return nil, err } toolHashes, err := CalculateFileHashes(toolExePath, cdx.HashAlgoMD5, cdx.HashAlgoSHA1, cdx.HashAlgoSHA256, cdx.HashAlgoSHA384, cdx.HashAlgoSHA512) if err != nil { return nil, fmt.Errorf("failed to calculate tool hashes: %w", err) } return &cdx.Tool{ Vendor: version.Author, Name: version.Name, Version: version.Version, Hashes: &toolHashes, }, nil } func BuildStdComponent(goVersion string) (*cdx.Component, error) { log.Debug(). Msg("building std component") var err error if goVersion == "" { goVersion, err = gocmd.GetVersion() if err != nil { return nil, fmt.Errorf("failed to determine Go version: %w", err) } goVersion = strings.TrimPrefix(goVersion, "go") } stdPURL := "pkg:golang/std@" + goVersion return &cdx.Component{ BOMRef: stdPURL, Type: cdx.ComponentTypeLibrary, Name: "std", Version: goVersion, Description: "The Go standard library", Scope: cdx.ScopeRequired, PackageURL: stdPURL, ExternalReferences: &[]cdx.ExternalReference{ { Type: cdx.ERTypeDocumentation, URL: "https://golang.org/pkg/", }, { Type: cdx.ERTypeVCS, URL: "https://go.googlesource.com/go", }, { Type: cdx.ERTypeWebsite, URL: "https://golang.org/", }, }, }, nil } func CalculateFileHashes(filePath string, algos ...cdx.HashAlgorithm) ([]cdx.Hash, error) { if len(algos) == 0 { return make([]cdx.Hash, 0), nil } log.Debug(). Str("file", filePath). Interface("algos", algos). Msg("calculating file hashes") hashMap := make(map[cdx.HashAlgorithm]hash.Hash) hashWriters := make([]io.Writer, 0) for _, algo := range algos { var hashWriter hash.Hash switch algo { //exhaustive:ignore case cdx.HashAlgoMD5: hashWriter = md5.New() // #nosec G401 case cdx.HashAlgoSHA1: hashWriter = sha1.New() // #nosec G401 case cdx.HashAlgoSHA256: hashWriter = sha256.New() case cdx.HashAlgoSHA384: hashWriter = sha512.New384() case cdx.HashAlgoSHA512: hashWriter = sha512.New() case cdx.HashAlgoSHA3_256: hashWriter = sha3.New256() case cdx.HashAlgoSHA3_512: hashWriter = sha3.New512() default: return nil, fmt.Errorf("unsupported hash algorithm: %s", algo) } hashWriters = append(hashWriters, hashWriter) hashMap[algo] = hashWriter } file, err := os.Open(filePath) if err != nil { return nil, err } defer file.Close() multiWriter := io.MultiWriter(hashWriters...) if _, err = io.Copy(multiWriter, file); err != nil { return nil, err } file.Close() cdxHashes := make([]cdx.Hash, 0, len(hashMap)) for _, algo := range algos { // Don't iterate over hashMap, as it doesn't retain order cdxHashes = append(cdxHashes, cdx.Hash{ Algorithm: algo, Value: fmt.Sprintf("%x", hashMap[algo].Sum(nil)), }) } return cdxHashes, nil } const PropertyPrefix = "cdx:gomod" func NewProperty(name, value string) cdx.Property { return cdx.Property{ Name: fmt.Sprintf("%s:%s", PropertyPrefix, name), Value: value, } }
package main import ( "bufio" "bytes" "code.google.com/p/mahonia" "io/ioutil" "log" "os" "regexp" "strconv" "time" ) const DAT_MAX_SIZE = 512 * 1024 var RegsLine = regexp.MustCompile(`(\d+)\.dat<>(?:.*\s\((\d+)\))`) func main() { path := "/2ch/dat" dir, err := ioutil.ReadDir(path) if err != nil { log.Fatal(err) } for _, it := range dir { if it.IsDir() { // ディレクトリの場合 index(path + "/" + it.Name()) } } } func index(path string) { sub, err := ioutil.ReadFile(path + "/subject.txt") if err != nil { return } count := 0 linecount := 0 now := time.Now().Unix() restart := time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC) scanner := bufio.NewScanner(mahonia.NewDecoder("cp932").NewReader(bytes.NewReader(sub))) for scanner.Scan() { m := RegsLine.FindStringSubmatch(scanner.Text()) if m == nil { continue } linecount++ rescount, _ := strconv.ParseInt(m[2], 10, 64) l := len(m[1]) if l >= 9 && l <= 10 && rescount < 1000 { p := path + "/" + m[1][:4] + "/" + m[1] + ".dat" stat, err := os.Stat(p) if err == nil { if (stat.Size() < DAT_MAX_SIZE) && (stat.ModTime().Unix() > now) { // 時間改変 os.Chtimes(p, restart, restart) count++ } } } } log.Printf("Line:%d\tCount:%d\tPath:%s", linecount, count, path) }
package main import ( "database/sql" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" _ "github.com/go-sql-driver/mysql" "github.com/labstack/echo" "github.com/patrickmn/go-cache" articleDelivery "github.com/sesha04/test_kumparan/article/delivery" articleRepo "github.com/sesha04/test_kumparan/article/repository" articleUsecase "github.com/sesha04/test_kumparan/article/usecase" ) type mysqlConfig struct { Username string Password string Host string DbName string Charset string Pool int } func newMysql() (*sql.DB, error) { db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=True", "root", "root", "127.0.0.1", "test_kumparan", "utf8"), ) if err != nil { return nil, err } db.SetMaxIdleConns(50) db.SetConnMaxLifetime(300 * time.Second) err = db.Ping() return db, err } func main() { e := echo.New() db, err := newMysql() if err != nil { log.Fatal(err) } defer func() { err := db.Close() if err != nil { log.Fatal(err) } }() ar := articleRepo.NewArticleRepository(db) au := articleUsecase.NewArticleUsecase(ar) ac := cache.New(5*time.Minute, 10*time.Minute) articleDelivery.NewArticleHandler(e, au, ac) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) go func(*echo.Echo) { if serr := e.Start(":8080"); serr != http.ErrServerClosed { log.Fatal(serr) } }(e) <-sigChan log.Println("\nShutting down...") }
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package fed import ( "fmt" "os" "path/filepath" "strings" "testing" "github.com/moov-io/base" "github.com/stretchr/testify/require" ) // loadTestWireFiles returns two WIREDictionary, one from the JSON source file // and other from the plaintext source file. func loadTestWireFiles(t *testing.T) (*WIREDictionary, *WIREDictionary) { t.Helper() open := func(path string) *WIREDictionary { f, err := os.Open(path) if err != nil { t.Fatalf("%T: %s", err, err) } t.Cleanup(func() { f.Close() }) dict := NewWIREDictionary() if err := dict.Read(f); err != nil { t.Fatalf("%T: %s", err, err) } return dict } jsonDict := open(filepath.Join("data", "fpddir.json")) plainDict := open(filepath.Join("data", "fpddir.txt")) return jsonDict, plainDict } func TestWIREParseParticipant(t *testing.T) { var line = "325280039MAC FCU MAC FEDERAL CREDIT UNION AKFAIRBANKS Y Y20180629" f := NewWIREDictionary() f.Read(strings.NewReader(line)) if fi, ok := f.IndexWIRERoutingNumber["325280039"]; ok { if fi.RoutingNumber != "325280039" { t.Errorf("Expected `325280039` got : %s", fi.RoutingNumber) } if fi.TelegraphicName != "MAC FCU" { t.Errorf("Expected `MAC FCU` got : %s", fi.TelegraphicName) } if fi.CustomerName != "MAC FEDERAL CREDIT UNION" { t.Errorf("Expected `MAC FEDERAL CREDIT UNION` got : %s", fi.CustomerName) } if fi.WIRELocation.State != "AK" { t.Errorf("Expected `AK` got ; %s", fi.State) } if fi.WIRELocation.City != "FAIRBANKS" { t.Errorf("Expected `FAIRBANKS` got : %s", fi.City) } if fi.FundsTransferStatus != "Y" { t.Errorf("Expected `Y` got : %s", fi.FundsTransferStatus) } if fi.FundsSettlementOnlyStatus != " " { t.Errorf("Expected ` ` got : %s", fi.FundsSettlementOnlyStatus) } if fi.BookEntrySecuritiesTransferStatus != "Y" { t.Errorf("Expected `Y` got : %s", fi.BookEntrySecuritiesTransferStatus) } if fi.Date != "20180629" { t.Errorf("Expected `20180629` got : %s", fi.Date) } } else { t.Errorf("routing number `325280039` not found") } } func TestWIREDirectoryRead(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { if fi, ok := dict.IndexWIRERoutingNumber["325280039"]; ok { if fi.TelegraphicName != "MAC FCU" { t.Errorf("Expected `MAC FCU` got : %s", fi.TelegraphicName) } } else { t.Errorf("routing number `325280039` not found") } } if len(jsonDict.WIREParticipants) != 10 { t.Errorf("Expected '7693' got: %v", len(jsonDict.WIREParticipants)) } check(t, "json", jsonDict) if len(plainDict.WIREParticipants) != 7693 { t.Errorf("Expected '7693' got: %v", len(plainDict.WIREParticipants)) } check(t, "plain", plainDict) } func TestWIREInvalidRecordLength(t *testing.T) { var line = "325280039MAC FCU MAC FEDERAL CREDIT UNION" f := NewWIREDictionary() if err := f.Read(strings.NewReader(line)); err != nil { if !base.Has(err, NewRecordWrongLengthErr(101, 51)) { t.Errorf("%T: %s", err, err) } } } // TestWIRERoutingNumberSearch tests that a valid routing number defined in FedWIREDir returns the participant data func TestWIRERoutingNumberSearchSingle(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.RoutingNumberSearchSingle("324172465") if fi == nil { t.Fatalf("wire routing number `324172465` not found") } if fi.CustomerName != "TRUGROCER FEDERAL CREDIT UNION" { t.Errorf("Expected `TRUGROCER FEDERAL CREDIT UNION` got : %s", fi.CustomerName) } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestInvalidWIRERoutingNumberSearch tests that an invalid routing number returns nil func TestInvalidWIRERoutingNumberSearchSingle(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.RoutingNumberSearchSingle("325183657") if fi != nil { t.Errorf("%s", "325183657 should have returned nil") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIREFinancialInstitutionSearch tests that a Financial Institution defined in FedWIREDir returns the participant // data func TestWIREFinancialInstitutionSearchSingle(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearchSingle("TRUGROCER FEDERAL CREDIT UNION") if fi == nil { t.Fatalf("wire financial institution `TRUGROCER FEDERAL CREDIT UNION` not found") } for _, f := range fi { if f.CustomerName != "TRUGROCER FEDERAL CREDIT UNION" { t.Errorf("TRUGROCER FEDERAL CREDIT UNION` got : %v", f.CustomerName) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestInvalidWIREFinancialInstitutionSearchSingle tests that a Financial Institution defined in FedWIREDir returns // the participant data func TestInvalidWIREFinancialInstitutionSearchSingle(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearchSingle("XYZ") if fi != nil { t.Errorf("%s", "XYZ should have returned nil") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRERoutingNumberSearch tests that routing number search returns nil or FEDWIRE participant data func TestWIRERoutingNumberSearch(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi, err := dict.RoutingNumberSearch("325", 1) if err != nil { t.Fatalf("%T: %s", err, err) } if len(fi) == 0 { t.Errorf("%s", "325 should have returned values") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRERoutingNumberSearch02 tests string `02` returns results func TestWIRERoutingNumberSearch02(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi, err := dict.RoutingNumberSearch("02", 1) if err != nil { t.Fatalf("%T: %s", err, err) } if len(fi) == 0 { t.Fatalf("02 should have returned values") } } _ = jsonDict // check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRERoutingNumberSearchMinimumLength tests that routing number search returns a RecordWrongLengthErr if the // length of the string passed in is less than 2. func TestWIRERoutingNumberSearchMinimumLength(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { if _, err := dict.RoutingNumberSearch("0", 1); err != nil { if !base.Has(err, NewRecordWrongLengthErr(2, 1)) { t.Errorf("%T: %s", err, err) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestInvalidWIRERoutingNumberSearch tests that routing number returns nil for an invalid RoutingNumber. func TestInvalidWIRERoutingNumberSearch(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi, err := dict.RoutingNumberSearch("777777777", 1) if err != nil { t.Fatalf("%T: %s", err, err) } if len(fi) != 0 { t.Fatal("wire routing number search should have returned nil") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRERoutingNumberMaximumLength tests that routing number search returns a RecordWrongLengthErr if the // length of the string passed in is greater than 9. func TestWIRERoutingNumberSearchMaximumLength(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { if _, err := dict.RoutingNumberSearch("1234567890", 1); err != nil { if !base.Has(err, NewRecordWrongLengthErr(9, 10)) { t.Errorf("%T: %s", err, err) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRERoutingNumberNumeric tests that routing number search returns an ErrRoutingNumberNumeric if the // string passed in is not numeric. func TestWIRERoutingNumberNumeric(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { if _, err := dict.RoutingNumberSearch("1 S5", 1); err != nil { if !base.Has(err, ErrRoutingNumberNumeric) { t.Errorf("%T: %s", err, err) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } func TestWIREParsingError(t *testing.T) { var line = "011000536FHLB BOSTON FEDERAL HOME LOAN BANK MABOSTON © Y20170818" f := NewWIREDictionary() if err := f.Read(strings.NewReader(line)); err != nil { if !base.Has(err, NewRecordWrongLengthErr(101, 51)) { t.Errorf("%T: %s", err, err) } } } func TestWIREFinancialInstitutionSearch__Examples(t *testing.T) { _, plainDict := loadTestWireFiles(t) cases := []struct { input string expected *ACHParticipant }{ { input: "Chase", expected: &ACHParticipant{ RoutingNumber: "021000021", CustomerName: "JPMORGAN CHASE BANK, NA", }, }, { input: "Wells", expected: &ACHParticipant{ RoutingNumber: "101205940", CustomerName: "WELLS BANK", }, }, { input: "Wells Fargo", expected: &ACHParticipant{ RoutingNumber: "021052943", CustomerName: "WELLS FARGO GNMA-P&I", }, }, } for i := range cases { // The plain dictionary has 18k records, so search is more realistic results := plainDict.FinancialInstitutionSearch(cases[i].input, 1) require.Equal(t, fmt.Sprintf("#%d = 1", i), fmt.Sprintf("#%d = %d", i, len(results))) require.Equal(t, cases[i].expected.RoutingNumber, results[0].RoutingNumber) require.Equal(t, cases[i].expected.CustomerName, results[0].CustomerName) } } // TestWIREFinancialInstitutionSearch tests search string `First Bank` func TestWIREFinancialInstitutionSearch(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearch("First Bank", 1) if len(fi) == 0 { t.Fatalf("No Financial Institutions matched your search query") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIREFinancialInstitutionFarmers tests search string `FaRmerS` func TestWIREFinancialInstitutionFarmers(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearch("FaRmerS", 1) if len(fi) == 0 { t.Fatalf("No Financial Institutions matched your search query") } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRESearchStateFilter tests search string `Farmers State Bank` and filters by the state of North Carolina, `NC` func TestWIRESearchStateFilter(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearch("Farmers State Bank", 100) if len(fi) == 0 { t.Fatalf("No Financial Institutions matched your search query") } filter := dict.WIREParticipantStateFilter(fi, "NC") if len(filter) == 0 { t.Fatalf("No Financial Institutions matched your search query") } for _, loc := range filter { if loc.WIRELocation.State != "NC" { t.Errorf("Expected `NC` got : %s", loc.WIRELocation.State) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIRESearchCityFilter tests search string `Farmers State Bank` and filters by the city of `SALISBURY` func TestWIRESearchCityFilter(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { fi := dict.FinancialInstitutionSearch("Farmers State Bank", 100) if len(fi) == 0 { t.Fatalf("No Financial Institutions matched your search query") } filter := dict.WIREParticipantCityFilter(fi, "SALISBURY") if len(filter) == 0 { t.Fatalf("No Financial Institutions matched your search query") } for _, loc := range filter { if loc.WIRELocation.City != "SALISBURY" { t.Errorf("Expected `SALISBURY` got : %s", loc.WIRELocation.City) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIREDictionaryStateFilter tests filtering WIREDictionary.WIREParticipants by the state of `PA` func TestWIREDictionaryStateFilter(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { filter := dict.StateFilter("pa") if len(filter) == 0 { t.Fatalf("No Financial Institutions matched your search query") } for _, loc := range filter { if loc.WIRELocation.State != "PA" { t.Errorf("Expected `PA` got : %s", loc.WIRELocation.State) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) } // TestWIREDictionaryCityFilter tests filtering WIREDictionary.WIREParticipants by the city of `Reading` func TestWIREDictionaryCityFilter(t *testing.T) { jsonDict, plainDict := loadTestWireFiles(t) check := func(t *testing.T, kind string, dict *WIREDictionary) { filter := dict.CityFilter("Reading") if len(filter) == 0 { t.Fatalf("No Financial Institutions matched your search query") } for _, loc := range filter { if loc.WIRELocation.City != "READING" { t.Errorf("Expected `READING` got : %s", loc.WIRELocation.City) } } } check(t, "json", jsonDict) check(t, "plain", plainDict) }
package postgres import ( "context" "database/sql" "fmt" "github.com/guregu/null" "github.com/pganalyze/collector/state" ) const functionsSQLDefaultKindFields = "CASE WHEN pp.proisagg THEN 'a' WHEN pp.proiswindow THEN 'w' ELSE 'f' END AS prokind" const functionsSQLpg11KindFields = "pp.prokind" const functionsSQL string = ` SELECT pp.oid, pn.nspname, pp.proname, pl.lanname, pp.prosrc, pp.probin, pp.proconfig, pg_catalog.pg_get_function_arguments(pp.oid), COALESCE(pg_catalog.pg_get_function_result(pp.oid), ''), %s, pp.prosecdef, pp.proleakproof, pp.proisstrict, pp.proretset, pp.provolatile FROM pg_catalog.pg_proc pp INNER JOIN pg_catalog.pg_namespace pn ON (pp.pronamespace = pn.oid) INNER JOIN pg_catalog.pg_language pl ON (pp.prolang = pl.oid) WHERE pn.nspname NOT IN ('pg_catalog', 'information_schema') AND pp.oid NOT IN (SELECT pd.objid FROM pg_catalog.pg_depend pd WHERE pd.deptype = 'e' AND pd.classid = 'pg_catalog.pg_proc'::regclass) AND ($1 = '' OR (pn.nspname || '.' || pp.proname) !~* $1)` const functionStatsSQL string = ` SELECT funcid, calls, total_time, self_time FROM pg_stat_user_functions psuf INNER JOIN pg_catalog.pg_proc pp ON (psuf.funcid = pp.oid) INNER JOIN pg_catalog.pg_namespace pn ON (pp.pronamespace = pn.oid) WHERE pn.nspname NOT IN ('pg_catalog', 'information_schema') AND pp.oid NOT IN (SELECT pd.objid FROM pg_catalog.pg_depend pd WHERE pd.deptype = 'e' AND pd.classid = 'pg_catalog.pg_proc'::regclass) AND ($1 = '' OR (pn.nspname || '.' || pp.proname) !~* $1)` func GetFunctions(ctx context.Context, db *sql.DB, postgresVersion state.PostgresVersion, currentDatabaseOid state.Oid, ignoreRegexp string) ([]state.PostgresFunction, error) { var kindFields string if postgresVersion.Numeric >= state.PostgresVersion11 { kindFields = functionsSQLpg11KindFields } else { kindFields = functionsSQLDefaultKindFields } stmt, err := db.PrepareContext(ctx, QueryMarkerSQL+fmt.Sprintf(functionsSQL, kindFields)) if err != nil { return nil, err } defer stmt.Close() rows, err := stmt.QueryContext(ctx, ignoreRegexp) if err != nil { return nil, err } defer rows.Close() var functions []state.PostgresFunction for rows.Next() { var row state.PostgresFunction var config null.String err := rows.Scan(&row.Oid, &row.SchemaName, &row.FunctionName, &row.Language, &row.Source, &row.SourceBin, &config, &row.Arguments, &row.Result, &row.Kind, &row.SecurityDefiner, &row.Leakproof, &row.Strict, &row.ReturnsSet, &row.Volatile) if err != nil { return nil, err } row.DatabaseOid = currentDatabaseOid row.Config = unpackPostgresStringArray(config) functions = append(functions, row) } if err = rows.Err(); err != nil { return nil, err } return functions, nil } func GetFunctionStats(ctx context.Context, db *sql.DB, postgresVersion state.PostgresVersion, ignoreRegexp string) (functionStats state.PostgresFunctionStatsMap, err error) { stmt, err := db.PrepareContext(ctx, QueryMarkerSQL+functionStatsSQL) if err != nil { err = fmt.Errorf("FunctionStats/Prepare: %s", err) return } defer stmt.Close() rows, err := stmt.QueryContext(ctx, ignoreRegexp) if err != nil { err = fmt.Errorf("FunctionStats/Query: %s", err) return } defer rows.Close() functionStats = make(state.PostgresFunctionStatsMap) for rows.Next() { var oid state.Oid var stats state.PostgresFunctionStats err = rows.Scan(&oid, &stats.Calls, &stats.TotalTime, &stats.SelfTime) if err != nil { err = fmt.Errorf("FunctionStats/Scan: %s", err) return } functionStats[oid] = stats } if err = rows.Err(); err != nil { err = fmt.Errorf("FunctionStats/Rows: %s", err) return } return }
package goutilmod func Max(a int, b int) int { if a > b { return a } else { return b } } func Min(a int, b int) int { if a > b { return b } else { return a } } func MaxThree(a int, b int, c int) int { if a > b { if a > c { return a } else { return c } } else { if b > c { return b } else { return c } } } func MinThree(a int, b int, c int) int { if a < b { if a < c { return a } else { return c } } else { if b < c { return b } else { return c } } }
package gate import ( "github.com/wudiliujie/common/gate" "github.com/wudiliujie/common/log" "github.com/wudiliujie/common/module" "yxlserver/services/I/eventcode" "yxlserver/services/conf" "yxlserver/services/gconf" "yxlserver/services/msg" ) var Module = new(GateModule) var netEvent = new(gate.NetEvent) func init() { gconf.Processor = msg.Processor netEvent.OnAgentInit = onAgentInit netEvent.OnAgentDestroy = onAgentDestroy netEvent.OnReceiveMsg = onReceiveMsg netEvent.Processor = gconf.Processor } type GateModule struct { *gate.Gate } func (m *GateModule) OnInit() { m.Gate = &gate.Gate{ MaxConnNum: conf.Server.MaxConnNum, WSAddr: conf.Server.WSAddr, PendingWriteNum: gconf.PendingWriteNum, MaxMsgLen: gconf.MaxMsgLen, HTTPTimeout: gconf.HTTPTimeout, //CertFile: conf.Server.CertFile, //KeyFile: conf.Server.KeyFile, //TCPAddr: conf.Server.TCPAddr, LenMsgLen: gconf.LenMsgLen, LittleEndian: gconf.LittleEndian, GoLen: gconf.AgentGoLen, TimerDispatcherLen: gconf.AgentTimerDispatcherLen, AsynCallLen: gconf.AgentAsyncCallLen, ChanRPCLen: gconf.AgentChanRPCLen, NetEvent: netEvent, } } func onAgentInit(agent gate.Agent) { log.Debug("客户端连接:%v", agent.RemoteAddr()) //怎么通知 module.OnChanRpcEvent(eventcode.Net_AgentInit, agent) } func onAgentDestroy(agent gate.Agent) { log.Debug("客户端断开连接:%v", agent.RemoteAddr()) module.OnChanRpcEvent(eventcode.Net_AgentDestroy, agent) } func (m *GateModule) OnDestroy() { log.Debug("销毁Gate") } func (m *GateModule) Debug() { log.Debug("gate") } func onReceiveMsg(agent gate.Agent, data []byte) { if gconf.Processor != nil { if len(data) < 4 { log.Debug("长度不够") return } //根据agent类型不同,解析不同的头部 pck, err := gconf.Processor.Unmarshal(data[2:]) if err != nil { log.Error("onReceiveMsg %v", err) } log.Debug("*******************%v", pck) module.OnChanRpcEvent(eventcode.Net_ReceiveMsg, agent, pck.GetId(), pck) } }
package config // Config represents Application global config. type Config struct { OpenAPIURL string DateFormat string ServiceKey string Port string }
package service import ( "crypto/md5" "encoding/hex" "encoding/json" "fmt" "shared/common" "shared/utility/errors" "shared/utility/httputil" "shared/utility/servertime" "sort" "strings" ) var koMoeSessionVerifyUrl = "%s/api/server/session.verify" // KoMoe 小萌sdk/* type KoMoe struct { host string // 请求host spareHost string // 备用host GP *KoMoeAppConfig // google play IOS *KoMoeAppConfig // ios } type KoMoeAppConfig struct { game_id int //游戏id,[参数表]中为CP分配的game_id merchant_id int //商户id,[参数表]中为CP分配的merchant_id secretKey string } func (ko *KoMoe) getSessionVerifyUrl() string { return ko.getSessionVerifyUrl_(false) } func (ko *KoMoe) getSessionVerifyUrl_(spare bool) string { host := ko.host if spare { host = ko.spareHost } return fmt.Sprintf(koMoeSessionVerifyUrl, host) } type PublicResponse struct { Timestamp int64 `json:"timestamp"` // 时间戳(毫秒),对应request的 Code int32 `json:"code"` // 状态码 Message string `json:"message"` // 错误信息,code不为0的时候出现 } type SessionVerifyResponse struct { *PublicResponse OpenId int64 `json:"open_id"` // Game⽤户的⽤户id,也就是客户端登录接⼝返回的uid Uname string `json:"uname"` // Game⽤户的昵称 } func (ko *KoMoe) GenSessionVerifyParams(access_key string, uid int64, ios bool) *httputil.Params { params := ko.GenPublicParams(ios) params.Put("access_key", access_key) // ⽤户登录后身份令牌 params.Put("uid", fmt.Sprint(uid)) // ⽤户唯⼀ID params.Put("region", "7") // 游戏账号域,region=7 params.Put("version", "2") // 接⼝版本,version=2 return params } // GenPublicParams 请求消息公共字段(公共请求参数 func (ko *KoMoe) GenPublicParams(ios bool) *httputil.Params { params := httputil.EmptyParams() var game_Id int var merchant_id int if ios { game_Id = ko.IOS.game_id merchant_id = ko.IOS.merchant_id } else { game_Id = ko.GP.game_id merchant_id = ko.GP.merchant_id } params.Put("game_id", fmt.Sprint(game_Id)) // 游戏id,[参数表]中为CP分配的game_id params.Put("merchant_id", fmt.Sprint(merchant_id)) // 商户id,[参数表]中为CP分配的merchant_id params.Put("timestamp", fmt.Sprint(servertime.Now().UnixNano()/1e6)) // 当前时间戳(毫秒) params.Put("sign", "") // 签名 ,后续生成,先放个位置 return params } // 对所有字段进行签名 func (ko *KoMoe) getSign(params *httputil.Params, ios bool) string { var buf strings.Builder values := params.Values() keys := make([]string, 0, len(values)) for k := range values { keys = append(keys, k) } // 对keys 排序 sort.Strings(keys) for _, k := range keys { //跳过不需要签名的字段 if "sign" == k { continue } buf.WriteString(params.Get(k).String()) } var secretKey string if ios { secretKey = ko.IOS.secretKey } else { secretKey = ko.GP.secretKey } buf.WriteString(secretKey) s := buf.String() // md5hex&lower md5ctx := md5.New() md5ctx.Write([]byte(s)) return strings.ToLower(hex.EncodeToString(md5ctx.Sum(nil))) } func (ko *KoMoe) DoSessionVerify(access_key string, uid int64, ios bool) (*SessionVerifyResponse, error) { params := ko.GenSessionVerifyParams(access_key, uid, ios) bytes, err := ko.DoPost(ko.getSessionVerifyUrl(), params, ios) if err != nil { // 尝试备用路线 bytes, err = ko.DoPost(ko.getSessionVerifyUrl_(true), params, ios) if err != nil { return nil, errors.WrapTrace(err) } } ret := &SessionVerifyResponse{} err = json.Unmarshal(bytes, ret) if err != nil { return nil, errors.WrapTrace(err) } if ret.Code != 0 || ret.Message != "" { return nil, errors.Swrapf(common.ErrLoginSdkError, "koMoe", ret.Code, ret.Message) } return ret, nil } func (ko *KoMoe) DoPost(url string, params *httputil.Params, ios bool) ([]byte, error) { params.Put("sign", ko.getSign(params, ios)) // header User-Agent Y Mozilla/5.0 GameServer 常量,所有API都是这个值 return httputil.DoPostUrl(url, params, httputil.NewHeaderField("User-Agent", "Mozilla/5.0 GameServer")) }
package main import "fmt" import ( "errors" "math" ) /** 抛出异常的时候,返回值nil代表错误消息 */ func sqrt(num float64) (float64, error) { if num < 0 { return 500, errors.New("入参不能为负数") } return math.Sqrt(num), nil } func main() { f, e := sqrt(64) fmt.Println(f, e) sqrt, i := sqrt(-12) fmt.Println(sqrt, i) }
package ravendb type OrderingType = string const ( OrderingTypeString = "STRING" OrderingTypeLong = "LONG" OrderingTypeDouble = "DOUBLE" OrderingTypeAlphaNumeric = "ALPHA_NUMERIC" )
package core const ( CreateUserEvent = "addUser" RemoveUserEvent = "removeUser" DumpUserEvent = "users" HelloEvent = "hello" )
package fun import ( "github.com/BurntSushi/ty/fun" ) func Map(xs, f interface{}) interface{} { return fun.Map(f, xs) }
//提供一个分等级的日志系统,建议直接使用全局的对象,而不是另外New一个 package logger import ( "fmt" "jscfg" "log" "os" "path" "runtime/debug" "strconv" "strings" "sync" //"sync/atomic" "time" "timer" ) const ( CfgBaseDir = "../cfg/" LogBaseDir = "../log/" LogBaseDir2 = "../logbyday/" ) //配置表 type stCfg struct { LogNumPreFile uint32 //最大条数 LogLevel int //日志级别 } var cfg stCfg //基础文件夹(可执行程序目录/../log/应用程序名/) var sBasePath = "" var sBasePath2 = "" //log索引 var iLogIndex uint64 = 0 var lCreateFile sync.Mutex var iLogIndex2 uint64 = 0 var lCreateFile2 sync.Mutex //记录到文件 func createLoggerFile(index uint64) { lCreateFile.Lock() if index < iLogIndex { lCreateFile.Unlock() return } iLogIndex = index + 1 lCreateFile.Unlock() //文件夹被删除了? if err := os.MkdirAll(sBasePath, os.ModePerm); err != nil { return } stime := time.Now().Format("20060102150405") i := 0 sname := "" for { sname = sBasePath + stime + "-" + strconv.Itoa(i) + ".log" f, err := os.OpenFile(sname, os.O_CREATE|os.O_EXCL|os.O_RDWR, os.ModePerm) if err != nil { i++ continue } loggerTemp := New(f, "", log.LstdFlags|log.Lshortfile, cfg.LogLevel, iLogIndex) if globalLogger != nil { globalLogger.close() } globalLogger = loggerTemp //标准输出重定向 os.Stdout = f os.Stderr = f break } //定时换 timeNow := time.Now() timeNext := time.Date(timeNow.Year(), timeNow.Month(), timeNow.Day(), timeNow.Hour()+1, 0, 0, 0, time.Local) tm := timer.NewTimer(time.Second * time.Duration(timeNext.Unix()-timeNow.Unix())) tm.Start(func() { tm.Stop() createLoggerFile(iLogIndex) }) } //定时读取配置表 func keepLoadCfg() error { spath, err := os.Getwd() if err != nil { return err } var cfgTemp stCfg //读取配置表 if err := jscfg.ReadJson(path.Join(spath, CfgBaseDir+"logger.json"), &cfgTemp); err != nil { return err } if cfg.LogLevel != cfgTemp.LogLevel && globalLogger != nil { globalLogger.SetLevel(cfgTemp.LogLevel) } cfg = cfgTemp return nil } func init() { _, sfile := path.Split(os.Args[0]) spath, err := os.Getwd() if err != nil { panic(err) return } //读取配置表 if err := jscfg.ReadJson(path.Join(spath, CfgBaseDir+"logger.json"), &cfg); err != nil { panic(err) return } sBasePath = path.Join(spath, LogBaseDir, sfile) + "/" sBasePath2 = path.Join(spath, LogBaseDir2, sfile) + "/" //定时读取配置表,开关日志及数量 tm := timer.NewTimer(time.Second * 5) tm.Start(func() { keepLoadCfg() }) createLoggerFile(iLogIndex) createLoggerFile2(iLogIndex) } var globalLogger *Logger const ( DEBUG = iota INFO WARNING ERROR FATAL NONE ) var levelNames = []string{ "DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "NONE", } var levelPrefixes []string func init() { levelPrefixes = make([]string, len(levelNames)) for i, name := range levelNames { levelPrefixes[i] = name + ": " } } func Debug(format string, args ...interface{}) { globalLogger.Output(DEBUG, format, args...) } func Info(format string, args ...interface{}) { globalLogger.Output(INFO, format, args...) } func Warning(format string, args ...interface{}) { globalLogger.Output(WARNING, format, args...) } func Error(format string, args ...interface{}) { globalLogger.Output(ERROR, format, args...) // globalLogger2.Output(ERROR, format, args...) } func Fatal(format string, args ...interface{}) { globalLogger.Output(FATAL, format, args...) debug.PrintStack() panic(fmt.Sprintf(format, args...)) } func SetLogger(logger *Logger) { globalLogger = logger } type Logger struct { file *os.File logger *log.Logger level int index uint64 //索引,防止多个log同时请求创建新的文件 numbers uint32 //log数量,超出开新文件 } func New(f *os.File, prefix string, flag, level int, index uint64) *Logger { return &Logger{ file: f, logger: log.New(f, prefix, flag), level: level, index: index, numbers: uint32(0), } } func (self *Logger) Debug(format string, args ...interface{}) { self.Output(DEBUG, format, args...) } func (self *Logger) Info(format string, args ...interface{}) { self.Output(INFO, format, args...) } func (self *Logger) Warning(format string, args ...interface{}) { self.Output(WARNING, format, args...) } func (self *Logger) Error(format string, args ...interface{}) { self.Output(ERROR, format, args...) } func (self *Logger) Fatal(format string, args ...interface{}) { self.Output(FATAL, format, args...) debug.PrintStack() panic(fmt.Sprintf(format, args...)) } //关闭,只调用一次,给30秒的缓冲,肯定都已经写完了 func (self *Logger) close() { go func() { time.Sleep(time.Second * 30) self.file.Close() }() } // 如果对象包含需要加密的信息(例如密码),请实现Redactor接口 type Redactor interface { // 返回一个去处掉敏感信息的示例 Redacted() interface{} } // Redact 返回跟字符串等长的“*”。 func Redact(s string) string { return strings.Repeat("*", len(s)) } func (self *Logger) Output(level int, format string, args ...interface{}) { if self.level > level { return } redactedArgs := make([]interface{}, len(args)) for i, arg := range args { if redactor, ok := arg.(Redactor); ok { redactedArgs[i] = redactor.Redacted() } else { redactedArgs[i] = arg } } self.logger.Output(3, levelPrefixes[level]+fmt.Sprintf(format, redactedArgs...)) //新文件,换新方式了 //if atomic.AddUint32(&self.numbers, 1) >= cfg.LogNumPreFile { // go createLoggerFile(self.index) //} } func (self *Logger) SetFlags(flag int) { self.logger.SetFlags(flag) } func (self *Logger) SetPrefix(prefix string) { self.logger.SetPrefix(prefix) } func (self *Logger) SetLevel(level int) { self.level = level } func LogNameToLogLevel(name string) int { s := strings.ToUpper(name) for i, level := range levelNames { if level == s { return i } } panic(fmt.Errorf("no log level: %v", name)) } //一天的错误日志 var globalLogger2 *Logger //记录到文件 func createLoggerFile2(index uint64) { lCreateFile2.Lock() if index < iLogIndex2 { lCreateFile2.Unlock() return } iLogIndex2 = index + 1 lCreateFile2.Unlock() //文件夹被删除了? if err := os.MkdirAll(sBasePath2, os.ModePerm); err != nil { return } stime := time.Now().Format("20060102150405") i := 0 sname := "" for { sname = sBasePath2 + stime + "-" + strconv.Itoa(i) + ".log" f, err := os.OpenFile(sname, os.O_CREATE|os.O_EXCL|os.O_RDWR, os.ModePerm) if err != nil { i++ continue } loggerTemp := New(f, "", log.LstdFlags|log.Lshortfile, cfg.LogLevel, iLogIndex2) if globalLogger2 != nil { globalLogger2.close() } globalLogger2 = loggerTemp //标准输出重定向 os.Stdout = f os.Stderr = f break } //定时换 timeNow := time.Now() timeNext := time.Date(timeNow.Year(), timeNow.Month(), timeNow.Day()+1, 0, 0, 0, 0, time.Local) tm := timer.NewTimer(time.Second * time.Duration(timeNext.Unix()-timeNow.Unix())) tm.Start(func() { tm.Stop() createLoggerFile2(iLogIndex) }) }
package chain import ( "fmt" "reflect" ) /** entity */ type Request struct { tagId string } func (request *Request) SetTagId(tagId string) { request.tagId = tagId } func (request *Request) GetTagId() string { return request.tagId } type Response struct { } /** interface */ type Handler interface { DoHandler(request Request, response Response) } type Pipeline interface { AddLast(handler Handler) DoHandler(request Request, response Response) } /** implement */ type PipelineImpl struct { handlers []Handler } func (pipeline *PipelineImpl) AddLast(handler Handler) { if pipeline.handlers == nil || len(pipeline.handlers) < 1 { pipeline.handlers = []Handler{} } pipeline.handlers = append(pipeline.handlers, handler) } func (pipeline *PipelineImpl) DoHandler(request Request, response Response) { for index, handler := range pipeline.handlers { fmt.Println("handler index: ", index, " -> ", &handler, " -> ", reflect.TypeOf(handler)) handler.DoHandler(request, response) } } /** metrics handler */ type MetricsHandler struct{} func (handler *MetricsHandler) DoHandler(request Request, response Response) { fmt.Println("metrics", "->", request.tagId) } /** global handler */ type GlobalHandler struct{} func (handler *GlobalHandler) DoHandler(request Request, response Response) { fmt.Println("global", "->", request.tagId) }
package catalog import ( "bytes" "os" "path/filepath" "time" "github.com/cidverse/cid/pkg/core/util" "github.com/cidverse/cidverseutils/pkg/encoding" "github.com/go-resty/resty/v2" "github.com/rs/zerolog/log" "gopkg.in/yaml.v3" ) type Source struct { URI string `yaml:"uri"` AddedAt string `yaml:"added_at"` UpdatedAt string `yaml:"updated_at"` SHA256 string `yaml:"sha256"` } func LoadSources() map[string]*Source { sources := make(map[string]*Source) file := filepath.Join(util.GetUserConfigDirectory(), "repositories.yaml") // file doesn't exist yet, init with main repo if _, err := os.Stat(file); os.IsNotExist(err) { sources["cid"] = &Source{URI: "https://raw.githubusercontent.com/cidverse/catalog/main/cid-index.yaml", AddedAt: time.Now().Format(time.RFC3339), UpdatedAt: time.Now().Format(time.RFC3339), SHA256: ""} return sources } content, err := os.ReadFile(file) if err != nil { log.Fatal().Err(err).Str("file", file).Msg("failed to read registries") } err = yaml.Unmarshal(content, &sources) if err != nil { log.Fatal().Err(err).Str("file", file).Msg("failed to read registries") } return sources } func LoadCatalogs(sources map[string]*Source) Config { var cfg Config for name := range sources { file := filepath.Join(util.GetUserConfigDirectory(), "repo.d", name+".yaml") if _, err := os.Stat(file); os.IsNotExist(err) { log.Warn().Str("file", file).Msg("cache for registry is missing, please run `cid catalog update`") continue } content, err := os.ReadFile(file) if err != nil { log.Error().Str("file", file).Msg("failed to read file") continue } var fileCfg Config err = yaml.Unmarshal(content, &fileCfg) if err != nil { log.Fatal().Err(err).Str("file", file).Msg("failed to read registries") } // set repository for i := 0; i < len(fileCfg.ContainerImages); i++ { fileCfg.ContainerImages[i].Repository = name } for i := 0; i < len(fileCfg.Actions); i++ { fileCfg.Actions[i].Repository = name } for i := 0; i < len(fileCfg.Workflows); i++ { fileCfg.Workflows[i].Repository = name } // append cfg.ContainerImages = append(cfg.ContainerImages, fileCfg.ContainerImages...) cfg.Actions = append(cfg.Actions, fileCfg.Actions...) cfg.Workflows = append(cfg.Workflows, fileCfg.Workflows...) } return cfg } func saveSources(data map[string]*Source) { file := filepath.Join(util.GetUserConfigDirectory(), "repositories.yaml") out, err := yaml.Marshal(data) if err != nil { return } err = os.WriteFile(file, out, os.ModePerm) if err != nil { log.Fatal().Str("file", file).Msg("failed to update registries") } } func AddCatalog(name string, url string) { sources := LoadSources() sources[name] = &Source{URI: url, AddedAt: time.Now().Format(time.RFC3339), UpdatedAt: time.Now().Format(time.RFC3339)} saveSources(sources) } func RemoveCatalog(name string) { sources := LoadSources() delete(sources, name) saveSources(sources) } func UpdateAllCatalogs() { sources := LoadSources() for name, source := range sources { UpdateCatalog(name, source) source.UpdatedAt = time.Now().Format(time.RFC3339) } saveSources(sources) } func UpdateCatalog(name string, source *Source) { dir := filepath.Join(util.GetUserConfigDirectory(), "repo.d") _ = os.MkdirAll(dir, os.ModePerm) // download file := filepath.Join(dir, name+".yaml") client := resty.New() resp, err := client.R(). SetOutput(file). Get(source.URI) if err != nil { log.Fatal().Err(err).Str("uri", source.URI).Msg("failed to fetch registry index") } else if resp.IsError() { log.Fatal().Str("uri", source.URI).Str("response_status", resp.Status()).Msg("failed to fetch registry index") } // sha256 hash fileHash, hashErr := encoding.SHA256Hash(bytes.NewReader(resp.Body())) if hashErr != nil { log.Fatal().Err(hashErr).Str("uri", source.URI).Msg("failed to calculate catalog hash") } source.SHA256 = fileHash }
package gube import ( "fmt" ) var _ = fmt.Errorf type CachedGarden interface { Reset() Garden } type cached_garden struct { Garden projects ProjectCache profiles ProfileCache shoots ShootCache } var _ Garden = &cached_garden{} func NewCachedGarden(g Garden) CachedGarden { return (&cached_garden{}).new(g) } func (this *cached_garden) new(g Garden) CachedGarden { this.Garden = g.NewWrapper(this) this.projects = NewProjectCache(this.Garden) this.profiles = NewProfileCache(this.Garden) this.shoots = NewShootCache(this.Garden) return this } func (this *cached_garden) Reset() { this.projects.Reset() this.profiles.Reset() this.shoots.Reset() } func (this *cached_garden) GetProject(name string) (Project, error) { //fmt.Printf("GET CACHED %s\n", name) return this.projects.GetProject(name) } func (this *cached_garden) GetProjects() (map[string]Project, error) { return this.projects.GetProjects() } func (this *cached_garden) GetProjectByNamespace(namespace string) (Project, error) { return this.projects.GetProjectByNamespace(namespace) } func (this *cached_garden) GetProfile(name string) (Profile, error) { //fmt.Printf("GET CACHED PROFILE %s\n", name) return this.profiles.GetProfile(name) } func (this *cached_garden) GetProfiles() (map[string]Profile, error) { return this.profiles.GetProfiles() } func (this *cached_garden) GetShoot(name *ShootName) (Shoot, error) { //fmt.Printf("GET CACHED SHOOT %s\n", name) return this.shoots.GetShoot(name) } func (this *cached_garden) GetShoots() (map[ShootName]Shoot, error) { return this.shoots.GetShoots() }
package rate_type import ( "sync" "vcm/api" ) type ZEC string func (z *ZEC) UpdateRate(wg *sync.WaitGroup) { defer wg.Done() rate, err := api.FetchRate("zec_jpy") if err != nil { panic(err) } *z = ZEC(rate) }
package acmetool import "os" // The state directory path to be used for a system-wide state storage // directory. It may vary by system and platform. On most POSIX-like // systems, it is "/var/lib/acme". Specific builds might customise // it. var DefaultStateDir string // The hooks directory is the path at which executable hooks are // looked for. On POSIX-like systems, this is usually // "/usr/lib/acme/hooks" (or "/usr/libexec/acme/hooks" if /usr/libexec // exists). var DefaultHooksDir string // The standard webroot path, into which the responder always tries to // install challenges, not necessarily successfully. This is intended // to be a standard, system-wide path to look for challenges at. On // POSIX-like systems, it is usually "/var/run/acme/acme-challenge". var DefaultWebRootDir string func init() { if DefaultStateDir == "" { DefaultStateDir = "/var/lib/acme" } if DefaultHooksDir == "" { if _, err := os.Stat("/usr/libexec"); err == nil { DefaultHooksDir = "/usr/libexec/acme/hooks" } else { DefaultHooksDir = "/usr/lib/acme/hooks" } } if DefaultWebRootDir == "" { DefaultWebRootDir = "/var/run/acme/acme-challenge" } }
package api import ( "context" "encoding/json" "fmt" "net/http" "strings" "github.com/porter-dev/porter/internal/models" ) // GetProjectResponse is the response returned after querying for a // given project type GetProjectResponse models.ProjectExternal // GetProject retrieves a project by id func (c *Client) GetProject(ctx context.Context, projectID uint) (*GetProjectResponse, error) { req, err := http.NewRequest( "GET", fmt.Sprintf("%s/projects/%d", c.BaseURL, projectID), nil, ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := &GetProjectResponse{} if httpErr, err := c.sendRequest(req, bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // GetProjectClusterResponse is the response returned after querying for a // given project's cluster type GetProjectClusterResponse models.ClusterExternal // GetProjectCluster retrieves a project's cluster by id func (c *Client) GetProjectCluster( ctx context.Context, projectID uint, clusterID uint, ) (*GetProjectClusterResponse, error) { req, err := http.NewRequest( "GET", fmt.Sprintf("%s/projects/%d/clusters/%d", c.BaseURL, projectID, clusterID), nil, ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := &GetProjectClusterResponse{} if httpErr, err := c.sendRequest(req, bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // ListProjectClustersResponse lists the linked clusters for a project type ListProjectClustersResponse []models.ClusterExternal // ListProjectClusters creates a list of clusters for a given project func (c *Client) ListProjectClusters( ctx context.Context, projectID uint, ) (ListProjectClustersResponse, error) { req, err := http.NewRequest( "GET", fmt.Sprintf("%s/projects/%d/clusters", c.BaseURL, projectID), nil, ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := ListProjectClustersResponse{} if httpErr, err := c.sendRequest(req, &bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // CreateProjectRequest represents the accepted fields for creating a project type CreateProjectRequest struct { Name string `json:"name" form:"required"` } // CreateProjectResponse is the resulting project after creation type CreateProjectResponse models.ProjectExternal // CreateProject creates a project with the given request options func (c *Client) CreateProject( ctx context.Context, createProjectRequest *CreateProjectRequest, ) (*CreateProjectResponse, error) { data, err := json.Marshal(createProjectRequest) if err != nil { return nil, err } req, err := http.NewRequest( "POST", fmt.Sprintf("%s/projects", c.BaseURL), strings.NewReader(string(data)), ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := &CreateProjectResponse{} if httpErr, err := c.sendRequest(req, bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // CreateProjectCandidatesRequest creates a project service account candidate, // which can be resolved to create a service account type CreateProjectCandidatesRequest struct { Kubeconfig string `json:"kubeconfig"` IsLocal bool `json:"is_local"` } // CreateProjectCandidatesResponse is the list of candidates returned after // creating the candidates type CreateProjectCandidatesResponse []*models.ClusterCandidateExternal // CreateProjectCandidates creates a service account candidate for a given project, // accepting a kubeconfig that gets parsed into a candidate func (c *Client) CreateProjectCandidates( ctx context.Context, projectID uint, createCandidatesRequest *CreateProjectCandidatesRequest, ) (CreateProjectCandidatesResponse, error) { data, err := json.Marshal(createCandidatesRequest) if err != nil { return nil, err } req, err := http.NewRequest( "POST", fmt.Sprintf("%s/projects/%d/clusters/candidates", c.BaseURL, projectID), strings.NewReader(string(data)), ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := CreateProjectCandidatesResponse{} if httpErr, err := c.sendRequest(req, &bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // GetProjectCandidatesResponse is the list of service account candidates type GetProjectCandidatesResponse []*models.ClusterCandidateExternal // GetProjectCandidates returns the service account candidates for a given // project id func (c *Client) GetProjectCandidates( ctx context.Context, projectID uint, ) (GetProjectCandidatesResponse, error) { req, err := http.NewRequest( "GET", fmt.Sprintf("%s/projects/%d/clusters/candidates", c.BaseURL, projectID), nil, ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := GetProjectCandidatesResponse{} if httpErr, err := c.sendRequest(req, &bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // CreateProjectClusterResponse is the cluster that gets // returned after the candidate has been resolved type CreateProjectClusterResponse models.ClusterExternal // CreateProjectCluster creates a cluster given a project id // and a candidate id, which gets resolved using the list of actions func (c *Client) CreateProjectCluster( ctx context.Context, projectID uint, candidateID uint, createReq *models.ClusterResolverAll, ) (*CreateProjectClusterResponse, error) { data, err := json.Marshal(&createReq) if err != nil { return nil, err } req, err := http.NewRequest( "POST", fmt.Sprintf("%s/projects/%d/clusters/candidates/%d/resolve", c.BaseURL, projectID, candidateID), strings.NewReader(string(data)), ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := &CreateProjectClusterResponse{} if httpErr, err := c.sendRequest(req, bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil } // DeleteProjectCluster deletes a cluster given a project id and cluster id func (c *Client) DeleteProjectCluster( ctx context.Context, projectID uint, clusterID uint, ) error { req, err := http.NewRequest( "DELETE", fmt.Sprintf("%s/projects/%d/clusters/%d", c.BaseURL, projectID, clusterID), nil, ) if err != nil { return err } req = req.WithContext(ctx) if httpErr, err := c.sendRequest(req, nil, true); httpErr != nil || err != nil { if httpErr != nil { return fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return err } return nil } // DeleteProjectResponse is the object returned after project deletion type DeleteProjectResponse models.ProjectExternal // DeleteProject deletes a project by id func (c *Client) DeleteProject(ctx context.Context, projectID uint) (*DeleteProjectResponse, error) { req, err := http.NewRequest( "DELETE", fmt.Sprintf("%s/projects/%d", c.BaseURL, projectID), nil, ) if err != nil { return nil, err } req = req.WithContext(ctx) bodyResp := &DeleteProjectResponse{} if httpErr, err := c.sendRequest(req, bodyResp, true); httpErr != nil || err != nil { if httpErr != nil { return nil, fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors) } return nil, err } return bodyResp, nil }
package pixivapi import ( "os" "testing" ) func Test_generateHash(t *testing.T) { type args struct { data string } tests := []struct { name string args args want string }{ { "given date", args{"2019-12-19T16:02:07+00:00" + "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"}, "2513613dfbec508c2531f471b3435e70", }, { "given another date", args{"2019-12-19T18:59:23+00:00" + "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"}, "7fe052bd82fc83102dac8fbe9531c89a", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := generateHash(tt.args.data); got != tt.want { t.Errorf("generateHash() = %v, want %v", got, tt.want) } }) } } func TestClient_Login(t *testing.T) { c := New() _, err := c.Login(os.Getenv("PIXIV_USERNAME"), os.Getenv("PIXIV_PASSWORD")) if err != nil { t.Errorf("Client.Error() experienced error %v", err) } }
// Copyright 2020 The VectorSQL Authors. // // Code is licensed under Apache License, Version 2.0. package config import ( "os" "github.com/naoina/toml" ) type Server struct { TCPPort int HTTPPort int DebugPort int Path string TmpPath string ListenHost string DisplayName string DefaultDatabase string DefaultBlockSize int CalculateTextStackTrace bool } func DefaultServerConfig() Server { return Server{ TCPPort: 9000, HTTPPort: 8123, DebugPort: 8080, Path: "./data9000", DisplayName: "VectorSQL", DefaultDatabase: "default", DefaultBlockSize: 65536, } } type Runtime struct { ParallelWorkerNumber int } func DefaultRuntimeConfig() Runtime { return Runtime{ ParallelWorkerNumber: 4, } } type Logger struct { Level string } func DefaultLoggerConfig() Logger { return Logger{ Level: "DEBUG", } } func DefaultConfig() *Config { return &Config{ Server: DefaultServerConfig(), Runtime: DefaultRuntimeConfig(), Logger: DefaultLoggerConfig(), } } type Config struct { Server Server Runtime Runtime Logger Logger } func Load(file string) (*Config, error) { f, err := os.Open(file) if err != nil { return nil, err } defer f.Close() conf := DefaultConfig() if err := toml.NewDecoder(f).Decode(conf); err != nil { return nil, err } return conf, nil }
// challenge :: https://www.hackerrank.com/challenges/a-very-big-sum package sum import "fmt" func read(n int) ([]int, error) { in := make([]int, n) for i := range in { _, err := fmt.Scan(&in[i]) if err != nil { return in[:i], err } } return in, nil } func main() { var a, res int fmt.Scanf("%v\n", &a) numbers, err := read(a) if err != nil { panic(err) } for _, val := range numbers { res += val } fmt.Println(res) }
package command import ( "github.com/goodmustache/pt/actor" "github.com/goodmustache/pt/command/display" ) //counterfeiter:generate . ProjectListActor type ProjectListActor interface { Projects() ([]actor.Project, error) } type ProjectList struct { UserID uint64 `short:"u" long:"user-id" description:"User ID to run commands with"` Actor ProjectListActor UI UI } func (cmd ProjectList) Execute(_ []string) error { projects, err := cmd.Actor.Projects() if err != nil { return err } displayProjects := make([]display.ProjectRow, 0, len(projects)) for _, project := range projects { displayProjects = append(displayProjects, display.ProjectRow{ ID: project.ID, Name: project.Name, Description: project.Description, Visibility: project.Visibility(), }) } cmd.UI.PrintTable(displayProjects) return nil }
package prolog import ( "bytes" "encoding/binary" "fmt" "net/http" ) // SocketWrite .. func SocketWrite(serverAddr string, s string) (err error) { client := &http.Client{} url := serverAddr buf := new(bytes.Buffer) binary.Write(buf, binary.LittleEndian, []byte(s)) request, err := http.NewRequest("POST", url, buf) if err != nil { return } response, err := client.Do(request) if err != nil { return } defer response.Body.Close() //stdout := os.Stdout //_, err = io.Copy(stdout, response.Body) status := response.StatusCode fmt.Println(status) return }
/* Copyright 2014 Huawei Technologies Co., Ltd. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package unittest import ( "testing" "github.com/stretchr/testify/assert" "github.com/containerops/dockyard/models" ) // TestNewAppV1 func TestNewAppV1(t *testing.T) { namespace := "containerops" repository := "official" _, err := models.NewAppV1(namespace, repository) assert.Nil(t, err, "Fail to create/query a repository") } // TestAppV1Put func TestAppV1Put(t *testing.T) { namespace := "containerops" repository := "official" a := models.ArtifactV1{} r, _ := models.NewAppV1(namespace, repository) err := r.Put(a) assert.Nil(t, err, "Fail to add an artifact to a repository") r.Locked = true err = r.Put(a) assert.NotNil(t, err, "Should not add an artifact to a locked repository") } // TestArtifactV1GetName func TestArtifactV1GetName(t *testing.T) { cases := []struct { a models.ArtifactV1 expected string }{ {a: models.ArtifactV1{OS: "os", Arch: "arch", App: "app", Tag: "tag"}, expected: "os/arch/app:tag"}, {a: models.ArtifactV1{OS: "os", Arch: "arch", App: "app", Tag: ""}, expected: "os/arch/app"}, {a: models.ArtifactV1{OS: "os", Arch: "arch", App: "", Tag: "tag"}, expected: ""}, {a: models.ArtifactV1{OS: "os", Arch: "", App: "app", Tag: "tag"}, expected: ""}, {a: models.ArtifactV1{OS: "", Arch: "arch", App: "app", Tag: "tag"}, expected: ""}, } for _, c := range cases { assert.Equal(t, c.a.GetName(), c.expected, "Fail to get artifact name") } }
package sentryhook import ( "runtime" "strings" "github.com/getsentry/sentry-go" ) // NewStacktrace creates a stacktrace using `runtime.Callers`. func NewStacktraceForHook() *sentry.Stacktrace { pcs := make([]uintptr, 100) n := runtime.Callers(1, pcs) if n == 0 { return nil } frames := extractFrames(pcs[:n]) frames = filterFrames(frames) stacktrace := sentry.Stacktrace{ Frames: frames, } return &stacktrace } func extractFrames(pcs []uintptr) []sentry.Frame { var frames []sentry.Frame callersFrames := runtime.CallersFrames(pcs) for { callerFrame, more := callersFrames.Next() frames = append([]sentry.Frame{ sentry.NewFrame(callerFrame), }, frames...) if !more { break } } return frames } // filterFrames filters out stack frames that are not meant to be reported to // Sentry. Those are frames internal to the SDK or Go. func filterFrames(frames []sentry.Frame) []sentry.Frame { if len(frames) == 0 { return nil } filteredFrames := make([]sentry.Frame, 0, len(frames)) for _, frame := range frames { // Skip Go internal frames. if frame.Module == "runtime" || frame.Module == "testing" { continue } // Skip Sentry internal frames, except for frames in _test packages (for // testing). if strings.HasPrefix(frame.Module, "github.com/getsentry/sentry-go") && !strings.HasSuffix(frame.Module, "_test") { continue } // Skip Logrus Sentry Hook if strings.HasPrefix(frame.Module, "github.com/prixa-ai/logrus-sentry-hook") && !strings.HasSuffix(frame.Module, "_test") { continue } // Skip Logrus if strings.HasPrefix(frame.Module, "github.com/sirupsen/logrus") && !strings.HasSuffix(frame.Module, "_test") { continue } filteredFrames = append(filteredFrames, frame) } return filteredFrames }
package fiberx import ( "regexp" "github.com/go-playground/locales/en" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" ent "github.com/go-playground/validator/v10/translations/en" "github.com/gofiber/fiber/v2/utils" ) // V is an instance of *validator.Validate // used for custom registrations. var V *validator.Validate var ( uni *ut.UniversalTranslator trans ut.Translator mobileRegexp *regexp.Regexp ) func init() { V = validator.New() uni = ut.New(en.New()) trans, _ = uni.GetTranslator("en") if err := ent.RegisterDefaultTranslations(V, trans); err != nil { panic(err) } registerValidations() } func registerValidations() { mobileRegexp = regexp.MustCompile(`^1[3456789]\d{9}$`) _ = V.RegisterValidation("mobile", MobileRule) } // MobileRule validates mobile phone number func MobileRule(fl validator.FieldLevel) bool { return mobileRegexp.Match(utils.GetBytes(fl.Field().String())) }
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) type state struct { votes int value map[int]float64 // issue.id -> fraction of votes } type issue struct { id int name string cost int frac float64 // total fractional votes } type descend []issue func (s descend) Len() int { return len(s) } func (s descend) Less(i, j int) bool { if s[i].frac == s[j].frac { return s[i].cost < s[j].cost } return s[i].frac > s[j].frac } func (s descend) Swap(i, j int) { s[i], s[j] = s[j], s[i] } var ( states []state issues []issue id2ix map[int]int ) func init() { id2ix = make(map[int]int) } func popular(is []int, s state) bool { var v float64 for _, i := range is { if _, f := s.value[i]; f { v += s.value[i] } } if v >= 0.51 { return true } return false } func elect(is []int) (votes, cost int) { for _, i := range is { cost += issues[id2ix[i]].cost } for _, i := range states { if popular(is, i) { votes += i.votes } } return votes, cost } type task struct { level int votes int cost int issues []int } func main() { data, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer data.Close() scanner := bufio.NewScanner(data) var niss, tvot int scanner.Scan() fmt.Sscanf(scanner.Text(), "Social issues: %d", &niss) issues = make([]issue, niss) iss := make(map[string]int) for i := 0; i < niss; i++ { scanner.Scan() for scanner.Text() == "" { scanner.Scan() } var cost int s := strings.Split(scanner.Text(), ": ") fmt.Sscanf(s[1], "%d", &cost) issues[i] = issue{i, strings.TrimRight(s[0], ":"), cost, 0} iss[issues[i].name] = i } for scanner.Scan() { name := scanner.Text() if len(name) == 0 { continue } scanner.Scan() var votes int fmt.Sscanf(scanner.Text(), "Votes: %d", &votes) var total float64 value := make(map[int]float64) for scanner.Scan() { if scanner.Text() == "" { break } s := strings.Split(scanner.Text(), ": ") var v float64 fmt.Sscanf(s[1], "%f", &v) total += v value[iss[s[0]]] = v } for k, v := range value { if v > 0 { value[k] = v / total issues[k].frac += value[k] * float64(votes) } } states = append(states, state{votes, value}) tvot += votes } sort.Sort(descend(issues)) for ix, i := range issues { id2ix[i.id] = ix } votes, cost := elect([]int{issues[0].id}) todo := []task{task{}, task{0, votes, cost, []int{issues[0].id}}} best, bestc, bestl := niss, 0, make([]int, niss) for i := 0; i < niss; i++ { bestc += issues[i].cost bestl[i] = i } for len(todo) > 0 { curr := todo[len(todo)-1] todo = todo[:len(todo)-1] if len(curr.issues) > best { continue } if curr.level == niss-2 { // finish curr.level++ votes, cost = elect(append(curr.issues, issues[curr.level].id)) if votes > tvot/2 { if len(curr.issues)+1 < best || (len(curr.issues)+1 == best && cost < bestc) { best, bestc, bestl = len(curr.issues)+1, cost, append(curr.issues, issues[curr.level].id) } } } else { // advance curr.level++ todo = append(todo, curr) votes, cost = elect(append(curr.issues, issues[curr.level].id)) if votes > tvot/2 { if len(curr.issues)+1 < best || (len(curr.issues)+1 == best && cost < bestc) { best, bestc, bestl = len(curr.issues)+1, cost, append(curr.issues, issues[curr.level].id) } } else { todo = append(todo, task{curr.level, votes, cost, append(curr.issues, issues[curr.level].id)}) } } } var ret []string for _, i := range bestl { ret = append(ret, issues[id2ix[i]].name) } sort.Strings(ret) fmt.Println(strings.Join(ret, "\n")) }