query
stringlengths
8
6.75k
document
stringlengths
9
1.89M
negatives
listlengths
19
19
metadata
dict
IsBare indicates a repository is a bare repository.
func (v Repository) IsBare() bool { return v.workDir == "" }
[ "func (r Repository) IsBare() bool {\n\treturn gitRepositoryIsBare(r.gitRepository)\n}", "func IsBareRepository(path string) bool {\n\n\tcmd := exec.Command(\"git\", fmt.Sprintf(\"--git-dir=%s\", path), \"rev-parse\", \"--is-bare-repository\")\n\tbody, err := cmd.Output()\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tstatus := strings.Trim(string(body), \"\\n \")\n\treturn status == \"true\"\n}", "func isBareRepo(path string) bool {\n\tbare := true\n\tif exists, err := dir.Exists(filepath.Join(path, \".git\")); exists && err == nil {\n\t\tbare = false // see if it's bare or not\n\t}\n\treturn bare\n}", "func InitBareRepository(dir string) (*Repository, error) {\n\tr, err := gitInitRepository(dir, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Repository{r}, nil\n}", "func IsLocalNonBareGitRepository(fs fs.FileSystem, dir string) (bool, error) {\n\t_, err := fs.Stat(filepath.Join(dir, \".git\"))\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func cloneBareRepository(remote string, dest string) error {\n\tcmd := exec.Command(\"git\", \"clone\", \"--bare\", remote, dest)\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CloneBare(URL string) (Repository, error) {\n\t// Git objects storer based on memory\n\tstorer := memory.NewStorage()\n\n\trepo, err := git.Clone(storer, nil, &git.CloneOptions{\n\t\tURL: URL,\n\t\tTags: git.TagMode(2),\n\t})\n\tif err != nil {\n\t\treturn Repository{}, err\n\t}\n\treturn Repository{repo}, nil\n}", "func InitBareRepository(path string) (*Repository, error) {\n\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not determine absolute path: %v\", err)\n\t}\n\n\tcmd := exec.Command(\"git\", \"init\", \"--bare\", path)\n\terr = cmd.Run()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Repository{Path: path}, nil\n}", "func setupBareGitRepo(t *testing.T) *repositories.GitRepository {\n\tt.Helper()\n\tassert := assert.New(t)\n\n\trepoDir, err := ioutil.TempDir(\"\", \"rb-gateway-bare-repo-\")\n\tassert.Nil(err)\n\n\t_, err = git.PlainInit(repoDir, true)\n\tassert.Nil(err)\n\n\treturn &repositories.GitRepository{\n\t\tRepositoryInfo: repositories.RepositoryInfo{\n\t\t\tName: \"upstream\",\n\t\t\tPath: repoDir,\n\t\t},\n\t}\n}", "func LocalNonBareGitRepositoryIsEmpty(fs fs.FileSystem, dir string) (bool, error) {\n\tgitPath := filepath.Join(dir, \".git\")\n\n\tfi, err := fs.Stat(gitPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif !fi.IsDir() {\n\t\tgitPath, err = followGitSubmodule(fs, gitPath)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Search for any file in .git/{objects,refs}. We don't just search the\n\t// base .git directory because of the hook samples that are normally\n\t// generated with `git init`\n\tfound := false\n\tfor _, dir := range []string{\"objects\", \"refs\"} {\n\t\terr := fs.Walk(filepath.Join(gitPath, dir), func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !info.IsDir() {\n\t\t\t\tfound = true\n\t\t\t}\n\n\t\t\tif found {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif found {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func onlyGo(repo, branch, goBranch string) bool { return repo == \"go\" }", "func BareMetal(name string) bool {\n\treturn name == None || name == Mock\n}", "func (r *Repo) IsRaw() (res bool) {\n\treturn r.WorkDir == \"\"\n}", "func IsRepo() bool {\n\treturn run.Silent(\"git rev-parse --git-dir >/dev/null 2>&1\")\n}", "func IsRepo() bool {\n\tout, err := Run(\"rev-parse\", \"--is-inside-work-tree\")\n\treturn err == nil && strings.TrimSpace(out) == \"true\"\n}", "func (p *cliModules) IsBoringBinary() bool {\n\treturn false\n}", "func (a *Application) checkRepoIsReal(name ...string) bool {\n\tvar fullname string\n\tswitch len(name) {\n\tcase 1:\n\t\tfullname = strings.TrimSpace(name[0])\n\t\tif fullname == \"\" || fullname == \"/\" {\n\t\t\treturn false\n\t\t}\n\tcase 2:\n\t\torg := strings.TrimSpace(name[0])\n\t\trepo := strings.TrimSpace(name[1])\n\t\tif org == \"\" || repo == \"\" {\n\t\t\treturn false\n\t\t}\n\t\tfullname = u.Format(\"%s/%s\", name[0], name[1])\n\tdefault:\n\t\tpanic(\"Youre doing this wrong\")\n\t}\n\turl := u.Format(\"https://github.com/%s\", fullname)\n\tif code, _, _, e := nt.HTTP(nt.HEAD, url, nt.NewHeaderBuilder().GetHeader(), nil); e != nil || code != 200 {\n\t\treturn false\n\t} else {\n\t\treturn true\n\t}\n}", "func (g *GitDriver) IsOpen() bool {\n\tif g.Repository == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func RepositoryBase_IsResource(construct awscdk.IConstruct) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_ecr.RepositoryBase\",\n\t\t\"isResource\",\n\t\t[]interface{}{construct},\n\t\t&returns,\n\t)\n\n\treturn returns\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Config returns git config object
func (v Repository) Config() GitConfig { return v.gitConfig }
[ "func (v Repository) Config() goconfig.GitConfig {\n\tcfg, err := goconfig.Load(v.configFile())\n\tif err != nil && err != goconfig.ErrNotExist {\n\t\tlog.Fatalf(\"fail to load config: %s: %s\", v.configFile(), err)\n\t}\n\tif cfg == nil {\n\t\tcfg = goconfig.NewGitConfig()\n\t}\n\treturn cfg\n}", "func (r *Repo) Config(args ...string) error {\n\tr.logger.WithField(\"args\", args).Info(\"Running git config.\")\n\tif b, err := r.gitCommand(append([]string{\"config\"}, args...)...).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"git config %v failed: %v. output: %s\", args, err, string(b))\n\t}\n\treturn nil\n}", "func (r *PriRepo) Config() (*config.Config, error) {\n\tpackageLock.Lock()\n\tdefer packageLock.Unlock()\n\n\tif r.closed {\n\t\treturn nil, errors.New(\"cannot access config, repo not open\")\n\t}\n\treturn r.config, nil\n}", "func (b *Branch) Config() map[string]string {\n\tif b.config != nil {\n\t\treturn b.config\n\t}\n\tvar cfgText string\n\tif b.Current {\n\t\tdata, _ := ioutil.ReadFile(filepath.Join(repoRoot(), \"codereview.cfg\"))\n\t\tcfgText = string(data)\n\t} else {\n\t\tout, err := cmdOutputDirErr(repoRoot(), \"git\", \"show\", b.Name+\":codereview.cfg\")\n\t\tif err == nil {\n\t\t\tcfgText = out\n\t\t}\n\t}\n\tcfg, err := parseConfig(cfgText)\n\tif err != nil {\n\t\tverbosef(\"failed to load config for branch %v: %v\", b.Name, err)\n\t\tcfg = make(map[string]string)\n\t}\n\tb.config = cfg\n\treturn b.config\n}", "func ReadConfig(ctx context.Context, git *Tool) (*Config, error) {\n\tp, err := git.Start(ctx, \"config\", \"-z\", \"--list\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", err)\n\t}\n\tcfg, parseErr := parseConfig(p)\n\twaitErr := p.Wait()\n\tif waitErr != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", waitErr)\n\t}\n\tif parseErr != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", parseErr)\n\t}\n\treturn cfg, nil\n}", "func (b *Bridge) Config() (Config, error) {\n\tconfig := Config{}\n\tif !b.isAvailable() {\n\t\treturn config, ErrBridgeNotAvailable\n\t}\n\n\turl := b.baseURL.String() + \"api/\" + b.Username + \"/config\"\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.NewDecoder(res.Body).Decode(&config)\n\treturn config, err\n}", "func getConfig() Conf {\n\tfile, _ := os.Open(\"config/config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tConfig := defaultConfig()\n\terr := decoder.Decode(&Config)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\treturn Config\n}", "func (miner *CGMiner) Config() (*Config, error) {\n\tresult, err := miner.runCommand(\"config\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Lets see the result so we can break it apart. \n\tif debug2 {\n\t\tfmt.Println(\"... DEBUG: IN cgminer.config -- Json Result from Config command: \\n\")\n\t\tb := []byte(result)\n\t\tb, _ = prettyprint(b)\n\t\tfmt.Printf(\"%s\", b)\n\t\tfmt.Println(\"\\n... END OF DEBUG\\n\\n\")\n\t}\n\n\tvar configResponse configResponse\n\terr = json.Unmarshal([]byte(result), &configResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(configResponse.Config) != 1 {\n\t\treturn nil, errors.New(\"Received multiple Config objects\")\n\t}\n\n\tvar config = configResponse.Config[0]\n\treturn &config, err\n}", "func config() error {\n\t// NOTE: No Docker config.\n\treturn mage.Config(mage.ShortConfigType|mage.ReferenceConfigType, configFileParams(), \".\")\n}", "func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error) {\n\tentry, err := s.Get(ctx, \"config\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif entry == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar result config\n\tif err := entry.DecodeJSON(&result); err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading configuration: %s\", err)\n\t}\n\n\tif len(result.TokenPolicies) == 0 && len(result.Policies) > 0 {\n\t\tresult.TokenPolicies = result.Policies\n\t}\n\n\treturn &result, nil\n}", "func (b *backend) Config(ctx context.Context, s logical.Storage) (*ConfigEntry, error) {\n\tentry, err := s.Get(ctx, \"config\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif entry == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar result ConfigEntry\n\tif entry != nil {\n\t\tif err := entry.DecodeJSON(&result); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &result, nil\n}", "func config() (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\treturn nil, ErrConfigNotLoaded\n}", "func GetConfig(fileName string) (*RepositoryConfig, error) {\n\tc := NewRepositoryConfig()\n\n\tif err := c.read(fileName); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tif err := c.processRepos(); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tif c.Services.NotaryURL == \"\" {\n\t\tgrip.Warning(message.Fields{\n\t\t\t\"message\": \"no notary service url specified\",\n\t\t\t\"file\": fileName,\n\t\t\t\"num_repos\": len(c.Repos),\n\t\t})\n\t}\n\n\treturn c, nil\n}", "func (c *Command) GetConfig() *commonEthereum.Config {\n\treturn c.config\n}", "func GetGit(appName string) (*Git, error) {\n\tconf := new(Git)\n\tif err := envconfig.Process(appName, conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func Create(c *gin.Context) apierror.APIErrors {\n\tctx := c.Request.Context()\n\tlogger := requestctx.Logger(ctx)\n\n\tcluster, err := kubernetes.GetCluster(ctx)\n\tif err != nil {\n\t\treturn apierror.InternalError(err)\n\t}\n\n\tvar request models.GitconfigCreateRequest\n\terr = c.BindJSON(&request)\n\tif err != nil {\n\t\treturn apierror.NewBadRequestError(err.Error())\n\t}\n\n\tgitconfigName := request.ID\n\tif gitconfigName == \"\" {\n\t\treturn apierror.NewBadRequestError(\"name of gitconfig to create not found\")\n\t}\n\terrorMsgs := validation.IsDNS1123Subdomain(gitconfigName)\n\tif len(errorMsgs) > 0 {\n\t\treturn apierror.NewBadRequestErrorf(\"Git configurations' name must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character (e.g. 'my-name', or '123-abc').\")\n\t}\n\n\tmanager, err := gitbridge.NewManager(logger, cluster.Kubectl.CoreV1().Secrets(helmchart.Namespace()))\n\tif err != nil {\n\t\treturn apierror.InternalError(err, \"creating git configuration manager\")\n\t}\n\n\tgitconfigList := manager.Configurations\n\n\t// see delete.go\n\tgcNames := map[string]struct{}{}\n\tfor _, gitconfig := range gitconfigList {\n\t\tgcNames[gitconfig.ID] = struct{}{}\n\t}\n\n\t// already known ?\n\tif _, ok := gcNames[gitconfigName]; ok {\n\t\treturn apierror.NewConflictError(\"gitconfig\", gitconfigName)\n\t}\n\n\tsecret := gitbridge.NewSecretFromConfiguration(gitbridge.Configuration{\n\t\tID: request.ID,\n\t\tURL: request.URL,\n\t\tProvider: request.Provider,\n\t\tUsername: request.Username,\n\t\tPassword: request.Password,\n\t\tUserOrg: request.UserOrg,\n\t\tRepository: request.Repository,\n\t\tSkipSSL: request.SkipSSL,\n\t\tCertificate: request.Certificates,\n\t})\n\n\terr = cluster.CreateSecret(ctx, helmchart.Namespace(), secret)\n\tif err != nil {\n\t\treturn apierror.InternalError(err)\n\t}\n\n\terr = addGitconfigToUser(ctx, request.ID)\n\tif err != nil {\n\t\treturn apierror.InternalError(err)\n\t}\n\n\tresponse.Created(c)\n\treturn nil\n}", "func RepoConfig() (models.MultiRepoConfig, Error) {\n\n\trepoConfigFile := filepath.Join(\"./\", repoConfigFileName)\n\tymlRepoConfigFile := filepath.Join(\"./\", ymlRepoConfigFileName)\n\n\tif utils.Exists(repoConfigFile) {\n\t\tutils.LogDebug(fmt.Sprintf(\"Reading repo config file %s\", repoConfigFile))\n\n\t\tyamlFile, err := ioutil.ReadFile(repoConfigFile) // #nosec G304\n\n\t\tif err != nil {\n\t\t\tvar e Error\n\t\t\te.Err = err\n\t\t\te.Message = \"Unable to read doppler repo config file\"\n\t\t\treturn models.MultiRepoConfig{}, e\n\t\t}\n\n\t\tvar repoConfig models.MultiRepoConfig\n\n\t\tif err := yaml.Unmarshal(yamlFile, &repoConfig); err != nil {\n\t\t\t// Try parsing old repoConfig format (i.e., no slice) for backwards compatibility\n\t\t\tvar oldRepoConfig models.RepoConfig\n\t\t\tif err := yaml.Unmarshal(yamlFile, &oldRepoConfig); err != nil {\n\t\t\t\tvar e Error\n\t\t\t\te.Err = err\n\t\t\t\te.Message = \"Unable to parse doppler repo config file\"\n\t\t\t\treturn models.MultiRepoConfig{}, e\n\t\t\t} else {\n\t\t\t\trepoConfig.Setup = append(repoConfig.Setup, oldRepoConfig.Setup)\n\t\t\t\treturn repoConfig, Error{}\n\t\t\t}\n\t\t}\n\n\t\treturn repoConfig, Error{}\n\t} else if utils.Exists(ymlRepoConfigFile) {\n\t\tutils.LogWarning(fmt.Sprintf(\"Found %s file, please rename to %s for repo configuration\", ymlRepoConfigFile, repoConfigFileName))\n\t} else {\n\t\t// If no config file exists, then this is for an interactive setup, so\n\t\t// return a MultiRepoConfig object containing an empty ProjectConfig object\n\t\tvar repoConfig models.MultiRepoConfig\n\t\trepoConfig.Setup = append(repoConfig.Setup, models.ProjectConfig{Path: configuration.Scope})\n\t\treturn repoConfig, Error{}\n\t}\n\treturn models.MultiRepoConfig{}, Error{}\n}", "func (conf *Conf) OverwriteFromGit(repo *Repository) (err error) {\n\tbuf := bytes.NewBuffer(nil)\n\terr = repo.Git(context.Background(), nil, buf, \"config\", \"--get-regexp\", \"^bits\")\n\tif err != nil {\n\t\treturn nil //no bits conf, nothing to do\n\t}\n\n\ts := bufio.NewScanner(buf)\n\tfor s.Scan() {\n\t\tfields := strings.Fields(s.Text())\n\t\tif len(fields) < 2 {\n\t\t\treturn fmt.Errorf(\"unexpected configuration returned from git: %v\", s.Text())\n\t\t}\n\n\t\tswitch fields[0] {\n\t\tcase \"bits.deduplication-scope\":\n\t\t\tscope, err := strconv.ParseUint(fields[1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unexpected format for configured dedup scope '%v', expected a base10 number\", fields[1])\n\t\t\t}\n\n\t\t\tconf.DeduplicationScope = scope\n\t\tcase \"bits.aws-s3-bucket-name\":\n\t\t\tconf.AWSS3BucketName = fields[1]\n\t\tcase \"bits.aws-access-key-id\":\n\t\t\tconf.AWSAccessKeyID = fields[1]\n\t\tcase \"bits.aws-secret-access-key\":\n\t\t\tconf.AWSSecretAccessKey = fields[1]\n\t\t}\n\t}\n\n\treturn nil\n}", "func FetchConfig(ctx context.Context, c *github.Client, owner, repo, path string, out interface{}) error {\n\treturn fetchConfig(ctx, c.Repositories, owner, repo, path, out)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FindRepository locates repository object search from the given dir.
func FindRepository(dir string) (*Repository, error) { var ( gitDir string commonDir string workDir string gitConfig GitConfig err error ) gitDir, err = findGitDir(dir) if err != nil { return nil, err } commonDir, err = getGitCommonDir(gitDir) if err != nil { return nil, err } gitConfig, err = LoadFileWithDefault(filepath.Join(commonDir, "config")) if err != nil { return nil, err } if !gitConfig.GetBool("core.bare", false) { workDir, _ = getWorkTree(gitDir) } return &Repository{ gitDir: gitDir, gitCommonDir: commonDir, workDir: workDir, gitConfig: gitConfig, }, nil }
[ "func FindRepository(ctx context.Context, exec boil.ContextExecutor, iD string, selectCols ...string) (*Repository, error) {\n\trepositoryObj := &Repository{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from `repositories` where `id`=?\", sel,\n\t)\n\n\tq := queries.Raw(query, iD)\n\n\terr := q.Bind(ctx, exec, repositoryObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from repositories\")\n\t}\n\n\treturn repositoryObj, nil\n}", "func Find(path string) (*Repository, error) {\n\t// get the full path of the directory\n\tp, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if we reach the root directory, we return error\n\tif p == \"/\" {\n\t\treturn nil, errors.New(\"no git repository found\")\n\t}\n\n\t// create path of the git config directory\n\tdir := filepath.Join(p, gitPath)\n\tif f, err := os.Stat(dir); !os.IsNotExist(err) {\n\t\tif !f.IsDir() {\n\t\t\treturn nil, fmt.Errorf(\"'%s' is not a directory\", dir)\n\t\t}\n\n\t\t// We have found the git directory\n\t\tr, err := NewRepository(p, false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn r, nil\n\t}\n\n\t// walk up the directories\n\treturn Find(filepath.Join(p, \"..\"))\n}", "func (f *RepoFinder) Find() error {\n\tif _, err := Exists(f.root); err != nil {\n\t\treturn err\n\t}\n\n\twalkOpts := &godirwalk.Options{\n\t\tErrorCallback: f.errorCb,\n\t\tCallback: f.walkCb,\n\t\t// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.\n\t\tUnsorted: true,\n\t}\n\n\terr := godirwalk.Walk(f.root, walkOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(f.repos) == 0 {\n\t\treturn fmt.Errorf(\"no git repos found in root path %s\", f.root)\n\t}\n\n\treturn nil\n}", "func (s *repositoryService) Find(ctx context.Context, repo string) (*scm.Repository, *scm.Response, error) {\n\tpath := fmt.Sprintf(\"2.0/repositories/%s\", repo)\n\tout := new(repository)\n\tres, err := s.client.do(ctx, \"GET\", path, nil, out)\n\treturn convertRepository(out), res, err\n}", "func FindRepos(repos interface{}) error {\n\terr := MysqlDB.Table(\"ansible_repository\").Find(repos)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Service) MatchRepository(ctx context.Context, q *apiclient.RepositoryRequest) (*apiclient.RepositoryResponse, error) {\n\tvar repoResponse apiclient.RepositoryResponse\n\tconfig := s.initConstants.PluginConfig\n\tif config.Spec.Discover.FileName != \"\" {\n\t\tlog.Debugf(\"config.Spec.Discover.FileName is provided\")\n\t\tpattern := strings.TrimSuffix(q.Path, \"/\") + \"/\" + strings.TrimPrefix(config.Spec.Discover.FileName, \"/\")\n\t\tmatches, err := filepath.Glob(pattern)\n\t\tif err != nil || len(matches) == 0 {\n\t\t\tlog.Debugf(\"Could not find match for pattern %s. Error is %v.\", pattern, err)\n\t\t\treturn &repoResponse, err\n\t\t} else if len(matches) > 0 {\n\t\t\trepoResponse.IsSupported = true\n\t\t\treturn &repoResponse, nil\n\t\t}\n\t}\n\n\tif config.Spec.Discover.Find.Glob != \"\" {\n\t\tlog.Debugf(\"config.Spec.Discover.Find.Glob is provided\")\n\t\tpattern := strings.TrimSuffix(q.Path, \"/\") + \"/\" + strings.TrimPrefix(config.Spec.Discover.Find.Glob, \"/\")\n\t\t// filepath.Glob doesn't have '**' support hence selecting third-party lib\n\t\t// https://github.com/golang/go/issues/11862\n\t\tmatches, err := zglob.Glob(pattern)\n\t\tif err != nil || len(matches) == 0 {\n\t\t\tlog.Debugf(\"Could not find match for pattern %s. Error is %v.\", pattern, err)\n\t\t\treturn &repoResponse, err\n\t\t} else if len(matches) > 0 {\n\t\t\trepoResponse.IsSupported = true\n\t\t\treturn &repoResponse, nil\n\t\t}\n\t}\n\n\tlog.Debugf(\"Going to try runCommand.\")\n\tfind, err := runCommand(config.Spec.Discover.Find.Command, q.Path, os.Environ())\n\tif err != nil {\n\t\treturn &repoResponse, err\n\t}\n\n\tvar isSupported bool\n\tif find != \"\" {\n\t\tisSupported = true\n\t}\n\treturn &apiclient.RepositoryResponse{\n\t\tIsSupported: isSupported,\n\t}, nil\n}", "func FindRepository(projectId string) (*Repository, error) {\n\trepository := &Repository{}\n\tq := db.Query(bson.M{RepoProjectKey: projectId})\n\terr := db.FindOneQ(RepositoriesCollection, q, repository)\n\tif adb.ResultsNotFound(err) {\n\t\treturn nil, nil\n\t}\n\treturn repository, err\n}", "func requestedRepository(repoName string) (repository.Repository, error) {\n\t/*\t_, repoName, err := parseGitCommand(sshcmd)\n\t\tif err != nil {\n\t\t\treturn repository.Repository{}, err\n\t\t}*/\n\tvar repo repository.Repository\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn repository.Repository{}, err\n\t}\n\tdefer conn.Close()\n\tif err := conn.Repository().Find(bson.M{\"_id\": repoName}).One(&repo); err != nil {\n\t\treturn repository.Repository{}, errors.New(\"Repository not found\")\n\t}\n\treturn repo, nil\n}", "func (r *RepoFinder) Find() ([]string, error) {\n\tif _, err := Exists(r.root); err != nil {\n\t\treturn nil, err\n\t}\n\n\twalkOpts := &godirwalk.Options{\n\t\tErrorCallback: r.errorCb,\n\t\tCallback: r.walkCb,\n\t\t// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.\n\t\tUnsorted: true,\n\t}\n\n\terr := godirwalk.Walk(r.root, walkOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(r.repos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no git repos found in root path %s\", r.root)\n\t}\n\n\treturn r.repos, nil\n}", "func (u *Updater) FindRepositories() error {\n\treturn filepath.Walk(u.root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn err\n\t\t}\n\t\tif info.Name() != \".git\" {\n\t\t\t// Skip\n\t\t\treturn nil\n\t\t}\n\t\tgitPath := filepath.Dir(path)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": gitPath,\n\t\t}).Info(\"found git repository\")\n\t\tu.repositories = append(u.repositories, gitPath)\n\t\treturn nil\n\t})\n}", "func (i Index) FindRepository(repo Repository) (RepositoryInIndex, error) {\n\tfor _, r := range i.Repositories {\n\t\tif r.Equals(repo) {\n\t\t\treturn r, nil\n\t\t}\n\t}\n\treturn RepositoryInIndex{}, fmt.Errorf(\"repository %v was not found in index\", repo)\n}", "func Find(dir string) (string, error) {\n\tvar stopAt []*regexp.Regexp\n\tstopAt = append(stopAt, srcDirRegexps...)\n\tstopAt = append(stopAt, vendorRegexp)\n\treturn findUpwards(dir, licenseRegexp, stopAt)\n}", "func (s *Service) ResolveRepositoryBySearch(name string) (*RepositoryInfo, error) {\n\treturn s.Config.NewRepositoryInfo(name, true)\n}", "func (s *REST) findImageRepository(dockerRepo string) (*api.ImageRepository, error) {\n\t//TODO make this more efficient\n\tlist, err := s.imageRepositoryRegistry.ListImageRepositories(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar repo *api.ImageRepository\n\tfor _, r := range list.Items {\n\t\tif dockerRepo == r.DockerImageRepository {\n\t\t\trepo = &r\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn repo, nil\n}", "func FindRepoRoot(dir string) (string, error) {\n\tdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor {\n\t\tfor _, workspaceFile := range workspaceFiles {\n\t\t\tfilepath := filepath.Join(dir, workspaceFile)\n\t\t\tinfo, err := os.Stat(filepath)\n\t\t\tif err == nil && !info.IsDir() {\n\t\t\t\treturn dir, nil\n\t\t\t}\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\tif strings.HasSuffix(dir, string(os.PathSeparator)) { // stop at root dir\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\tdir = filepath.Dir(dir)\n\t}\n}", "func Find(dir string, rootDir string, classifier Classifier) (string, error) {\n\tdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trootDir, err = filepath.Abs(rootDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !strings.HasPrefix(dir, rootDir) {\n\t\treturn \"\", fmt.Errorf(\"licenses.Find: rootDir %s should contain dir %s\", rootDir, dir)\n\t}\n\tfound, err := findUpwards(dir, licenseRegexp, rootDir, func(path string) bool {\n\t\t// TODO(RJPercival): Return license details\n\t\tif _, err := classifier.Identify(path); err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\tif err != nil {\n\t\tif errors.Is(err, errNotFound) {\n\t\t\treturn \"\", fmt.Errorf(\"cannot find a known open source license for %q whose name matches regexp %s and locates up until %q\", dir, licenseRegexp, rootDir)\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"finding a known open source license: %w\", err)\n\t}\n\treturn found, nil\n}", "func (c *TestContext) FindRepoRoot() string {\n\tgoMod := c.findRepoFile(\"go.mod\")\n\treturn filepath.Dir(goMod)\n}", "func findAnyRepo(importPath string) RemoteRepo {\n\tfor _, v := range vcsMap {\n\t\ti := strings.Index(importPath+\"/\", v.suffix+\"/\")\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.Contains(importPath[:i], \"/\") {\n\t\t\tcontinue // don't match vcs suffix in the host name\n\t\t}\n\t\treturn &anyRepo{\n\t\t\tbaseRepo{\n\t\t\t\troot: importPath[:i] + v.suffix,\n\t\t\t\tvcs: v,\n\t\t\t},\n\t\t\timportPath[:i],\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Client) RepoSearch(params *RepoSearchParams, authInfo runtime.ClientAuthInfoWriter) (*RepoSearchOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRepoSearchParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"repoSearch\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/repos/search\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &RepoSearchReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*RepoSearchOK), nil\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CheckSemanticTitle checks if the given PR contains semantic title
func CheckSemanticTitle(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string { change := ghservice.NewRepositoryChangeForPR(pr) prefixes := GetValidTitlePrefixes(config) isTitleWithValidType := HasTitleWithValidType(prefixes, *pr.Title) if !isTitleWithValidType { if prefix, ok := wip.GetWorkInProgressPrefix(*pr.Title, wip.LoadConfiguration(logger, change)); ok { trimmedTitle := strings.TrimPrefix(*pr.Title, prefix) isTitleWithValidType = HasTitleWithValidType(prefixes, trimmedTitle) } } if !isTitleWithValidType { allPrefixes := "`" + strings.Join(prefixes, "`, `") + "`" return fmt.Sprintf(TitleFailureMessage, pr.GetTitle(), allPrefixes) } return "" }
[ "func testFrontMatterTitle(mdBytes []byte) error {\n\tfm, _, err := frontparser.ParseFrontmatterAndContent(mdBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, exists := fm[\"title\"]; exists == false {\n\t\treturn errors.New(\"can't find title in frontmatter\")\n\t}\n\treturn nil\n}", "func TitleValidate(field validator.FieldLevel) bool {\n\treturn strings.Contains(field.Field().String(), \"cool\")\n}", "func IsTitle(r rune) bool", "func (p *piPlugin) titleIsValid(title string) bool {\n\treturn p.titleRegexp.MatchString(title)\n}", "func (me TSearchHITsSortProperty) IsTitle() bool { return me.String() == \"Title\" }", "func (me TGetReviewableHITsSortProperty) IsTitle() bool { return me.String() == \"Title\" }", "func IsTitle(rune int) bool {\n\tif rune < 0x80 {\t// quick ASCII check\n\t\treturn false\n\t}\n\treturn Is(Title, rune);\n}", "func testFrontmatterTitle(path string) error {\n\tif strings.HasSuffix(path, \".md\") {\n\t\tfileBytes, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// if file has frontmatter\n\t\tif frontparser.HasFrontmatterHeader(fileBytes) {\n\t\t\tfm, _, err := frontparser.ParseFrontmatterAndContent(fileBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// skip markdowns that are not published\n\t\t\tif published, exists := fm[\"published\"]; exists {\n\t\t\t\tif publishedBool, ok := published.(bool); ok {\n\t\t\t\t\tif publishedBool == false {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif _, exists := fm[\"title\"]; exists == false {\n\t\t\t\treturn errors.New(\"can't find title in frontmatter\")\n\t\t\t}\n\t\t} else {\n\t\t\t// no frontmatter is not an error\n\t\t\t// markdown files without frontmatter won't be considered\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func IsTitle(r rune) bool {\n\treturn is(title, r)\n}", "func areTitle(line1, line2 string) bool {\n\treturn len(strings.Replace(line1, \" \", \"\", -1)) > 0 &&\n\t\tlen(line2) > 0 &&\n\t\tlen(strings.Replace(line2, \"=\", \"\", -1)) == 0\n}", "func (o *Content) GetTitleOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Title.Get(), o.Title.IsSet()\n}", "func TestFrontMatterTitle(t *testing.T) {\n\tfilepath.Walk(\"/docs\", func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tt.Error(err.Error(), \"-\", path)\n\t\t}\n\t\tpublished, mdBytes, err := isPublishedMarkdown(path)\n\t\tif err != nil {\n\t\t\tt.Error(err.Error(), \"-\", path)\n\t\t}\n\t\tif published == false {\n\t\t\treturn nil\n\t\t}\n\t\terr = testFrontMatterTitle(mdBytes)\n\t\tif err != nil {\n\t\t\tt.Error(err.Error(), \"-\", path)\n\t\t}\n\t\treturn nil\n\t})\n}", "func parseTitle(fs http.FileSystem, path string) (string, error) {\n\tf, err := fs.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tdoc, err := titlesContext.Parse(f, path, present.TitlesOnly)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn doc.Title, nil\n}", "func (m *ReviewMutation) Title() (r string, exists bool) {\n\tv := m.title\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *ArticleMutation) Title() (r string, exists bool) {\n\tv := m.title\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func HasTitleWithValidType(prefixes []string, title string) bool {\n\tpureTitle := strings.TrimSpace(title)\n\tfor _, prefix := range prefixes {\n\t\tprefixRegexp := regexp.MustCompile(`(?i)^` + prefix + `(:| |\\()+`)\n\t\tif prefixRegexp.MatchString(pureTitle) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func getTitle(w http.ResponseWriter, r *http.Request) (string, error) {\n\tm := validPath.FindStringSubmatch(r.URL.Path)\n\tif m == nil {\n\t\thttp.NotFound(w, r)\t// 404 not found http error\n\t\treturn \"\", errors.New(\"Invalid Page Title\")\n\t}\n\treturn m[2], nil // The title is the second subexpression\n}", "func (m *NametitleMutation) Title() (r string, exists bool) {\n\tv := m._Title\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *PostMutation) Title() (r string, exists bool) {\n\tv := m.title\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CheckDescriptionLength checks if the given PR's description contains enough number of arguments
func CheckDescriptionLength(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string { actualLength := len(strings.TrimSpace(issueLinkRegexp.ReplaceAllString(pr.GetBody(), ""))) if actualLength < config.DescriptionContentLength { return fmt.Sprintf(DescriptionLengthShortMessage, config.DescriptionContentLength, actualLength) } return "" }
[ "func CheckDescription(s string) error {\n\tif len(s) > 2000 {\n\t\treturn errors.New(\"exceeds max length (2000 characters)\")\n\t}\n\n\treturn nil\n}", "func CheckArgsLength(args []string, expectedLength int) error {\r\n\tif len(args) != expectedLength {\r\n\t\treturn fmt.Errorf(\"invalid number of arguments. Expected %v, got %v\", expectedLength, len(args))\r\n\t}\r\n\treturn nil\r\n}", "func ErrDescriptionLength(descriptor string, got, max int) sdk.Error {\n\treturn sdkerrors.New(DefaultCodespace, CodeInvalidDescriptionLength,\n\t\tfmt.Sprintf(\"bad description length for %v, got length %v, max is %v\", descriptor, got, max))\n}", "func IsValidArgsLength(args []string, n int) bool {\n\tif args == nil && n == 0 {\n\t\treturn true\n\t}\n\tif args == nil {\n\t\treturn false\n\t}\n\n\tif n < 0 {\n\t\treturn false\n\t}\n\n\targsNr := len(args)\n\tif argsNr < n || argsNr > n {\n\t\treturn false\n\t}\n\treturn true\n}", "func (d Description) EnsureLength() (Description, error) {\n\tif len(d.Moniker) > MaxMonikerLength {\n\t\treturn d, ErrDescriptionLength(\"moniker\", len(d.Moniker), MaxMonikerLength)\n\t}\n\tif len(d.Identity) > MaxIdentityLength {\n\t\treturn d, ErrDescriptionLength(\"identity\", len(d.Identity), MaxIdentityLength)\n\t}\n\tif len(d.Website) > MaxWebsiteLength {\n\t\treturn d, ErrDescriptionLength(\"website\", len(d.Website), MaxWebsiteLength)\n\t}\n\tif len(d.Details) > MaxDetailsLength {\n\t\treturn d, ErrDescriptionLength(\"details\", len(d.Details), MaxDetailsLength)\n\t}\n\n\treturn d, nil\n}", "func (d Description) EnsureLength() (Description, error) {\n\tif len(d.Moniker) > MaxMonikerLength {\n\t\treturn d, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"invalid moniker length; got: %d, max: %d\", len(d.Moniker), MaxMonikerLength)\n\t}\n\tif len(d.Identity) > MaxIdentityLength {\n\t\treturn d, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"invalid identity length; got: %d, max: %d\", len(d.Identity), MaxIdentityLength)\n\t}\n\tif len(d.Website) > MaxWebsiteLength {\n\t\treturn d, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"invalid website length; got: %d, max: %d\", len(d.Website), MaxWebsiteLength)\n\t}\n\tif len(d.Details) > MaxDetailsLength {\n\t\treturn d, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"invalid details length; got: %d, max: %d\", len(d.Details), MaxDetailsLength)\n\t}\n\n\treturn d, nil\n}", "func (a *Asserts) Length(obtained any, expected int, msgs ...string) bool {\n\tok, l, err := hasLength(obtained, expected)\n\tif err != nil {\n\t\treturn a.failer.Fail(Length, ValueDescription(obtained), expected, err.Error())\n\t}\n\tif !ok {\n\t\treturn a.failer.Fail(Length, l, expected, msgs...)\n\t}\n\treturn true\n}", "func CheckLongDesc(cmd *cobra.Command) []error {\n\tfmt.Fprint(os.Stdout, \" ↳ checking long description\\n\")\n\tcmdPath := cmd.CommandPath()\n\tlong := cmd.Long\n\tif len(long) > 0 {\n\t\tif strings.Trim(long, \" \\t\\n\") != long {\n\t\t\treturn []error{fmt.Errorf(`command %q: long description is not normalized, make sure you are calling templates.LongDesc (from pkg/cmd/templates) before assigning cmd.Long`, cmdPath)}\n\t\t}\n\t}\n\treturn nil\n}", "func verifyLen(eventName string, parts []string, n int) (string, error) {\n\tif len(parts) < n {\n\t\treturn \"\", fmt.Errorf(\"%s: got %d parts, want %d\", eventName, len(parts), n)\n\t}\n\tif len(parts) > n {\n\t\treturn fmt.Sprintf(\"%s: got %d parts, expected %d\", eventName, len(parts), n), nil\n\t}\n\treturn \"\", nil\n}", "func TestLength(t *testing.T) {\n\tis := is.New(t)\n\n\titem := Item{\n\t\tText: strings.Repeat(\"x\", 20),\n\t\tParams: ItemParams{\n\t\t\tLength: 10,\n\t\t},\n\t}\n\tdisplayText := item.DisplayText()\n\tis.Equal(displayText, \"xxxxxxxxx…\")\n\n\titem = Item{\n\t\tText: strings.Repeat(\"x\", 20),\n\t\tParams: ItemParams{\n\t\t\tLength: 30,\n\t\t},\n\t}\n\tdisplayText = item.DisplayText()\n\tis.Equal(displayText, strings.Repeat(\"x\", 20))\n}", "func checkLength(t *testing.T, m simple.Manifest, length int) {\n\tt.Helper()\n\n\tif m.Length() != length {\n\t\tt.Fatalf(\"expected length to be %d, but is %d instead\", length, m.Length())\n\t}\n}", "func lengthCheck(name string, array []byte, expected int) error {\n\tif len(array) != expected {\n\t\treturn fmt.Errorf(\"length of %s should be %d\", name, expected)\n\t}\n\treturn nil\n}", "func Length(param string, min int, max int) error {\n\tlength := len(param)\n\tif min != -1 && length < min {\n\t\treturn fmt.Errorf(\"length of string %s %d, expected > %d\", param, length, min)\n\t}\n\tif max != -1 && length > max {\n\t\treturn fmt.Errorf(\"length of string %s %d, expected < %d\", param, length, max)\n\t}\n\treturn nil\n}", "func ShouldHaveLength(actual interface{}, expected ...interface{}) error {\n\tif err := need(1, expected); err != nil {\n\t\treturn err\n\t}\n\n\tlength, err := cast.ToInt64E(expected[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar actualLength int\n\n\tvalue := reflect.ValueOf(actual)\n\tswitch value.Kind() {\n\tcase reflect.Slice, reflect.Chan, reflect.Map, reflect.String:\n\t\tactualLength = value.Len()\n\t\tif value.Len() == int(length) {\n\t\t\treturn nil\n\t\t}\n\tcase reflect.Ptr:\n\t\telem := value.Elem()\n\t\tkind := elem.Kind()\n\t\tactualLength = elem.Len()\n\t\tif (kind == reflect.Slice || kind == reflect.Array) && actualLength == int(length) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"expected '%v' have length of %d but it wasn't (%d)\", actual, length, actualLength)\n}", "func (a *ApplicationDescription) Len() int {\n\tvar l = 4\n\tif a.ApplicationURI != nil {\n\t\tl += a.ApplicationURI.Len()\n\t}\n\tif a.ProductURI != nil {\n\t\tl += a.ProductURI.Len()\n\t}\n\tif a.ApplicationName != nil {\n\t\tl += a.ApplicationName.Len()\n\t}\n\tif a.GatewayServerURI != nil {\n\t\tl += a.GatewayServerURI.Len()\n\t}\n\tif a.DiscoveryProfileURI != nil {\n\t\tl += a.DiscoveryProfileURI.Len()\n\t}\n\tif a.DiscoveryURIs != nil {\n\t\tl += a.DiscoveryURIs.Len()\n\t}\n\n\treturn l\n}", "func Len(t TestingT, v interface{}, length int, extras ...interface{}) bool {\n\tn, ok := tryLen(v)\n\tif !ok {\n\t\t_, acts := toString(nil, v)\n\n\t\treturn Errorf(t, fmt.Sprintf(\"Expect to apply buildin len() on %s\", acts), []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t})\n\t}\n\n\tif n != length {\n\t\t_, acts := toString(nil, v)\n\n\t\treturn Errorf(t, fmt.Sprintf(\"Expect %s to have %d item(s)\", acts, length), []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: strconv.Itoa(length),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: strconv.Itoa(n),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func lengthRule(ctx *Context, arg *Argument) error {\n\tif arg.Value == \"\" || arg.Value == \"~\" {\n\t\treturn errors.Format(\"rule `length` expected 1-2 arguments like: (5), [3~8) etc\")\n\t}\n\n\tpair := strings.Split(arg.Value, \"~\")\n\tif len(pair) > 2 {\n\t\treturn errors.Format(\"invalid argument for rule `length`: %v\", arg.Value)\n\t}\n\n\tv := reflects.Indirect(ctx.Value)\n\tif err := assertKind(\"length\", ctx, v, reflect.String, reflect.Slice, reflect.Map, reflect.Chan); err != nil {\n\t\treturn err\n\t}\n\n\tl := v.Len()\n\tif len(pair) == 1 {\n\t\tlength, err := strconv.Atoi(arg.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn assert(l == length, \"length1\", ctx, arg, l)\n\t} else if len(pair) == 2 {\n\t\tstart, err := toInt(pair[0], -1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tend, err := toInt(pair[1], math.MaxInt32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif arg.Left == LeftOpen {\n\t\t\terr = assert(l > start, \"length2\", ctx, arg, l)\n\t\t} else if arg.Left == LeftSquare {\n\t\t\terr = assert(l >= start, \"length2\", ctx, arg, l)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif arg.Right == RightOpen {\n\t\t\terr = assert(l < end, \"length2\", ctx, arg, l)\n\t\t} else if arg.Right == RightSquare {\n\t\t\terr = assert(l <= end, \"length2\", ctx, arg, l)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Len(t Testing, v interface{}, length int, formatAndArgs ...interface{}) bool {\n\tn, ok := getLen(v)\n\tif !ok {\n\t\treturn Fail(t,\n\t\t\tpretty.Sprintf(\"Could not apply len() with %# v\", v),\n\t\t\tformatAndArgs...)\n\t}\n\n\tif n != length {\n\t\treturn Fail(t,\n\t\t\tpretty.Sprintf(\"Expected %# v should have %d item(s), but got: %d item(s)\", v, length, n),\n\t\t\tformatAndArgs...)\n\t}\n\n\treturn true\n}", "func (t *Check) Length(length string, array []interface{}) (bool, error) {\n\tl, err := strconv.Atoi(length)\n\treturn l == len(array), err\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CheckIssueLinkPresence checks if the given PR's description contains an issue link
func CheckIssueLinkPresence(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string { if !issueLinkRegexp.MatchString(pr.GetBody()) { return IssueLinkMissingMessage } return "" }
[ "func CheckDescriptionLength(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string {\n\tactualLength := len(strings.TrimSpace(issueLinkRegexp.ReplaceAllString(pr.GetBody(), \"\")))\n\tif actualLength < config.DescriptionContentLength {\n\t\treturn fmt.Sprintf(DescriptionLengthShortMessage, config.DescriptionContentLength, actualLength)\n\t}\n\treturn \"\"\n}", "func ifPullRequest(issue *github.Issue) bool {\n\tif issue.PullRequestLinks != nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func (mt *ProposalLink) Validate() (err error) {\n\tif mt.Title != nil {\n\t\tif len(*mt.Title) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.title`, *mt.Title, len(*mt.Title), 10, true))\n\t\t}\n\t}\n\tif mt.Title != nil {\n\t\tif len(*mt.Title) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.title`, *mt.Title, len(*mt.Title), 200, false))\n\t\t}\n\t}\n\treturn\n}", "func (o *NiaapiNewReleaseDetailAllOf) HasReleaseNoteLinkTitle() bool {\n\tif o != nil && o.ReleaseNoteLinkTitle != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsIssueReference(name string) bool {\n\treturn regexp.MustCompile(fmt.Sprintf(\"^refs/heads/%s/[1-9]+([0-9]+)?$\", IssueBranchPrefix)).MatchString(name)\n}", "func isAccessibleLink(hg HttpGetter, url string) bool {\n\tresponse, err := hg(url)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif response.StatusCode == http.StatusOK {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func hasLinkValidation(cond []string) bool {\n\tfor _, c := range cond {\n\t\tif c != \"html\" /* && c != \"css\" */ {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isValidLink(link string) bool {\n\tresponse, err := http.Get(link)\n\tif err != nil {\n\t\tfmt.Println(\"Link is not a http link\", err)\n\t}\n\tdefer response.Body.Close()\n\tif response.StatusCode == 200 {\n\t\treturn true\n\t}\n\treturn false\n}", "func IsRepoURL(value string) bool {\n\treturn Regex.Match([]byte(value))\n}", "func (o *NiaapiNewReleaseDetailAllOf) HasReleaseNoteLink() bool {\n\tif o != nil && o.ReleaseNoteLink != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (t *Tweet) IsLinkable() {}", "func hasLabel(iss *github.Issue, label string) bool {\n\tfor i := range iss.Labels {\n\t\tif iss.Labels[i].GetName() == label {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isRepoUrl(arg string) bool {\n\targ = strings.ToLower(arg)\n\treturn !filepath.IsAbs(arg) &&\n\t\t(strings.HasPrefix(arg, \"git::\") ||\n\t\t\tstrings.HasPrefix(arg, \"gh:\") ||\n\t\t\tstrings.HasPrefix(arg, \"github.com\") ||\n\t\t\tstrings.HasPrefix(arg, \"git@github.com:\") ||\n\t\t\tstrings.Index(arg, \"github.com/\") > -1)\n}", "func (s *htmlState) checkURL(raw string) {\n\tif s.ignore&issueURL != 0 {\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(raw, \"mailto:\") {\n\t\tif strings.Index(raw, \"@\") == -1 {\n\t\t\ts.err(fmt.Errorf(\"not an email address\"))\n\t\t}\n\t\treturn\n\t}\n\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\ts.err(fmt.Errorf(\"bad URL '%s': %s\", raw, err.Error()))\n\t\treturn\n\t}\n\tif u.Opaque != \"\" {\n\t\ts.err(fmt.Errorf(\"bad URL part '%s'\", u.Opaque))\n\t\treturn\n\t}\n\n\tif strings.Index(raw, \" \") != -1 {\n\t\ts.err(fmt.Errorf(\"unencoded space in URL\"))\n\t}\n}", "func IsIssueReferencePath(name string) bool {\n\treturn regexp.MustCompile(fmt.Sprintf(\"^refs/heads/%s(/|$)?\", IssueBranchPrefix)).MatchString(name)\n}", "func (p Project) HasUrl() bool {\n\treturn p.MainContainer().HasExposedTCPPorts()\n}", "func (o *NiaapiNewReleaseDetailAllOf) GetReleaseNoteLinkTitleOk() (*string, bool) {\n\tif o == nil || o.ReleaseNoteLinkTitle == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ReleaseNoteLinkTitle, true\n}", "func expectedMsg(msg *prowapi.ReportMessage) bool {\n\trepos, err := getReportRepos()\n\tif err != nil {\n\t\tlog.Printf(\"Failed getting reporter's repos: %v\", err)\n\t\treturn false\n\t}\n\texpRepo := false\n\tif len(msg.Refs) > 0 {\n\t\tfor _, repo := range repos {\n\t\t\tif msg.Refs[0].Repo == repo {\n\t\t\t\texpRepo = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn expRepo && msg.Status == prowapi.FailureState && msg.JobType == prowapi.PresubmitJob\n}", "func AssureIsLink(path string) error {\n\terrPrefix := func() string {\n\t\treturn fmt.Sprintf(\"failed asserting that the path %s is a symbolic link\", path)\n\t}\n\tif err := AssureExists(path); err != nil {\n\t\treturn errors.Wrap(err, errPrefix())\n\t}\n\tfileInfoStat, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn errors.Wrap(err, errPrefix())\n\t}\n\tif fileInfoStat.Mode()&os.ModeSymlink != os.ModeSymlink {\n\t\treturn errors.Wrapf(err, \"%s: unexpected file mode: got %v\", errPrefix(), fileInfoStat.Mode())\n\t}\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetValidTitlePrefixes returns list of valid prefixes
func GetValidTitlePrefixes(config PluginConfiguration) []string { prefixes := defaultTypes if len(config.TypePrefix) != 0 { if config.Combine { prefixes = append(prefixes, config.TypePrefix...) } else { prefixes = config.TypePrefix } } return prefixes }
[ "func cleansePrefixes(ss []string) []string {\n\n\tret := []string{}\n\tfor _, s := range ss {\n\t\tstripped := \"\"\n\t\tfor i := len(ss) - 1; i > -1; i-- { // reversely\n\t\t\tpref := ss[i]\n\t\t\tif s != pref && strings.HasPrefix(s, pref) {\n\n\t\t\t\tstripped = strings.TrimPrefix(s, pref)\n\n\t\t\t\tstripped = strings.TrimSpace(stripped)\n\t\t\t\tstripped = strings.TrimPrefix(stripped, \"-- \")\n\t\t\t\tstripped = strings.TrimSuffix(stripped, \" --\")\n\n\t\t\t\t// log.Printf(\"stripped off\\n\\t%q \\n\\t%q \\n\\t%q\", s, pref, stripped)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif stripped == \"\" {\n\t\t\tret = append(ret, s)\n\t\t} else {\n\t\t\tret = append(ret, stripped)\n\t\t}\n\t}\n\n\treturn ret\n\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecFacetKeyOutput) Prefixes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaSearchRequestFacetSpecFacetKey) []string { return v.Prefixes }).(pulumi.StringArrayOutput)\n}", "func (c *HelpCountryCode) GetPrefixes() (value []string, ok bool) {\n\tif c == nil {\n\t\treturn\n\t}\n\tif !c.Flags.Has(0) {\n\t\treturn value, false\n\t}\n\treturn c.Prefixes, true\n}", "func IsValidPathSegmentPrefix(name string) []string {\n\tvar errors []string\n\n\tfor _, illegalContent := range NameMayNotContain {\n\t\tif strings.Contains(name, illegalContent) {\n\t\t\terrors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))\n\t\t}\n\t}\n\n\treturn errors\n}", "func makePrefixMap(ss []string, prefixLen int) prefixMap {\n\tprefixes := make(prefixMap)\n\tfor i, s := range ss {\n\t\t// We use < rather than <= because if a label matches on a prefix equal to\n\t\t// its full length, that's actually a substring match handled by\n\t\t// removeSubstrings.\n\t\tif prefixLen < len(s) {\n\t\t\tprefix := s[:prefixLen]\n\t\t\tprefixes[prefix] = append(prefixes[prefix], i)\n\t\t}\n\t}\n\n\treturn prefixes\n}", "func stripPrefixes(subj string) string {\n\tredo := true\n\tfor redo {\n\t\tredo = false\n\t\tfor _, prefix := range _BAD_PREFIXES {\n\t\t\tif strings.HasPrefix(strings.ToLower(subj), prefix) {\n\t\t\t\tsubj = subj[len(prefix):]\n\t\t\t\tredo = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn subj\n}", "func CreatePrefixList(pkg string) []string {\n\tif pkg == \"\" {\n\t\treturn []string{\"\"}\n\t}\n\n\tnumDots := 0\n\t// one pass to pre-allocate the returned slice\n\tfor i := 0; i < len(pkg); i++ {\n\t\tif pkg[i] == '.' {\n\t\t\tnumDots++\n\t\t}\n\t}\n\tif numDots == 0 {\n\t\treturn []string{pkg, \"\"}\n\t}\n\n\tprefixes := make([]string, numDots+2)\n\t// second pass to fill in returned slice\n\tfor i := 0; i < len(pkg); i++ {\n\t\tif pkg[i] == '.' {\n\t\t\tprefixes[numDots] = pkg[:i]\n\t\t\tnumDots--\n\t\t}\n\t}\n\tprefixes[0] = pkg\n\n\treturn prefixes\n}", "func AnnouncedPrefixes(asn string) (*RipeAnnouncedPrefixesResponse, error) {\n\tfetchURL := \"https://stat.ripe.net/data/announced-prefixes/data.json?soft_limit=ignore&resource=AS%s\"\n\turl := fmt.Sprintf(fetchURL, asn)\n\n\tresp, err := http.Get(url)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result RipeAnnouncedPrefixesResponse\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func HasTitleWithValidType(prefixes []string, title string) bool {\n\tpureTitle := strings.TrimSpace(title)\n\tfor _, prefix := range prefixes {\n\t\tprefixRegexp := regexp.MustCompile(`(?i)^` + prefix + `(:| |\\()+`)\n\t\tif prefixRegexp.MatchString(pureTitle) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func hasPrefixLower(s, prefixLower string) (skip int) {\n\tvar firstSize int\n\tfor i, r := range prefixLower {\n\t\tr2, size := utf8.DecodeRuneInString(s[i:])\n\t\tif firstSize == 0 {\n\t\t\tfirstSize = size\n\t\t}\n\t\tif r2 != r && r2 != unicode.ToUpper(r) {\n\t\t\treturn firstSize\n\t\t}\n\t}\n\treturn 0\n}", "func (kps *KubernetesPrefixSource) Prefixes() []string {\n\treturn kps.prefixes.Load()\n}", "func Prefixes(s string) []string {\n\tprefixes := make(map[string]struct{})\n\n\trunes := make([]rune, 0, 64)\n\n\tfor _, w := range strings.Split(s, \" \") {\n\t\tif w == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\trunes = runes[0:0]\n\n\t\tfor _, c := range w {\n\t\t\trunes = append(runes, c)\n\t\t\tprefixes[string(runes)] = struct{}{}\n\t\t}\n\t}\n\n\ttokens := make([]string, 0, 32)\n\n\tfor pref := range prefixes {\n\t\ttokens = append(tokens, pref)\n\t}\n\n\treturn tokens\n}", "func prefixListing() error {\n\tinputDir := getUserHome() + \"/sequence_lists/genbank_prefixes\"\n\tfiles, err := ioutil.ReadDir(inputDir)\n\tif err != nil {\n\t\treturn handle(\"Error in reading dir\", err)\n\t}\n\t// Gets a list of the prefixes found in the files and puts them into a\n\t// sorted list.\n\tres := []string{}\n\tfor _, f := range files {\n\t\tfname := f.Name()\n\t\tfileResult, err := prefixListForFile(inputDir+\"/\"+fname, fname)\n\t\tif err != nil {\n\t\t\treturn handle(\"Error in getting prefix list from file\", err)\n\t\t}\n\t\tres = append(res, fileResult)\n\t}\n\tsort.Sort(naturalsort.NaturalSort(res))\n\tfor _, v := range res {\n\t\tfmt.Println(v)\n\t}\n\treturn err\n}", "func (c *config) PrefixKeys(prefix string) []string {\n c.m.Lock()\n defer c.m.Unlock()\n\n keys := []string{}\n for k, _ := range c.conf {\n if strings.HasPrefix(k, prefix) {\n keys = append(keys, k)\n }\n }\n return keys\n}", "func generatePrefixes() []string {\n\tprefixes := []string{}\n\tletters := []string{\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"}\n\tfor _, l := range letters {\n\t\tfor i := 1; i < 10; i++ {\n\t\t\tprefixes = append(prefixes, fmt.Sprintf(\"%s%d\", l, i))\n\t\t}\n\t}\n\treturn prefixes\n}", "func NamePrefixes() []string {\n\ts := UserID.String()\n\treturn []string{\"<@\" + s + \">\", \"<@!\" + s + \">\", \"1dot\"}\n}", "func (pc PrefixCodes) checkPrefixes() bool {\n\tfor i, c1 := range pc {\n\t\tfor j, c2 := range pc {\n\t\t\tmask := uint32(1)<<c1.Len - 1\n\t\t\tif i != j && c1.Len <= c2.Len && c1.Val&mask == c2.Val&mask {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func KnownDoHPrefixes() []string {\n\tpopulateOnce.Do(populate)\n\tret := make([]string, 0, len(dohIPsOfBase))\n\tfor b := range dohIPsOfBase {\n\t\tret = append(ret, b)\n\t}\n\tsort.Strings(ret)\n\treturn ret\n}", "func HandlePrefixList(prefixes ...string) SkipperFunc {\n\treturn func(c *gin.Context) bool {\n\t\tpath := c.Request.URL.Path\n\t\tpathLen := len(path)\n\n\t\tfor _, p := range prefixes {\n\t\t\tif pl := len(p); pathLen >= pl && path[:pl] == p {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HasTitleWithValidType checks if title prefix conforms with semantic message style.
func HasTitleWithValidType(prefixes []string, title string) bool { pureTitle := strings.TrimSpace(title) for _, prefix := range prefixes { prefixRegexp := regexp.MustCompile(`(?i)^` + prefix + `(:| |\()+`) if prefixRegexp.MatchString(pureTitle) { return true } } return false }
[ "func TitleValidate(field validator.FieldLevel) bool {\n\treturn strings.Contains(field.Field().String(), \"cool\")\n}", "func (p *piPlugin) titleIsValid(title string) bool {\n\treturn p.titleRegexp.MatchString(title)\n}", "func CheckSemanticTitle(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string {\n\tchange := ghservice.NewRepositoryChangeForPR(pr)\n\tprefixes := GetValidTitlePrefixes(config)\n\tisTitleWithValidType := HasTitleWithValidType(prefixes, *pr.Title)\n\n\tif !isTitleWithValidType {\n\t\tif prefix, ok := wip.GetWorkInProgressPrefix(*pr.Title, wip.LoadConfiguration(logger, change)); ok {\n\t\t\ttrimmedTitle := strings.TrimPrefix(*pr.Title, prefix)\n\t\t\tisTitleWithValidType = HasTitleWithValidType(prefixes, trimmedTitle)\n\t\t}\n\t}\n\tif !isTitleWithValidType {\n\t\tallPrefixes := \"`\" + strings.Join(prefixes, \"`, `\") + \"`\"\n\t\treturn fmt.Sprintf(TitleFailureMessage, pr.GetTitle(), allPrefixes)\n\t}\n\treturn \"\"\n}", "func IsTitle(rune int) bool {\n\tif rune < 0x80 {\t// quick ASCII check\n\t\treturn false\n\t}\n\treturn Is(Title, rune);\n}", "func IsTitle(r rune) bool {\n\treturn is(title, r)\n}", "func (me TxsdPersonNameTypeSequenceAlternateScriptSequenceAffixSimpleContentExtensionType) IsAristocraticTitle() bool {\n\treturn me.String() == \"aristocraticTitle\"\n}", "func (me TSearchHITsSortProperty) IsTitle() bool { return me.String() == \"Title\" }", "func (me TGetReviewableHITsSortProperty) IsTitle() bool { return me.String() == \"Title\" }", "func (o *TalangAttribute) HasTitle() bool {\n\tif o != nil && o.Title != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *GroupWidgetDefinition) HasTitle() bool {\n\tif o != nil && o.Title != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsTitle(r rune) bool", "func (d UserData) HasTitle() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"Title\", \"title_id\"))\n}", "func GetValidTitlePrefixes(config PluginConfiguration) []string {\n\tprefixes := defaultTypes\n\tif len(config.TypePrefix) != 0 {\n\t\tif config.Combine {\n\t\t\tprefixes = append(prefixes, config.TypePrefix...)\n\t\t} else {\n\t\t\tprefixes = config.TypePrefix\n\t\t}\n\t}\n\treturn prefixes\n}", "func (m *TitleMutation) TitleType() (r string, exists bool) {\n\tv := m._Title_type\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func IsTitleUnsafe(r rune) bool {\n\treturn isUnsafe(title, r)\n}", "func (me *XsdGoPkgHasElem_TitlesequencePlatformBaseTypeschema_Title_TextType_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TitlesequencePlatformBaseTypeschema_Title_TextType_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.Title.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func testFrontMatterTitle(mdBytes []byte) error {\n\tfm, _, err := frontparser.ParseFrontmatterAndContent(mdBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, exists := fm[\"title\"]; exists == false {\n\t\treturn errors.New(\"can't find title in frontmatter\")\n\t}\n\treturn nil\n}", "func (m *Photo) HasTitle() bool {\n\treturn m.PhotoTitle != \"\"\n}", "func (me *XElemTitlealldescTitleMetadataschemaTitleTtitleType) Walk() (err error) {\n\tif fn := WalkHandlers.XElemTitlealldescTitleMetadataschemaTitleTtitleType; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.Title.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CountCSVRowsGo returns a count of the number of rows in the give csv file
func CountCSVRowsGo(source string) (int, error) { defer un(trace("CountCSVRowsGo")) err := assertValidFilename(source) if err != nil { return 0, err } f, _ := os.Open(source) r := csv.NewReader(bufio.NewReader(f)) rowCount := 0 for { _, err := r.Read() if err == io.EOF { break } rowCount++ } return rowCount, nil }
[ "func countCSVFieldsFromString(str []byte, histogram []int64) {\n\tcountFields(csv.NewReader(bytes.NewReader(str)), histogram)\n}", "func countFields(csvReader *csv.Reader, histogram []int64) {\n\thistogramLen := len(histogram)\n\tcsvReader.FieldsPerRecord = -1 // Tell the CVS reader to expect an unknown field count\n\tfor {\n\t\tstrs, err := csvReader.Read()\n\t\tif nil != err {\n\t\t\tbreak\n\t\t}\n\t\tf := len(strs)\n\t\tif f < histogramLen {\n\t\t\tif 0 < f {\n\t\t\t\thistogram[f]++\n\t\t\t} // There's no such thing as a 0 length field record.\n\t\t} else {\n\t\t\tfmt.Print(\"\\nWARNING:\", histogramLen, \"<\", f, \"histogram length.\")\n\t\t}\n\t}\n\treturn\n}", "func CSVFileInfo(f0 string) (size int64, nRec int64) {\n\tfd0, err := os.Open(f0)\n\tdefer fd0.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfi0, err := fd0.Stat()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbuf0 := bufio.NewReader(fd0)\n\tl0, _, err := buf0.ReadLine()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsize = fi0.Size()\n\tnRec = size / int64(len(l0))\n\treturn\n}", "func (table *Table) NumberOfRows() (int, int) {\n\tvar numberOfRows int\n\tvar dataFileInfo *os.FileInfo\n\tdataFileInfo, err := table.DataFile.Stat()\n\tif err != nil {\n\t\tlogg.Err(\"table\", \"NumberOfRows\", err.String())\n\t\treturn 0, st.CannotStatTableDataFile\n\t}\n\tnumberOfRows = int(dataFileInfo.Size) / table.RowLength\n\treturn numberOfRows, st.OK\n}", "func rowsInFile(fileName string) (int, error) {\n\tfileReader, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer fileReader.Close()\n\treturn lineCounter(fileReader)\n}", "func SQLRowCount(rows *sql.Rows) int {\n\tcount := 0\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\tfmt.Println(strconv.Itoa(count))\n\treturn count\n\n}", "func (c *Collection) ImportCSV(buf io.Reader, idCol int, skipHeaderRow bool, overwrite bool, verboseLog bool) (int, error) {\n\tvar (\n\t\tfieldNames []string\n\t\tkey string\n\t\terr error\n\t)\n\tr := csv.NewReader(buf)\n\tr.FieldsPerRecord = -1\n\tr.TrimLeadingSpace = true\n\tlineNo := 0\n\tif skipHeaderRow == true {\n\t\tlineNo++\n\t\tfieldNames, err = r.Read()\n\t\tif err != nil {\n\t\t\treturn lineNo, fmt.Errorf(\"Can't read header csv table at %d, %s\", lineNo, err)\n\t\t}\n\t}\n\tfor {\n\t\tlineNo++\n\t\trow, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn lineNo, fmt.Errorf(\"Can't read row csv table at %d, %s\", lineNo, err)\n\t\t}\n\t\tvar fieldName string\n\t\trecord := map[string]interface{}{}\n\t\tif idCol < 0 {\n\t\t\tkey = fmt.Sprintf(\"%d\", lineNo)\n\t\t}\n\t\tfor i, val := range row {\n\t\t\tif i < len(fieldNames) {\n\t\t\t\tfieldName = fieldNames[i]\n\t\t\t\tif idCol == i {\n\t\t\t\t\tkey = val\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfieldName = fmt.Sprintf(fmtColumnName, i+1)\n\t\t\t}\n\t\t\t//Note: We need to convert the value\n\t\t\tif i, err := strconv.ParseInt(val, 10, 64); err == nil {\n\t\t\t\trecord[fieldName] = i\n\t\t\t} else if f, err := strconv.ParseFloat(val, 64); err == nil {\n\t\t\t\trecord[fieldName] = f\n\t\t\t} else if strings.ToLower(val) == \"true\" {\n\t\t\t\trecord[fieldName] = true\n\t\t\t} else if strings.ToLower(val) == \"false\" {\n\t\t\t\trecord[fieldName] = false\n\t\t\t} else {\n\t\t\t\tval = strings.TrimSpace(val)\n\t\t\t\tif len(val) > 0 {\n\t\t\t\t\trecord[fieldName] = val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(key) > 0 && len(record) > 0 {\n\t\t\tif c.HasKey(key) {\n\t\t\t\tif overwrite == true {\n\t\t\t\t\terr = c.Update(key, record)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn lineNo, fmt.Errorf(\"can't update %+v to %s, %s\", record, key, err)\n\t\t\t\t\t}\n\t\t\t\t} else if verboseLog {\n\t\t\t\t\tlog.Printf(\"Skipping row %d, key %q, already exists\", lineNo, key)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = c.Create(key, record)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn lineNo, fmt.Errorf(\"can't create %+v to %s, %s\", record, key, err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if verboseLog {\n\t\t\tlog.Printf(\"Skipping row %d, key value missing\", lineNo)\n\t\t}\n\t\tif verboseLog == true && (lineNo%1000) == 0 {\n\t\t\tlog.Printf(\"%d rows processed\", lineNo)\n\t\t}\n\t}\n\treturn lineNo, nil\n}", "func (c *CSVInterpolator) numRows() int64 {\n\tif c.row == 1 {\n\t\treturn rowsNeededToInterpolate - 1\n\t}\n\n\treturn rowsNeededToInterpolate\n}", "func countCSVFieldsFromChunkedReaderWorker(wg *sync.WaitGroup, threadId int, r io.ReadCloser, partials [][]byte, histogram []int64) {\n\tnow := time.Now()\n\tbufr := bufrecs.NewBufRecs(r, threadId) // Create the buffered record reader\n\n\tBufRecs[threadId] = bufr // Keep track of the bufrec for status updates\n\n\tpartials[threadId*2] = bufr.Get() // Keep track of the first record which is assumed to be partial (the rest belonging to the previous thread's chunk.\n\n\tcountFields(csv.NewReader(bufr), histogram) // Count the fields\n\n\tr.Close() // Close the ReadCloser. No longer needed now\n\n\tpartials[threadId*2+1] = recordFlatten(bufr.FinalPartial) // Keep track of the last record, which is assumed to be partisl (the rest belonging to the next thread's chunk).\n\n\tfmt.Printf(\"\\n%d:: done [%s].\", threadId, time.Since(now))\n\twg.Done()\n}", "func (fw *Writer) NumRows() int { return fw.nrows }", "func (r *Result) RowCount() (n int) {\n\tfor _, s := range r.sets {\n\t\tn += len(s.Rows)\n\t}\n\treturn\n}", "func LineCount(r io.Reader, skipEmpty bool) int {\n\tif r == nil {\n\t\treturn -1\n\t}\n\n\tsc := bufio.NewScanner(r)\n\tvar i int\n\n\tif skipEmpty {\n\t\tfor sc.Scan() {\n\t\t\tif len(sc.Bytes()) > 0 {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\n\t\tif sc.Err() != nil {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn i\n\t}\n\n\tfor i = 0; sc.Scan(); i++ {\n\t}\n\n\treturn i\n}", "func (f *File) LineCount() int {}", "func (*mySQL) GetRowCount(r RequestAgGrid, rows int) int64 {\n\tif rows == 0 {\n\t\treturn 0\n\t}\n\n\tcurrentLastRow := r.StartRow + int64(rows)\n\n\tif currentLastRow <= r.EndRow {\n\t\treturn currentLastRow\n\t}\n\treturn -1\n}", "func (c *Chunk) NumRows() int {\n\tif c.NumCols() == 0 {\n\t\treturn c.numVirtualRows\n\t}\n\treturn c.columns[0].length\n}", "func ImportCSVFile(DB services.Database, filePath, tableName string) {\n\tlog.Printf(\"start ImportCSVFile for filePath %s\", filePath)\n\ttimeStampCurrent := time.Now()\n\tlog.Printf(\"time started: %v\", timeStampCurrent)\n\tmysql.RegisterLocalFile(filePath)\n\tres, err := DB.DatabaseConnection.Exec(\"LOAD DATA LOCAL INFILE '\" + filePath + \"' INTO TABLE \" + tableName + \" FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\\\n'\")\n\tif err != nil {\n\t\tlog.Fatalf(\"importCSVFile load err %v\", err)\n\t}\n\tval, err := res.RowsAffected()\n\tif err != nil {\n\t\tlog.Printf(\"res.RowsAffected err %v\", err)\n\t}\n\tmysql.DeregisterLocalFile(filePath)\n\tlog.Printf(\"LOAD DATA LOCAL INFILE took %s time\", time.Since(timeStampCurrent).String())\n\tlog.Printf(\"Rows affected %d\", val)\n\tlog.Printf(\"finished ImportCSVFile for filePath %s\", filePath)\n\n}", "func (bkr *Broker) RowCount(tableName string) (int, error) {\n\ttableName = strings.TrimSpace(tableName)\n\n\tif len(tableName) == 0 {\n\t\treturn -1, errors.New(\"`tableName` cannot be empty or whitespace\")\n\t}\n\n\trow := bkr.database.QueryRow(fmt.Sprintf(\"SELECT COUNT(*) FROM %s\", tableName))\n\n\tvar count int\n\n\tif err := row.Scan(&count); err != nil {\n\t\treturn -1, fmt.Errorf(\"Failed to count rows for table %s: %w\", tableName, err)\n\t}\n\n\treturn count, nil\n}", "func CountNbLines(filename string) int {\n\treader, file := ReturnReader(filename, 0)\n\tdefer CloseFile(file)\n\n\tnbLines := 0\n\n\ttStart := time.Now()\n\n\tfor reader.Scan() {\n\t\tnbLines++\n\t}\n\n\ttDiff := time.Since(tStart)\n\tfmt.Printf(\"Count nb lines done in time: %f s \\n\", tDiff.Seconds())\n\n\treturn nbLines\n}", "func readCSV(csvFileName string) []Record {\n\tvar records []Record\n\n\tcsvFile, err := os.Open(csvFileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer csvFile.Close()\n\n\tr := csv.NewReader(bufio.NewReader(csvFile))\n\tr.Comma = ';'\n\tfor {\n\t\trecord, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// fmt.Printf(\"%T: %v\\n\", record, record)\n\t\tcount, err := strconv.Atoi(record[2])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\trecords = append(records, Record{\n\t\t\tDate: record[0],\n\t\t\tTerm: record[1],\n\t\t\tCount: count,\n\t\t})\n\t}\n\n\treturn records\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the service returns the correct protocol version
func TestServiceProtocolVersion(t *testing.T) { s := res.NewService("test") restest.AssertEqualJSON(t, "ProtocolVersion()", s.ProtocolVersion(), "1.2.2") }
[ "func TestVersion(t *testing.T) {\n\t// First, create a new server and connection.\n\tserverSocket, clientSocket, err := unet.SocketPair(false)\n\tif err != nil {\n\t\tt.Fatalf(\"socketpair got err %v expected nil\", err)\n\t}\n\tdefer clientSocket.Close()\n\n\t// Create a new server and client.\n\ts := NewServer(nil)\n\tgo s.Handle(serverSocket)\n\n\t// NewClient does a Tversion exchange, so this is our test for success.\n\tc, err := NewClient(clientSocket, DefaultMessageSize, HighestVersionString())\n\tif err != nil {\n\t\tt.Fatalf(\"got %v, expected nil\", err)\n\t}\n\n\t// Check a bogus version string.\n\tif err := c.sendRecv(&Tversion{Version: \"notokay\", MSize: DefaultMessageSize}, &Rversion{}); err != unix.EINVAL {\n\t\tt.Errorf(\"got %v expected %v\", err, unix.EINVAL)\n\t}\n\n\t// Check a bogus version number.\n\tif err := c.sendRecv(&Tversion{Version: \"9P1000.L\", MSize: DefaultMessageSize}, &Rversion{}); err != unix.EINVAL {\n\t\tt.Errorf(\"got %v expected %v\", err, unix.EINVAL)\n\t}\n\n\t// Check a too high version number.\n\tif err := c.sendRecv(&Tversion{Version: versionString(highestSupportedVersion + 1), MSize: DefaultMessageSize}, &Rversion{}); err != unix.EAGAIN {\n\t\tt.Errorf(\"got %v expected %v\", err, unix.EAGAIN)\n\t}\n\n\t// Check an invalid MSize.\n\tif err := c.sendRecv(&Tversion{Version: versionString(highestSupportedVersion), MSize: 0}, &Rversion{}); err != unix.EINVAL {\n\t\tt.Errorf(\"got %v expected %v\", err, unix.EINVAL)\n\t}\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func TestGetVersion(t *testing.T) {\n\n\tversion, err := GetVersion()\n\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\n\tif version != \"v1\"{\n\t\tt.Errorf(\"app version not match: %s, expect: %s.\", version, \"v1\")\n\t}\n\n\tfmt.Println(version)\n}", "func VersionCheck(endpoint string) (int, string) {\n\n\turl := fmt.Sprintf(\"%s/version\", endpoint)\n\n\tstatus, body := httpGet(url)\n\tif status != http.StatusOK {\n\t\treturn status, \"\"\n\t}\n\n\tr := VersionResponse{}\n\terr := json.Unmarshal([]byte(body), &r)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: unmarshal of [%s] returns: %s\\n\", body, err)\n\t\treturn http.StatusInternalServerError, \"\"\n\t}\n\n\treturn status, r.Build\n}", "func TestClientVersion(t *testing.T) {\n\t// t.SkipNow()\n\tet := testutil.GetETH()\n\n\tclientVersion, err := et.ClientVersion()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"clientVersion:\", clientVersion)\n}", "func TestGetVersion(t *testing.T) {\n\tv := \"0.0.0\"\n\tmaj, min, patch := getVersion(v)\n\n\tif maj != 0 && min != 0 && patch != 0 {\n\t\tt.Error(\"maj, min or patch are not set to 0\", maj, min, patch)\n\t}\n\n\tv = \"1.2.4\"\n\n\tmaj, min, patch = getVersion(v)\n\n\tif maj != 1 && min != 2 && patch != 4 {\n\t\tt.Error(\"maj, min or patch are not set to 1, 2, 4\", maj, min, patch)\n\t}\n}", "func TestDataprotocols(t *testing.T) {\n\tl := SPL_10\n\tif !supported.Supported(l) {\n\t\tt.Errorf(\"Expected: [true], got: [false] for protocol level %v\\n\", l)\n\t}\n\tl = SPL_11\n\tif !supported.Supported(l) {\n\t\tt.Errorf(\"Expected: [true], got: [false] for protocol level %v\\n\", l)\n\t}\n\tl = \"9.9\"\n\tif supported.Supported(l) {\n\t\tt.Errorf(\"Expected: [false], got: [true] for protocol level %v\\n\", l)\n\t}\n}", "func TestGetVersion(c internalapi.RuntimeService) {\n\tversion, err := c.Version(defaultAPIVersion)\n\tExpectNoError(err, \"failed to get version: %v\", err)\n\tExpect(version.Version).To(Not(BeNil()), \"Version should not be nil\")\n\tExpect(version.RuntimeName).To(Not(BeNil()), \"RuntimeName should not be nil\")\n\tExpect(version.RuntimeVersion).To(Not(BeNil()), \"RuntimeVersion should not be nil\")\n\tExpect(version.RuntimeApiVersion).To(Not(BeNil()), \"RuntimeApiVersion should not be nil\")\n\tLogf(\"Get version info succeed\")\n}", "func (p OpenFlow10Protocol) GetVersion() uint8 {\n\treturn goloxi.VERSION_1_0\n}", "func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) {\n\tprotoVersion := int(opts.ProtocolVersion)\n\tpluginSet := opts.Plugins\n\tprotoType := ProtocolNetRPC\n\t// Check if the client sent a list of acceptable versions\n\tvar clientVersions []int\n\tif vs := os.Getenv(\"PLUGIN_PROTOCOL_VERSIONS\"); vs != \"\" {\n\t\tfor _, s := range strings.Split(vs, \",\") {\n\t\t\tv, err := strconv.Atoi(s)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"server sent invalid plugin version %q\", s)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclientVersions = append(clientVersions, v)\n\t\t}\n\t}\n\n\t// We want to iterate in reverse order, to ensure we match the newest\n\t// compatible plugin version.\n\tsort.Sort(sort.Reverse(sort.IntSlice(clientVersions)))\n\n\t// set the old un-versioned fields as if they were versioned plugins\n\tif opts.VersionedPlugins == nil {\n\t\topts.VersionedPlugins = make(map[int]PluginSet)\n\t}\n\n\tif pluginSet != nil {\n\t\topts.VersionedPlugins[protoVersion] = pluginSet\n\t}\n\n\t// Sort the version to make sure we match the latest first\n\tvar versions []int\n\tfor v := range opts.VersionedPlugins {\n\t\tversions = append(versions, v)\n\t}\n\n\tsort.Sort(sort.Reverse(sort.IntSlice(versions)))\n\n\t// See if we have multiple versions of Plugins to choose from\n\tfor _, version := range versions {\n\t\t// Record each version, since we guarantee that this returns valid\n\t\t// values even if they are not a protocol match.\n\t\tprotoVersion = version\n\t\tpluginSet = opts.VersionedPlugins[version]\n\n\t\t// If we have a configured gRPC server we should select a protocol\n\t\tif opts.GRPCServer != nil {\n\t\t\t// All plugins in a set must use the same transport, so check the first\n\t\t\t// for the protocol type\n\t\t\tfor _, p := range pluginSet {\n\t\t\t\tswitch p.(type) {\n\t\t\t\tcase GRPCPlugin:\n\t\t\t\t\tprotoType = ProtocolGRPC\n\t\t\t\tdefault:\n\t\t\t\t\tprotoType = ProtocolNetRPC\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tfor _, clientVersion := range clientVersions {\n\t\t\tif clientVersion == protoVersion {\n\t\t\t\treturn protoVersion, protoType, pluginSet\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the lowest version as the fallback.\n\t// Since we iterated over all the versions in reverse order above, these\n\t// values are from the lowest version number plugins (which may be from\n\t// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins\n\t// fields). This allows serving the oldest version of our plugins to a\n\t// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.\n\treturn protoVersion, protoType, pluginSet\n}", "func Test_downloadURLVersion(t *testing.T) {\n\ttests := []struct {\n\t\tin string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tin: \"1.17.0\",\n\t\t\twant: \"1.17.0\",\n\t\t},\n\t\t{\n\t\t\tin: \"1.18.0\",\n\t\t\twant: \"1.18.0\",\n\t\t},\n\t\t{\n\t\t\tin: \"2.0.0\",\n\t\t\twant: \"2.0.0\",\n\t\t},\n\t\t{\n\t\t\tin: \"v2.0.0\",\n\t\t\twant: \"2.0.0\",\n\t\t},\n\t\t{\n\t\t\tin: \"v1.12.13+hotfix.8\",\n\t\t\twant: \"v1.12.13+hotfix.8\",\n\t\t},\n\t\t{\n\t\t\tin: \"1.12.13+hotfix.8\",\n\t\t\twant: \"v1.12.13+hotfix.8\",\n\t\t},\n\t\t{\n\t\t\tin: \"v1.12.0\",\n\t\t\twant: \"v1.12.0\",\n\t\t},\n\t\t{\n\t\t\tin: \"1.12.0\",\n\t\t\twant: \"v1.12.0\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.in, func(t *testing.T) {\n\t\t\tif got := downloadURLVersion(tt.in); got != tt.want {\n\t\t\t\tt.Errorf(\"downloadURLVersion() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (a *DefaultApiService) VersionCheck(ctx _context.Context) (ServiceVersion, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ServiceVersion\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/version\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Test_LatestVersion(t *testing.T) {\n\tmockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"0.6.1\\n\"))\n\t}))\n\tdefer mockServer.Close()\n\n\tversion, err := latestVersion(mockServer.URL)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttestVersion := semver.New(\"0.6.1\")\n\tif !version.Equal(*testVersion) {\n\t\tt.Error(\"Version equality check failed.\")\n\t}\n}", "func TestParseVersion(t *testing.T) {\n\n\tversion, database := parseSophosVersion(versionString)\n\n\tif true {\n\t\tt.Log(\"version: \", version)\n\t\tt.Log(\"database: \", database)\n\t}\n\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (_m *MockBackend) ProtocolVersion() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func (api *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {\n\tapi.logger.Debug(\"eth_protocolVersion\")\n\treturn hexutil.Uint(ethermint.ProtocolVersion)\n}", "func (p OpenFlow12Protocol) GetVersion() uint8 {\n\treturn goloxi.VERSION_1_2\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that service can be served without logger
func TestServiceWithoutLogger(t *testing.T) { s := res.NewService("test") s.SetLogger(nil) s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) session := restest.NewSession(t, s, restest.WithKeepLogger) defer session.Close() }
[ "func TestLogOperationForDisabledClient(t *testing.T) {\n\tc := constructDisabledClient()\n\terr := c.Log(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Fatal(\"Error should not be returned for disabled client\")\n\t}\n}", "func TestReturns200IfThereAreNoChecks(t *testing.T) {\n\trecorder := httptest.NewRecorder()\n\n\treq, err := http.NewRequest(\"GET\", \"https://fakeurl.com/debug/health\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create request.\")\n\t}\n\n\tStatusHandler(recorder, req)\n\n\tif recorder.Code != 200 {\n\t\tt.Errorf(\"Did not get a 200.\")\n\t}\n}", "func TestServiceSetLogger(t *testing.T) {\n\ts := res.NewService(\"test\")\n\tl := logger.NewMemLogger()\n\ts.SetLogger(l)\n\tif s.Logger() != l {\n\t\tt.Errorf(\"expected Logger to return the logger passed to SetLogger, but it didn't\")\n\t}\n\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\n\tsession := restest.NewSession(t, s, restest.WithKeepLogger)\n\tdefer session.Close()\n}", "func makeHTTPTestServerNoLogs(t testing.TB, fnmc func(mc *config.MayaConfig)) *TestServer {\n\treturn makeHTTPTestServerWithWriter(t, ioutil.Discard, fnmc)\n}", "func TestLogOperationForEnabledClient(t *testing.T) {\n\tc := constructEnabledClient()\n\terr := c.Log(\"foo\", \"bar\")\n\tif err == nil {\n\t\tt.Fatal(\"Error should be returned for enabled client with improper address\")\n\t}\n}", "func testGatePipelineGetMissing() *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.NotFound(w, r)\n\t}))\n}", "func noRouteResponseLogger(c *gin.Context) {\n\tdetails := obtainBodyLogWriter(c)\n\n\tdumpPayload := repository.DumpResponsePayload{\n\t\tHeaders: details.Blw.Header(),\n\t\tBody: details.Blw.Body,\n\t\tStatus: http.StatusNotFound,\n\t}\n\n\tif utils.CheckExcludedPaths(c.FullPath()) {\n\t\tgo repository.DumpRequestResponse(c, Config.ApplicationID, DB, dumpPayload, readBody(details.Rdr))\n\t}\n\n\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\"code\": http.StatusNotFound,\n\t\t\"message\": \"The requested resource could not be found!\",\n\t})\n}", "func TestServer_InitNetworkLogging(t *testing.T) {\n\tconst errString = \"must error to get Start to return!\"\n\tfor _, test := range []struct {\n\t\tName string\n\t\tEnv map[string]string\n\t\tInstall config.Install\n\t\tRuntime config.Runtime\n\t\tInitFn witchcraft.InitFunc\n\t\tVerifyLog func(t *testing.T, logOutput []byte)\n\t}{\n\t\t{\n\t\t\tName: \"Missing URIs\",\n\t\t\tInstall: config.Install{UseConsoleLog: true},\n\t\t\tInitFn: func(ctx context.Context, info witchcraft.InitInfo) (func(), error) {\n\t\t\t\tsvc1log.FromContext(ctx).Info(\"Inside initFunc\")\n\t\t\t\treturn nil, werror.ErrorWithContextParams(ctx, errString)\n\t\t\t},\n\t\t\tVerifyLog: func(t *testing.T, logOutput []byte) {\n\t\t\t\tassert.Contains(t, string(logOutput), \"Inside initFunc\")\n\t\t\t\tassert.Contains(t, string(logOutput), errString)\n\t\t\t\t// No messages about TCP logger should be logged\n\t\t\t\tassert.NotContains(t, string(logOutput), \"TCP\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Configured URI, missing environment metadata\",\n\t\t\tInstall: config.Install{UseConsoleLog: true},\n\t\t\tRuntime: config.Runtime{\n\t\t\t\tServiceDiscovery: httpclient.ServicesConfig{Services: map[string]httpclient.ClientConfig{\n\t\t\t\t\t\"sls-log-tcp-json-receiver\": {\n\t\t\t\t\t\tURIs: []string{\"tcp://network-log-forwarder.domain:8514\"},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tInitFn: func(ctx context.Context, info witchcraft.InitInfo) (func(), error) {\n\t\t\t\tsvc1log.FromContext(ctx).Info(\"Inside initFunc\")\n\t\t\t\treturn nil, werror.ErrorWithContextParams(ctx, errString)\n\t\t\t},\n\t\t\tVerifyLog: func(t *testing.T, logOutput []byte) {\n\t\t\t\tassert.Contains(t, string(logOutput), \"TCP logging will not be enabled since all environment variables are not set.\")\n\t\t\t\tassert.Contains(t, string(logOutput), \"Inside initFunc\")\n\t\t\t\tassert.Contains(t, string(logOutput), errString)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Environment URI, missing environment metadata\",\n\t\t\tInstall: config.Install{UseConsoleLog: true},\n\t\t\tRuntime: config.Runtime{},\n\t\t\tEnv: map[string]string{\n\t\t\t\t\"NETWORK_LOGGING_URL\": \"tcp://network-log-forwarder.domain:8514\",\n\t\t\t},\n\t\t\tInitFn: func(ctx context.Context, info witchcraft.InitInfo) (func(), error) {\n\t\t\t\tsvc1log.FromContext(ctx).Info(\"Inside initFunc\")\n\t\t\t\treturn nil, werror.ErrorWithContextParams(ctx, errString)\n\t\t\t},\n\t\t\tVerifyLog: func(t *testing.T, logOutput []byte) {\n\t\t\t\tassert.Contains(t, string(logOutput), \"TCP logging will not be enabled since all environment variables are not set.\")\n\t\t\t\tassert.Contains(t, string(logOutput), \"Inside initFunc\")\n\t\t\t\tassert.Contains(t, string(logOutput), errString)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Environment URI and metadata, missing TLS info\",\n\t\t\tInstall: config.Install{UseConsoleLog: true},\n\t\t\tRuntime: config.Runtime{},\n\t\t\tEnv: map[string]string{\n\t\t\t\t\"NETWORK_LOGGING_URL\": \"tcp://network-log-forwarder.domain:8514\",\n\t\t\t\t\"LOG_ENVELOPE_DEPLOYMENT_NAME\": \"deployment\",\n\t\t\t\t\"LOG_ENVELOPE_ENVIRONMENT_NAME\": \"environment\",\n\t\t\t\t\"LOG_ENVELOPE_ENVIRONMENT_ID\": \"env_id\",\n\t\t\t\t\"LOG_ENVELOPE_HOST\": \"hostname\",\n\t\t\t\t\"LOG_ENVELOPE_NODE_ID\": \"node_id\",\n\t\t\t\t\"LOG_ENVELOPE_PRODUCT_NAME\": \"product\",\n\t\t\t\t\"LOG_ENVELOPE_PRODUCT_VERSION\": \"version\",\n\t\t\t\t\"LOG_ENVELOPE_SERVICE_NAME\": \"service\",\n\t\t\t\t\"LOG_ENVELOPE_SERVICE_ID\": \"service_id\",\n\t\t\t\t\"LOG_ENVELOPE_STACK_NAME\": \"stack\",\n\t\t\t\t\"LOG_ENVELOPE_STACK_ID\": \"stack_id\",\n\t\t\t},\n\t\t\tInitFn: func(ctx context.Context, info witchcraft.InitInfo) (func(), error) {\n\t\t\t\tsvc1log.FromContext(ctx).Info(\"Inside initFunc\")\n\t\t\t\treturn nil, werror.ErrorWithContextParams(ctx, errString)\n\t\t\t},\n\t\t\tVerifyLog: func(t *testing.T, logOutput []byte) {\n\t\t\t\tassert.Contains(t, string(logOutput), \"TCP logging will not be enabled since TLS config is unset or invalid.\")\n\t\t\t\tassert.Contains(t, string(logOutput), \"Inside initFunc\")\n\t\t\t\tassert.Contains(t, string(logOutput), errString)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Configured URI and environment metadata, missing TLS info\",\n\t\t\tInstall: config.Install{UseConsoleLog: true},\n\t\t\tRuntime: config.Runtime{\n\t\t\t\tServiceDiscovery: httpclient.ServicesConfig{Services: map[string]httpclient.ClientConfig{\n\t\t\t\t\t\"sls-log-tcp-json-receiver\": {\n\t\t\t\t\t\tURIs: []string{\"tcp://network-log-forwarder.domain:8514\"},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tEnv: map[string]string{\n\t\t\t\t\"LOG_ENVELOPE_DEPLOYMENT_NAME\": \"deployment\",\n\t\t\t\t\"LOG_ENVELOPE_ENVIRONMENT_NAME\": \"environment\",\n\t\t\t\t\"LOG_ENVELOPE_ENVIRONMENT_ID\": \"env_id\",\n\t\t\t\t\"LOG_ENVELOPE_HOST\": \"hostname\",\n\t\t\t\t\"LOG_ENVELOPE_NODE_ID\": \"node_id\",\n\t\t\t\t\"LOG_ENVELOPE_PRODUCT_NAME\": \"product\",\n\t\t\t\t\"LOG_ENVELOPE_PRODUCT_VERSION\": \"version\",\n\t\t\t\t\"LOG_ENVELOPE_SERVICE_NAME\": \"service\",\n\t\t\t\t\"LOG_ENVELOPE_SERVICE_ID\": \"service_id\",\n\t\t\t\t\"LOG_ENVELOPE_STACK_NAME\": \"stack\",\n\t\t\t\t\"LOG_ENVELOPE_STACK_ID\": \"stack_id\",\n\t\t\t},\n\t\t\tInitFn: func(ctx context.Context, info witchcraft.InitInfo) (func(), error) {\n\t\t\t\tsvc1log.FromContext(ctx).Info(\"Inside initFunc\")\n\t\t\t\treturn nil, werror.ErrorWithContextParams(ctx, errString)\n\t\t\t},\n\t\t\tVerifyLog: func(t *testing.T, logOutput []byte) {\n\t\t\t\tassert.Contains(t, string(logOutput), \"TCP logging will not be enabled since TLS config is unset or invalid.\")\n\t\t\t\tassert.Contains(t, string(logOutput), \"Inside initFunc\")\n\t\t\t\tassert.Contains(t, string(logOutput), errString)\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(test.Name, func(t *testing.T) {\n\t\t\tos.Clearenv()\n\t\t\tfor k, v := range test.Env {\n\t\t\t\trequire.NoError(t, os.Setenv(k, v))\n\t\t\t}\n\t\t\tlogOutputBuffer := &bytes.Buffer{}\n\t\t\terr := witchcraft.NewServer().\n\t\t\t\tWithInitFunc(test.InitFn).\n\t\t\t\tWithInstallConfig(test.Install).\n\t\t\t\tWithRuntimeConfig(test.Runtime).\n\t\t\t\tWithLoggerStdoutWriter(logOutputBuffer).\n\t\t\t\tWithECVKeyProvider(witchcraft.ECVKeyNoOp()).\n\t\t\t\tWithDisableGoRuntimeMetrics().\n\t\t\t\tWithMetricsBlacklist(map[string]struct{}{\"server.uptime\": {}, \"logging.sls\": {}, \"logging.sls.length\": {}}).\n\t\t\t\tWithSelfSignedCertificate().\n\t\t\t\tStart()\n\t\t\tassert.EqualError(t, err, errString)\n\t\t\ttest.VerifyLog(t, logOutputBuffer.Bytes())\n\t\t})\n\t}\n}", "func TestLogActionOperationForDisabledClient(t *testing.T) {\n\tc := constructDisabledClient()\n\terr := c.LogAction(\"foo\", \"bar\", \"description\")\n\tif err != nil {\n\t\tt.Fatal(\"Error should not be returned for disabled client\")\n\t}\n}", "func (m *CloudWatchLogsServiceMock) CreateNewServiceIfUnHealthy() {\n\n}", "func TestHomeHandlerWithoutEnv(t *testing.T) {\n\tserver = NewServer()\n\n\tgetHomePageRequest, _ := http.NewRequest(\"GET\", \"/\", nil)\n\trecorder = httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, getHomePageRequest)\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"Expected response code to be %d, received: %d\",\n\t\t\thttp.StatusOK, recorder.Code)\n\t}\n\tif !strings.Contains(recorder.Body.String(), \"stranger\") {\n\t\tt.Errorf(\"Expected page to contain `stranger`.\")\n\t}\n}", "func _TestLogsNoDebug(t *testing.T) {\n // init\n DebugLogs = false\n\n logPerfs.Reset()\n\n doLogRun()\n\n if logPerfs.Value(PERF_LOG_DEBUG) != 0 {\n t.Fatalf(\n \"TestLogsNoDebug failed: debug count %d\",\n logPerfs.Value(PERF_LOG_DEBUG) ,\n )\n }\n\n fmt.Println(\"TestLogsNoDebug: passed\")\n}", "func TestFailedEndpoint0(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/devices\",\n\t\tHTTPMethod: \"PUT\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestCallToPublicService(t *testing.T) {\n\tt.Parallel()\n\n\tclients := Setup(t)\n\n\tt.Log(\"Creating a Service for the helloworld test app.\")\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.HelloWorld,\n\t}\n\n\ttest.EnsureTearDown(t, clients, &names)\n\n\tresources, err := v1test.CreateServiceReady(t, clients, &names)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service: %v: %v\", names.Service, err)\n\t}\n\n\tif resources.Route.Status.URL.Host == \"\" {\n\t\tt.Fatalf(\"Route is missing .Status.URL: %#v\", resources.Route.Status)\n\t}\n\tif resources.Route.Status.Address == nil {\n\t\tt.Fatalf(\"Route is missing .Status.Address: %#v\", resources.Route.Status)\n\t}\n\n\tgatewayTestCases := []struct {\n\t\tname string\n\t\turl *url.URL\n\t\taccessibleExternally bool\n\t}{\n\t\t{\"local_address\", resources.Route.Status.Address.URL.URL(), false},\n\t\t{\"external_address\", resources.Route.Status.URL.URL(), true},\n\t}\n\n\tfor _, tc := range gatewayTestCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tif !test.ServingFlags.DisableLogStream {\n\t\t\t\tcancel := logstream.Start(t)\n\t\t\t\tdefer cancel()\n\t\t\t}\n\t\t\ttestProxyToHelloworld(t, clients, tc.url, false /*inject*/, tc.accessibleExternally)\n\t\t})\n\t}\n}", "func serviceUnavailable(rw http.ResponseWriter, r *http.Request) {\n\n}", "func TestServiceMiddlewareNoMiddleware(t *testing.T) {\n\tassert := assert.New(t)\n\thandler := &testHandler{}\n\tmethod := NewMethod(handler, handler.handlerMethod, \"handlerMethod\", nil)\n\n\tctx := NewFContext(\"fooid\")\n\targ := 42\n\tret := method.Invoke([]interface{}{ctx, arg})\n\n\tassert.Equal(\"foo\", ret[0])\n\tassert.Equal(arg, handler.calledArg)\n}", "func TestLogWithTimeOperationForDisabledClient(t *testing.T) {\n\tc := constructDisabledClient()\n\terr := c.LogWithTime(123, \"bar\", \"description\")\n\tif err != nil {\n\t\tt.Fatal(\"Error should not be returned for disabled client\")\n\t}\n}", "func Test_NoUserNoPassAuth(t *testing.T) {\n\treq, _ := http.NewRequest(http.MethodGet, \"/freightsrv/\", nil)\n\n\t// Correct password.\n\tres := httptest.NewRecorder()\n\n\t// indexHandler(res, req, nil)\n\trouter.ServeHTTP(res, req)\n\n\tgot := res.Body.String()\n\twant := \"Unauthorised\\n\"\n\n\tif got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}", "func TestMiddlewareWithLogging(t *testing.T) {\n\thandler := WithLogging(nil, http.HandlerFunc(testHandler))\n\n\treq := httptest.NewRequest(http.MethodGet, \"/api/v1/\", nil)\n\tw := httptest.NewRecorder()\n\n\thandler.ServeHTTP(w, req)\n\n\t// Check the status code is what we expect.\n\tif status := w.Code; status != http.StatusOK {\n\t\tt.Errorf(\"handler returned wrong status code: got %v want %v\", status, http.StatusOK)\n\t}\n\t// Check the response body is what we expect.\n\texpected := `{\"alive\": true}`\n\tif w.Body.String() != expected {\n\t\tt.Errorf(\"handler returned unexpected body: got %v want %v\", w.Body.String(), expected)\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that Logger returns the logger set with SetLogger
func TestServiceSetLogger(t *testing.T) { s := res.NewService("test") l := logger.NewMemLogger() s.SetLogger(l) if s.Logger() != l { t.Errorf("expected Logger to return the logger passed to SetLogger, but it didn't") } s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) session := restest.NewSession(t, s, restest.WithKeepLogger) defer session.Close() }
[ "func GetLogger() *log.Logger { return std.GetLogger() }", "func SetLogger(l utils.Logger) {\n\tlog = l\n}", "func (_m *Client) SetLogger(_a0 log.Logger) {\n\t_m.Called(_a0)\n}", "func setLogger(mainLog *log.Logger) {\n\tLog = log.New(mainLog.Writer(), \"[DataServer/Database] \", mainLog.Flags())\n}", "func UseLogger(logger logging.Logger) {\n\tlog = logger\n}", "func SetLogger(l Logger) {\n\tdLog.Fulfill(l)\n}", "func setupLogger(cfg *conf.SplitSdkConfig) logging.LoggerInterface {\n\tvar logger logging.LoggerInterface\n\tif cfg.Logger != nil {\n\t\t// If a custom logger is supplied, use it.\n\t\tlogger = cfg.Logger\n\t} else {\n\t\tlogger = logging.NewLogger(&cfg.LoggerConfig)\n\t}\n\treturn logger\n}", "func (f *FakeOutput) Logger() *zap.SugaredLogger { return f.SugaredLogger }", "func Getlogger() Logger {\r\n\treturn log\r\n}", "func SetLogger(logger logrus.FieldLogger) {\n\tlog = logger\n}", "func setMockLogger(l logger.Level) <-chan []byte {\n\tmw, errChan := newMockWriter()\n\tmockLogger := logger.NewLogger(\n\t\tlogger.LoggerConfig{\n\t\t\tWriter: mw,\n\t\t\tLevel: logger.NewAtomicLevelAt(l),\n\t\t\tEncoder: logger.NewJSONEncoder(logger.NewProductionConfig().EncoderConfig),\n\t\t},\n\t)\n\tlogger.SetLogger(mockLogger)\n\treturn errChan\n}", "func TestLogger(tb testing.TB) Logging {\n\ttb.Helper()\n\treturn testLogger{TB: tb}\n}", "func Test() Logger {\n\treturn Logger{\n\t\tout: &bytes.Buffer{},\n\t\terr: &bytes.Buffer{},\n\t}\n}", "func SetLogger(logger logrus.FieldLogger) {\n\tbaseLogger = logger\n}", "func SetLogger(l *zerolog.Logger) {\n\tlogger.Store(l)\n}", "func UseLogger(logger dex.Logger) {\n\tlog = logger\n}", "func UseLogger(logger seelog.LoggerInterface) {\n\tlog = logger\n}", "func GetTestLogger() log.Logger {\n\tlogger := log.New(\"Alarmie\", \"Test Logger\")\n\tlogHandler := log.LvlFilterHandler(log.LvlDebug, log.StdoutHandler)\n\tlogger.SetHandler(logHandler)\n\treturn logger\n}", "func SetLogger(name string, logger Logger) {\n if logger == nil {\n return\n }\n store[name] = NewCfLogger(logger, nil, nil)\n if name == \"Logger_Default\" {\n defaultLogger = logger\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that With returns an error if there is no registered pattern matching the resource
func TestServiceWith_WithoutMatchingPattern(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("collection", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { err := s.Service().With("test.model", func(r res.Resource) {}) if err == nil { t.Errorf("expected With to return an error, but it didn't") } }) }
[ "func TestAddHandlerWithInvalidPathCausesPanic(t *testing.T) {\n\ttbl := []struct {\n\t\tPath string\n\t\tPattern string\n\t}{\n\t\t{\"test\", \"model.$id.type.$id\"},\n\t\t{\"test\", \"model..foo\"},\n\t\t{\"test\", \"model.$\"},\n\t\t{\"test\", \"model.$.foo\"},\n\t\t{\"test\", \"model.>.foo\"},\n\t\t{\"test\", \"model.foo.>bar\"},\n\t\t{\"$id\", \"model\"},\n\t\t{\">\", \"model\"},\n\t\t{\"test.>\", \"model\"},\n\t\t{\"test.\", \"model\"},\n\t\t{\"test.$id\", \"model\"},\n\t\t{\"test..foo\", \"model\"},\n\t}\n\n\tfor i, l := range tbl {\n\t\trestest.AssertPanic(t, func() {\n\t\t\tm := res.NewMux(l.Path)\n\t\t\tm.Handle(l.Pattern, res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t\t}, \"test \", i)\n\t}\n}", "func TestMountToExistingPatternCausesPanic(t *testing.T) {\n\ttbl := []struct {\n\t\tPattern string\n\t}{\n\t\t{\"model\"},\n\t\t{\"model.foo\"},\n\t\t{\"model.$id\"},\n\t\t{\"model.>\"},\n\t}\n\n\tfor i, l := range tbl {\n\t\tm := res.NewMux(\"test\")\n\t\tm.Handle(l.Pattern)\n\t\tsub := res.NewMux(\"\")\n\t\trestest.AssertPanic(t, func() { m.Mount(l.Pattern, sub) }, \"test \", i)\n\t}\n}", "func (c *Client) Match(pattern string) (resource.Resources, error) {\n\treturn c.match(pattern, false)\n}", "func (r *Router) Resource(pattern string, resource Resource) {\n\tsub := r.Group(pattern)\n\n\tif usesRes, ok := resource.(ResourceUses); ok {\n\t\tif len(usesRes.Uses()) > 0 {\n\t\t\tsub.Use(usesRes.Uses()...)\n\t\t}\n\t}\n\n\tfor _, m := range allowedHTTPMethods {\n\t\tif hfn, ok := isHandlerFuncInResource(m, resource); ok {\n\t\t\ts := sub.Subrouter()\n\t\t\tif mws, ok := isMiddlewareInResource(m, resource); ok {\n\t\t\t\ts.Use(mws()...)\n\t\t\t}\n\t\t\ts.HandleFunc(m, \"/\", hfn)\n\t\t}\n\t}\n}", "func TestAddHandlerWithValidPath(t *testing.T) {\n\ttbl := []struct {\n\t\tPattern string\n\t\tPath string\n\t}{\n\t\t{\"\", \"model\"},\n\t\t{\"\", \"model.foo\"},\n\t\t{\"\", \"model.$id\"},\n\t\t{\"\", \"model.$id.foo\"},\n\t\t{\"\", \"model.>\"},\n\t\t{\"\", \"model.$id.>\"},\n\t\t{\"test\", \"model\"},\n\t\t{\"test\", \"model.foo\"},\n\t\t{\"test\", \"model.$id\"},\n\t\t{\"test\", \"model.$id.foo\"},\n\t\t{\"test\", \"model.>\"},\n\t\t{\"test\", \"model.$id.>\"},\n\t}\n\n\tfor _, l := range tbl {\n\t\tm := res.NewMux(l.Pattern)\n\t\tm.Handle(l.Path, res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}\n}", "func TestAddHandlerWithInvalidGroupWillPanic(t *testing.T) {\n\ttbl := []struct {\n\t\tGroup string\n\t\tPattern string\n\t}{\n\t\t{\"$\", \"test.$foo\"},\n\t\t{\"${\", \"test.$foo\"},\n\t\t{\"${foo\", \"test.$foo\"},\n\t\t{\"${}\", \"test.$foo\"},\n\t\t{\"${$foo}\", \"test.$foo\"},\n\t\t{\"${bar}\", \"test.$foo\"},\n\t}\n\n\tfor _, l := range tbl {\n\t\tm := res.NewMux(\"\")\n\t\trestest.AssertPanic(t, func() {\n\t\t\tm.Handle(l.Pattern, res.Group(l.Group))\n\t\t})\n\t}\n}", "func MatchPattern(logger logr.Logger, resource, pattern interface{}) error {\n\t// newAnchorMap - to check anchor key has values\n\tac := anchor.NewAnchorMap()\n\telemPath, err := validateResourceElement(logger, resource, pattern, pattern, \"/\", ac)\n\tif err != nil {\n\t\tif skip(err) {\n\t\t\tlogger.V(2).Info(\"resource skipped\", \"reason\", ac.AnchorError.Error())\n\t\t\treturn &PatternError{err, \"\", true}\n\t\t}\n\n\t\tif fail(err) {\n\t\t\tlogger.V(2).Info(\"failed to apply rule on resource\", \"msg\", ac.AnchorError.Error())\n\t\t\treturn &PatternError{err, elemPath, false}\n\t\t}\n\n\t\t// check if an anchor defined in the policy rule is missing in the resource\n\t\tif ac.KeysAreMissing() {\n\t\t\tlogger.V(3).Info(\"missing anchor in resource\")\n\t\t\treturn &PatternError{err, \"\", false}\n\t\t}\n\n\t\treturn &PatternError{err, elemPath, false}\n\t}\n\n\treturn nil\n}", "func TestGetHandlerWithMismatchingPathReturnsNil(t *testing.T) {\n\ttbl := []struct {\n\t\tPath string\n\t\tPattern string\n\t\tResourceName string\n\t}{\n\t\t{\"\", \"\", \"model\"},\n\t\t{\"\", \"model\", \"\"},\n\t\t{\"\", \"model\", \"model.foo\"},\n\t\t{\"\", \"model.foo\", \"model\"},\n\t\t{\"\", \"model.$id\", \"model.42.foo\"},\n\t\t{\"\", \"model.$id.foo\", \"model.42\"},\n\t\t{\"\", \"model.>\", \"model\"},\n\t\t{\"\", \"model.$id.>\", \"model.42\"},\n\t\t{\"test\", \"\", \"model\"},\n\t\t{\"test\", \"model\", \"this.model\"},\n\t\t{\"test\", \"model\", \"test\"},\n\t\t{\"test\", \"model\", \"test.model.foo\"},\n\t\t{\"test\", \"model.foo\", \"test.model\"},\n\t\t{\"test\", \"model.$id\", \"test.model.42.foo\"},\n\t\t{\"test\", \"model.$id.foo\", \"test.model.42\"},\n\t\t{\"test\", \"model.>\", \"test.model\"},\n\t\t{\"test\", \"model.$id.>\", \"test.model.42\"},\n\t\t{\"test\", \"model\", \"test\"},\n\t}\n\n\tfor i, l := range tbl {\n\t\tm := res.NewMux(l.Path)\n\t\tm.Handle(l.Pattern)\n\t\tmh := m.GetHandler(l.ResourceName)\n\t\trestest.AssertTrue(t, \"*Match to equal nil\", mh == nil, \"test \", i)\n\t}\n}", "func Test_CreateHorizonDevice_conflictpattern(t *testing.T) {\n\n\tdir, db, err := utsetup()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer cleanTestDir(dir)\n\n\tmyOrg := \"testOrg\"\n\tmyPattern := \"testPattern\"\n\thd := getBasicDevice(myOrg, \"otherPattern\")\n\n\tvar myError error\n\terrorhandler := GetPassThroughErrorHandler(&myError)\n\tgetOrg := func(org string, id string, token string) (*exchange.Organization, error) {\n\t\tif org == myOrg {\n\t\t\treturn &exchange.Organization{\n\t\t\t\tLabel: \"test label\",\n\t\t\t\tDescription: \"test description\",\n\t\t\t\tLastUpdated: \"some time ago\",\n\t\t\t}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"org not found\")\n\t\t}\n\t}\n\n\tgetPatterns := func(org string, pattern string, id string, token string) (map[string]exchange.Pattern, error) {\n\t\tif pattern == myPattern && org == myOrg {\n\t\t\tpatid := fmt.Sprintf(\"%v/%v\", org, pattern)\n\t\t\treturn map[string]exchange.Pattern{\n\t\t\t\tpatid: exchange.Pattern{\n\t\t\t\t\tLabel: \"label\",\n\t\t\t\t\tDescription: \"desc\",\n\t\t\t\t\tPublic: true,\n\t\t\t\t\tServices: []exchange.ServiceReference{},\n\t\t\t\t\tAgreementProtocols: []exchange.AgreementProtocol{},\n\t\t\t\t},\n\t\t\t}, nil\n\t\t} else {\n\t\t\treturn nil, errors.New(\"pattern not found\")\n\t\t}\n\t}\n\n\terrHandled, device, exDevice := CreateHorizonDevice(hd, errorhandler, getOrg, getPatterns, getDummyGetExchangeVersion(), getDummyPatchDeviceHandler(), getExchangeDevice(\"DifferentPattern\"), events.NewEventStateManager(), db)\n\n\tif !errHandled {\n\t\tt.Errorf(\"expected error\")\n\t} else if apiErr, ok := myError.(*APIUserInputError); !ok {\n\t\tt.Errorf(\"myError has the wrong type (%T)\", myError)\n\t} else if apiErr.Input != \"device.pattern\" {\n\t\tt.Errorf(\"wrong error input field %v\", *apiErr)\n\t} else if !strings.Contains(apiErr.Err, \"conflict\") {\n\t\tt.Errorf(\"Wrong error message: %v\", apiErr.Err)\n\t} else if device != nil {\n\t\tt.Errorf(\"device should not be returned\")\n\t} else if exDevice != nil {\n\t\tt.Errorf(\"output device should not be returned\")\n\t}\n\n}", "func checkResource(config interface{}, resource *unstructured.Unstructured) (bool, error) {\n\n\t// we are checking if config is a subset of resource with default pattern\n\tpath, err := validateResourceWithPattern(resource.Object, config)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"config not a subset of resource. failed at path %s: %v\", path, err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func TestGetBadResource(t *testing.T) {\n\n\tdefer gock.Off()\n\n\tmock := gock.New(\"https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net/config-gtm/v1/domains/\" + gtmTestDomain + \"/resources/somebadname\")\n\tmock.\n\t\tGet(\"/config-gtm/v1/domains/\"+gtmTestDomain+\"/resources/somebadname\").\n\t\tHeaderPresent(\"Authorization\").\n\t\tReply(404).\n\t\tSetHeader(\"Content-Type\", \"application/vnd.config-gtm.v1.3+json;charset=UTF-8\").\n\t\tBodyString(`{\n }`)\n\n\tInit(config)\n\n\t_, err := GetResource(\"somebadname\", gtmTestDomain)\n\t// Shouldn't have found\n\tassert.Error(t, err)\n\n}", "func matchResource(kinda, typea, kindb, typeb string) bool {\n\tif kinda == \"\" {\n\t\tkinda = \"pipeline\"\n\t}\n\tif kindb == \"\" {\n\t\tkindb = \"pipeline\"\n\t}\n\tif typea == \"\" {\n\t\ttypea = \"docker\"\n\t}\n\tif typeb == \"\" {\n\t\ttypeb = \"docker\"\n\t}\n\treturn kinda == kindb && typea == typeb\n}", "func (rest *TestResourceREST) TestFailRegisterResourceNonServiceAccount() {\n\tsa := account.Identity{\n\t\tUsername: \"unknown-account\",\n\t}\n\tservice, controller := rest.SecuredController(sa)\n\n\tresourceDescription := \"Resource description\"\n\tresourceID := \"\"\n\tresourceScopes := []string{}\n\n\tresourceOwnerID := rest.testIdentity.ID\n\n\tpayload := &app.RegisterResourcePayload{\n\t\tDescription: &resourceDescription,\n\t\tName: \"My new resource\",\n\t\tParentResourceID: nil,\n\t\tResourceScopes: resourceScopes,\n\t\tResourceID: &resourceID,\n\t\tResourceOwnerID: resourceOwnerID.String(),\n\t\tType: \"Area\",\n\t}\n\n\ttest.RegisterResourceUnauthorized(rest.T(), service.Context, service, controller, payload)\n}", "func ValidResource(api *kit.API, lookupOrgByResourceID func(context.Context, influxdb.ID) (influxdb.ID, error)) kit.Middleware {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstatusW := kit.NewStatusResponseWriter(w)\n\t\t\tid, err := influxdb.IDFromString(chi.URLParam(r, \"id\"))\n\t\t\tif err != nil {\n\t\t\t\tapi.Err(w, ErrCorruptID(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx := r.Context()\n\n\t\t\torgID, err := lookupOrgByResourceID(ctx, *id)\n\t\t\tif err != nil {\n\t\t\t\tapi.Err(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(statusW, r.WithContext(context.WithValue(ctx, ctxOrgKey, orgID)))\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func TestContainsWithSinglePath(t *testing.T) {\n\ttbl := []struct {\n\t\tPath string\n\t\tPattern string\n\t}{\n\t\t{\"\", \"model\"},\n\t\t{\"\", \"model.foo\"},\n\t\t{\"\", \"model.$id\"},\n\t\t{\"\", \"model.$id.foo\"},\n\t\t{\"\", \"model.>\"},\n\t\t{\"\", \"model.$id.>\"},\n\t\t{\"test\", \"model\"},\n\t\t{\"test\", \"model.foo\"},\n\t\t{\"test\", \"model.$id\"},\n\t\t{\"test\", \"model.$id.foo\"},\n\t\t{\"test\", \"model.>\"},\n\t\t{\"test\", \"model.$id.>\"},\n\t}\n\n\tfor i, l := range tbl {\n\t\tm := res.NewMux(l.Path)\n\t\tm.Handle(l.Pattern)\n\t\trestest.AssertTrue(t, \"Contains to return true\", m.Contains(func(h res.Handler) bool { return true }), \"test \", i)\n\t}\n}", "func TestDROStructuralValidatorMemberNotFound(t *testing.T) {\n\tvalidator := NewDROStructuralValidator(newMockRepository(nil))\n\tobj := testObjectResource([]string{\"NotfindableID\"})\n\terr := validator.ValidateResource(obj)\n\tassert.NotNil(t, err)\n}", "func TestMatchesWithMalformedPatterns(t *testing.T) {\n\tmatches, err := Matches(\"/any/path/there\", []string{\"[\"})\n\tif err == nil {\n\t\tt.Fatal(\"Should have failed because of a malformed syntax in the pattern\")\n\t}\n\tif matches {\n\t\tt.Fatalf(\"Should not have match anything\")\n\t}\n}", "func abortOnMatch(*Descriptor) error { return errors.New(\"\") }", "func TestMatchesWithNoPatterns(t *testing.T) {\n\tmatches, err := Matches(\"/any/path/there\", []string{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif matches {\n\t\tt.Fatalf(\"Should not have match anything\")\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that SetOwnedResources sets which resources are reset when calling Reset.
func TestServiceSetOwnedResources(t *testing.T) { resources := []string{"test.foo.>", "test.bar.>"} access := []string{"test.zoo.>", "test.baz.>"} runTest(t, func(s *res.Service) { s.SetOwnedResources(resources, access) }, nil, restest.WithReset(resources, access)) }
[ "func (s *RepoServerControllerSuite) TestCreationOfOwnedResources(c *C) {\n\tctx := context.Background()\n\n\trepoServerCR := testutil.GetTestKopiaRepositoryServerCR(s.repoServerControllerNamespace)\n\tsetRepositoryServerSecretsInCR(&s.repoServerSecrets, &repoServerCR)\n\n\trepoServerCRCreated, err := s.crCli.RepositoryServers(s.repoServerControllerNamespace).Create(ctx, &repoServerCR, metav1.CreateOptions{})\n\tc.Assert(err, IsNil)\n\n\terr = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name)\n\tc.Assert(err, IsNil)\n\n\t//Get repository server CR with the updated server information\n\trepoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{})\n\tc.Assert(err, IsNil)\n\n\tpod, err := s.kubeCli.CoreV1().Pods(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Status.ServerInfo.PodName, metav1.GetOptions{})\n\tc.Assert(err, IsNil)\n\tc.Assert(len(pod.OwnerReferences), Equals, 1)\n\tc.Assert(pod.OwnerReferences[0].UID, Equals, repoServerCRCreated.UID)\n\n\tservice, err := s.kubeCli.CoreV1().Services(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Status.ServerInfo.ServiceName, metav1.GetOptions{})\n\tc.Assert(err, IsNil)\n\tc.Assert(len(service.OwnerReferences), Equals, 1)\n\tc.Assert(service.OwnerReferences[0].UID, Equals, repoServerCRCreated.UID)\n\n\terr = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Delete(context.Background(), repoServerCRCreated.Name, metav1.DeleteOptions{})\n\tc.Assert(err, IsNil)\n}", "func (m *User) SetOwnedObjects(value []DirectoryObjectable)() {\n m.ownedObjects = value\n}", "func TestReset(t *testing.T) {\n\ttestCancel(t, false)\n}", "func TestApplyOwnershipDiff(t *testing.T) {\n\tusers := []*user.User{\n\t\tfakeUser(\"1\", \"1\", \"user-1\"),\n\t\tfakeUser(\"2\", \"2\", \"user-2\"),\n\t}\n\tgroups := []*user.Group{\n\t\tfakeGroup(\"1\", \"group-1\"),\n\t\tfakeGroup(\"2\", \"group-2\"),\n\t}\n\townershipRecords := []ownershipRecord{\n\t\tmakeOwned(\"foo\", \"user-1\", \"1\", \"group-1\", \"1\"),\n\t}\n\tm := newMockOS(ownershipRecords, users, groups, nil, nil)\n\tt.Run(\"no-changes\", func(t *testing.T) {\n\t\to := &owner.Ownership{UID: intRef(1), GID: intRef(1)}\n\t\tdiff, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\trequire.NoError(t, err)\n\t\terr = diff.Apply()\n\t\trequire.NoError(t, err)\n\t\tm.AssertNotCalled(t, \"Chown\", any, any, any)\n\t})\n\tt.Run(\"uid-changes\", func(t *testing.T) {\n\t\to := &owner.Ownership{UID: intRef(2), GID: intRef(1)}\n\t\tdiff, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\trequire.NoError(t, err)\n\t\terr = diff.Apply()\n\t\trequire.NoError(t, err)\n\t\tm.AssertCalled(t, \"Chown\", \"foo\", 2, 1)\n\t})\n\tt.Run(\"gid-changes\", func(t *testing.T) {\n\t\to := &owner.Ownership{UID: intRef(1), GID: intRef(2)}\n\t\tdiff, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\trequire.NoError(t, err)\n\t\terr = diff.Apply()\n\t\trequire.NoError(t, err)\n\t\tm.AssertCalled(t, \"Chown\", \"foo\", 1, 2)\n\t})\n\tt.Run(\"uid-and-gid-changes\", func(t *testing.T) {\n\t\to := &owner.Ownership{UID: intRef(2), GID: intRef(2)}\n\t\tdiff, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\trequire.NoError(t, err)\n\t\terr = diff.Apply()\n\t\trequire.NoError(t, err)\n\t\tm.AssertCalled(t, \"Chown\", \"foo\", 2, 2)\n\t})\n\tt.Run(\"chown-error-needs-changes\", func(t *testing.T) {\n\t\texpected := errors.New(\"error1\")\n\t\tm := failingMockOS(map[string]error{\"Chown\": expected})\n\t\to := &owner.Ownership{UID: intRef(2), GID: intRef(2)}\n\t\tdiff, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\trequire.NoError(t, err)\n\t\terr = diff.Apply()\n\t\tm.AssertCalled(t, \"Chown\", any, any, any)\n\t\tassert.Equal(t, expected, err)\n\t})\n}", "func TestResetIPSetsOnFailure(t *testing.T) {\n\tmetrics.ReinitializeAll()\n\tcalls := []testutils.TestCmd{\n\t\t{Cmd: []string{\"ipset\", \"list\", \"--name\"}, PipedToCommand: true, HasStartError: true, ExitCode: 1},\n\t\t{Cmd: []string{\"grep\", \"-q\", \"-v\", \"azure-npm-\"}, ExitCode: 0}, // non-azure sets exist\n\t\t{Cmd: []string{\"ipset\", \"list\", \"--name\"}, PipedToCommand: true, HasStartError: true, ExitCode: 1},\n\t\t{Cmd: []string{\"grep\", \"azure-npm-\"}},\n\t}\n\tioShim := common.NewMockIOShim(calls)\n\tdefer ioShim.VerifyCalls(t, calls)\n\tiMgr := NewIPSetManager(applyAlwaysCfg, ioShim)\n\n\tiMgr.CreateIPSets([]*IPSetMetadata{namespaceSet, keyLabelOfPodSet})\n\n\tmetrics.IncNumIPSets()\n\tmetrics.IncNumIPSets()\n\tmetrics.AddEntryToIPSet(\"test1\")\n\tmetrics.AddEntryToIPSet(\"test1\")\n\tmetrics.AddEntryToIPSet(\"test2\")\n\n\trequire.Error(t, iMgr.ResetIPSets())\n\n\tassertExpectedInfo(t, iMgr, &expectedInfo{\n\t\tmainCache: nil,\n\t\ttoAddUpdateCache: nil,\n\t\ttoDeleteCache: nil,\n\t\tsetsForKernel: nil,\n\t})\n}", "func (_m *Resource) SetOwnerReferences(_a0 []v1.OwnerReference) {\n\t_m.Called(_a0)\n}", "func (r *FooReconciler) cleanupOwnedResources(ctx context.Context, log logr.Logger, foo *batchv1.Foo) error {\n\tlog.Info(\"finding existing Deployments for MyKind resource\")\n\n\t// List all deployment resources owned by this MyKind\n\tvar deployments apps.DeploymentList\n\t//if err := r.List(ctx, &deployments, client.InNamespace(foo.Namespace), client.MatchingField(deploymentOwnerKey, foo.Name)); err != nil {\n\t//\treturn err\n\t//}\n\n\tdeleted := 0\n\tfor _, depl := range deployments.Items {\n\t\tif depl.Name == foo.Spec.Name {\n\t\t\t// If this deployment's name matches the one on the MyKind resource\n\t\t\t// then do not delete it.\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := r.Client.Delete(ctx, &depl); err != nil {\n\t\t\tlog.Error(err, \"failed to delete Deployment resource\")\n\t\t\treturn err\n\t\t}\n\n\t\tr.Recorder.Eventf(foo, core.EventTypeNormal, \"Deleted\", \"Deleted deployment %q\", depl.Name)\n\t\tdeleted++\n\t}\n\n\tlog.Info(\"finished cleaning up old Deployment resources\", \"number_deleted\", deleted)\n\n\treturn nil\n}", "func TestReset(t *testing.T) {\n\tqd, err := New(QFILE)\n\tif nil != err {\n\t\tt.Error(err)\n\t}\n\tt.Logf(\"%s: %d unused, and %d used quotes\", QFILE, qd.Unused(), qd.Used())\n\tqd.ResetAndSave()\n\tt.Logf(\"%s: %d unused, and %d used quotes\", QFILE, qd.Unused(), qd.Used())\n}", "func (p *Player) Reset() {\n\t//Reset Lifes to 2\n\tp.Lives = 2\n\n\t//Reset CurrentDeck to \"Original\" Deck\n\tp.Deck = p.Cards\n\n\t//Go trough Deck & generate GUIDs\n\tfor _, c := range p.Deck {\n\t\tc.SetGUID(GetNextGUID())\n\t}\n\tif p.Leader != nil {\n\t\tp.Leader.SetGUID(GetNextGUID())\n\t}\n\n\t//Give 10 random cards from CurrentDeck to Hand\n\tfor i := 0; i < 10; i++ {\n\t\tp.DrawCard()\n\t}\n\n\t//Check for Leader-related effects\n\tif p.Leader != nil && p.Leader.LeaderEffect == LeaderFxDrawExtraCard {\n\t\tp.Leader.Play(p, nil)\n\t}\n}", "func TestServiceReset(t *testing.T) {\n\ttbl := []struct {\n\t\tResources []string\n\t\tAccess []string\n\t\tExpected interface{}\n\t}{\n\t\t{nil, nil, nil},\n\t\t{[]string{}, nil, nil},\n\t\t{nil, []string{}, nil},\n\t\t{[]string{}, []string{}, nil},\n\n\t\t{[]string{\"test.foo.>\"}, nil, json.RawMessage(`{\"resources\":[\"test.foo.>\"]}`)},\n\t\t{nil, []string{\"test.foo.>\"}, json.RawMessage(`{\"access\":[\"test.foo.>\"]}`)},\n\t\t{[]string{\"test.foo.>\"}, []string{\"test.bar.>\"}, json.RawMessage(`{\"resources\":[\"test.foo.>\"],\"access\":[\"test.bar.>\"]}`)},\n\n\t\t{[]string{\"test.foo.>\"}, []string{}, json.RawMessage(`{\"resources\":[\"test.foo.>\"]}`)},\n\t\t{[]string{}, []string{\"test.foo.>\"}, json.RawMessage(`{\"access\":[\"test.foo.>\"]}`)},\n\t}\n\n\tfor _, l := range tbl {\n\t\trunTest(t, func(s *res.Service) {\n\t\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t\t}, func(s *restest.Session) {\n\t\t\ts.Service().Reset(l.Resources, l.Access)\n\t\t\t// Send token event to flush any system.reset event\n\t\t\ts.Service().TokenEvent(mock.CID, nil)\n\n\t\t\tif l.Expected != nil {\n\t\t\t\ts.GetMsg().\n\t\t\t\t\tAssertSubject(\"system.reset\").\n\t\t\t\t\tAssertPayload(l.Expected)\n\t\t\t}\n\n\t\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t\t})\n\t}\n}", "func TestOwnershipDiff(t *testing.T) {\n\tusers := []*user.User{\n\t\tfakeUser(\"1\", \"1\", \"user-1\"),\n\t\tfakeUser(\"2\", \"2\", \"user-2\"),\n\t\tfakeUser(\"3\", \"3\", \"user-3\"),\n\t}\n\tgroups := []*user.Group{\n\t\tfakeGroup(\"1\", \"group-1\"),\n\t\tfakeGroup(\"2\", \"group-2\"),\n\t\tfakeGroup(\"3\", \"group-3\"),\n\t}\n\tm := newMockOS(nil, users, groups, nil, nil)\n\tt.Run(\"Original\", func(t *testing.T) {\n\t\tt.Run(\"uid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"user: user-1 (1)\", o.Original())\n\t\t})\n\t\tt.Run(\"gid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"group: group-1 (1)\", o.Original())\n\t\t})\n\t\tt.Run(\"both\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"user: user-1 (1); group: group-1 (1)\", o.Original())\n\t\t})\n\t\tt.Run(\"heterogenous\", func(t *testing.T) {\n\t\t\tt.Run(\"mismatched-uid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 1}}).SetProxy(m)\n\t\t\t\tassert.Equal(t, \"user: user-1 (1)\", o.Original())\n\t\t\t})\n\t\t\tt.Run(\"mismatched-gid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 1}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\t\tassert.Equal(t, \"group: group-1 (1)\", o.Original())\n\t\t\t})\n\t\t})\n\t})\n\tt.Run(\"Current\", func(t *testing.T) {\n\t\tt.Run(\"uid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"user: user-2 (2)\", o.Current())\n\t\t})\n\t\tt.Run(\"gid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"group: group-2 (2)\", o.Current())\n\t\t})\n\t\tt.Run(\"both\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.Equal(t, \"user: user-2 (2); group: group-2 (2)\", o.Current())\n\t\t})\n\t\tt.Run(\"heterogenous\", func(t *testing.T) {\n\t\t\tt.Run(\"mismatched-uid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 1}}).SetProxy(m)\n\t\t\t\tassert.Equal(t, \"user: user-2 (2)\", o.Current())\n\t\t\t})\n\t\t\tt.Run(\"mismatched-gid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 1}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\t\tassert.Equal(t, \"group: group-2 (2)\", o.Current())\n\t\t\t})\n\t\t})\n\t})\n\tt.Run(\"Changes\", func(t *testing.T) {\n\t\tt.Run(\"uid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.True(t, o.Changes())\n\t\t})\n\t\tt.Run(\"gid\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.True(t, o.Changes())\n\t\t})\n\t\tt.Run(\"both\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\tassert.True(t, o.Changes())\n\t\t})\n\t\tt.Run(\"heterogenous\", func(t *testing.T) {\n\t\t\tt.Run(\"mismatched-uid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 2}, GIDs: &[2]int{1, 1}}).SetProxy(m)\n\t\t\t\tassert.True(t, o.Changes())\n\t\t\t})\n\t\t\tt.Run(\"mismatched-gid\", func(t *testing.T) {\n\t\t\t\to := (&owner.OwnershipDiff{UIDs: &[2]int{1, 1}, GIDs: &[2]int{1, 2}}).SetProxy(m)\n\t\t\t\tassert.True(t, o.Changes())\n\t\t\t})\n\t\t})\n\t\tt.Run(\"neither\", func(t *testing.T) {\n\t\t\to := (&owner.OwnershipDiff{}).SetProxy(m)\n\t\t\tassert.False(t, o.Changes())\n\t\t})\n\t})\n\tt.Run(\"NewOwnershipDiff\", func(t *testing.T) {\n\t\townershipRecords := []ownershipRecord{\n\t\t\tmakeOwned(\"foo\", \"user-1\", \"1\", \"group-1\", \"1\"),\n\t\t}\n\t\tm := newMockOS(ownershipRecords, users, groups, nil, nil)\n\t\tt.Run(\"when-matching\", func(t *testing.T) {\n\t\t\to := &owner.Ownership{UID: intRef(1), GID: intRef(1)}\n\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.False(t, d.Changes())\n\t\t})\n\t\tt.Run(\"when-mismatched\", func(t *testing.T) {\n\t\t\to := &owner.Ownership{UID: intRef(2), GID: intRef(2)}\n\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.True(t, d.Changes())\n\t\t})\n\t\tt.Run(\"when-uid-match\", func(t *testing.T) {\n\t\t\to := &owner.Ownership{UID: intRef(1), GID: intRef(2)}\n\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.True(t, d.Changes())\n\t\t})\n\t\tt.Run(\"when-gid-match\", func(t *testing.T) {\n\t\t\to := &owner.Ownership{UID: intRef(2), GID: intRef(1)}\n\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.True(t, d.Changes())\n\t\t})\n\t\tt.Run(\"when-only-uid\", func(t *testing.T) {\n\t\t\tt.Run(\"when-matches\", func(t *testing.T) {\n\t\t\t\to := &owner.Ownership{UID: intRef(1)}\n\t\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.False(t, d.Changes())\n\t\t\t})\n\t\t\tt.Run(\"when-not-matches\", func(t *testing.T) {\n\t\t\t\to := &owner.Ownership{UID: intRef(2)}\n\t\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.True(t, d.Changes())\n\t\t\t})\n\t\t})\n\t\tt.Run(\"when-only-gid\", func(t *testing.T) {\n\t\t\tt.Run(\"when-matches\", func(t *testing.T) {\n\t\t\t\to := &owner.Ownership{GID: intRef(1)}\n\t\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.False(t, d.Changes())\n\t\t\t})\n\t\t\tt.Run(\"when-not-matches\", func(t *testing.T) {\n\t\t\t\to := &owner.Ownership{GID: intRef(2)}\n\t\t\t\td, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.True(t, d.Changes())\n\t\t\t})\n\t\t})\n\t})\n\tt.Run(\"when-syscall-errors\", func(t *testing.T) {\n\t\texpectedError := errors.New(\"error\")\n\t\to := &owner.Ownership{UID: intRef(1), GID: intRef(1)}\n\t\tt.Run(\"GetUID\", func(t *testing.T) {\n\t\t\tm := failingMockOS(map[string]error{\"GetUID\": expectedError})\n\t\t\t_, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\tassert.Equal(t, expectedError, err)\n\t\t})\n\t\tt.Run(\"GetGID\", func(t *testing.T) {\n\t\t\tm := failingMockOS(map[string]error{\"GetGID\": expectedError})\n\t\t\t_, err := owner.NewOwnershipDiff(m, \"foo\", o)\n\t\t\tassert.Equal(t, expectedError, err)\n\t\t})\n\t})\n}", "func (cr *cmdRunner) prepReset(scanRes *storage.ScmScanResponse) (*storage.ScmPrepareResponse, error) {\n\tstate := scanRes.State\n\tresp := &storage.ScmPrepareResponse{State: state}\n\n\tcr.log.Debugf(\"scm backend prep reset: state %q\", state)\n\n\tif err := cr.deleteGoals(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch state {\n\tcase storage.ScmStateNoRegions:\n\t\treturn resp, nil\n\tcase storage.ScmStateFreeCapacity, storage.ScmStateNoFreeCapacity, storage.ScmStateNotInterleaved:\n\t\t// Continue to remove namespaces and regions.\n\t\tresp.RebootRequired = true\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unhandled scm state %q\", state)\n\t}\n\n\tfor _, dev := range scanRes.Namespaces {\n\t\tif err := cr.removeNamespace(dev.Name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcr.log.Infof(\"Resetting PMem memory allocations.\")\n\n\tif err := cr.removeRegions(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (m *PlayerMutation) ResetCards() {\n\tm.cards = nil\n\tm.clearedcards = false\n\tm.removedcards = nil\n}", "func (m *User) SetOwnedDevices(value []DirectoryObjectable)() {\n m.ownedDevices = value\n}", "func ResetTest() {\n\tsecurity.SetAssetLoader(securitytest.EmbeddedAssets)\n}", "func (m *PatientrightstypeMutation) ResetResponsible() {\n\tm._Responsible = nil\n}", "func (m *Mock) Reset() {\n\tm.responders = []*Responder{}\n}", "func (pas *PodAutoscalerStatus) MarkResourceNotOwned(kind, name string) {\n\tpas.MarkInactive(\"NotOwned\",\n\t\tfmt.Sprintf(\"There is an existing %s %q that we do not own.\", kind, name))\n}", "func (m *CarMutation) ResetOwner() {\n\tm.owner = nil\n\tm.clearedowner = false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenEvent sends a connection token event.
func TestServiceTokenEvent_WithObjectToken_SendsToken(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { s.Service().TokenEvent(mock.CID, mock.Token) s.GetMsg().AssertTokenEvent(mock.CID, mock.Token) }) }
[ "func TestAuthRequestTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(mock.Token)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, mock.Token)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, nil)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t})\n}", "func (s *Service) TestToken(ctx context.Context, info *pushmdl.PushInfo, token string) (err error) {\n\tparams := url.Values{}\n\tparams.Add(\"app_id\", strconv.FormatInt(info.APPID, 10))\n\tparams.Add(\"alert_title\", info.Title)\n\tparams.Add(\"alert_body\", info.Summary)\n\tparams.Add(\"token\", token)\n\tparams.Add(\"link_type\", strconv.FormatInt(int64(info.LinkType), 10))\n\tparams.Add(\"link_value\", info.LinkValue)\n\tparams.Add(\"sound\", strconv.Itoa(info.Sound))\n\tparams.Add(\"vibration\", strconv.Itoa(info.Vibration))\n\tparams.Add(\"expire_time\", strconv.FormatInt(int64(info.ExpireTime), 10))\n\tparams.Add(\"image_url\", info.ImageURL)\n\tif err = s.httpClient.Post(ctx, _testTokenURL, \"\", params, nil); err != nil {\n\t\tlog.Error(\"s.TestToken(%+v) error(%v)\", info, err)\n\t}\n\treturn\n}", "func TestMockOnEvent(t *testing.T) {\n\tmockServer := &MockRailsServer{T: t, Behaviour: MockEvent}\n\n\tdialer := wstest.NewDialer(mockServer)\n\tdialer.HandshakeTimeout = time.Second * 2\n\n\tclient := NewClient(fakeEndpoint).WithDialer(dialer)\n\n\tcalled := make(chan struct{})\n\n\tclient.OnEvent(\"AgentChannel\", func(conn *websocket.Conn, payload *Payload, error error) {\n\t\tcalled <- struct{}{}\n\t\treturn\n\t})\n\n\terr := client.Serve()\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treceiveSleepMs(2000, called, t)\n}", "func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEventWithID(mock.CID, \"foo\", nil)\n\t\ts.GetMsg().AssertTokenEventWithID(mock.CID, \"foo\", nil)\n\t})\n}", "func (s *ConnectionSuite) TestCreateConnectionAfterLoginRefreshNewToken(c *C) {\n\tc.Skip(\"Skip this for now as we don't have the endpoint in the docs yet\")\n\taccounts := CorrectDeploy(1, 0, 1, 2, 0, false, false)\n\taccount := accounts[0]\n\tapplication := account.Applications[0]\n\tuserFrom := application.Users[0]\n\tuserTo := application.Users[1]\n\n\tpayload := fmt.Sprintf(\n\t\t`{\"email\": \"%s\", \"password\": \"%s\"}`,\n\t\tuserFrom.Email,\n\t\tuserFrom.OriginalPassword,\n\t)\n\n\trouteName := \"loginCurrentUserApplicationUser\"\n\troute := getComposedRoute(routeName)\n\tcode, body, err := runRequest(routeName, route, payload, signApplicationRequest(application, userFrom, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n\tc.Assert(body, Not(Equals), \"\")\n\n\tsessionToken := struct {\n\t\tUserID uint64 `json:\"id\"`\n\t\tToken string `json:\"session_token\"`\n\t}{}\n\ter := json.Unmarshal([]byte(body), &sessionToken)\n\tc.Assert(er, IsNil)\n\tc.Assert(sessionToken.UserID, Equals, userFrom.ID)\n\tc.Assert(sessionToken.Token, Not(Equals), \"\")\n\n\tuserFrom.SessionToken = sessionToken.Token\n\n\tpayload = fmt.Sprintf(`{\"session_token\": \"%s\"}`, userFrom.SessionToken)\n\n\trouteName = \"refreshApplicationUserSession\"\n\troute = getComposedRoute(routeName)\n\tcode, body, err = runRequest(routeName, route, payload, signApplicationRequest(application, userFrom, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n\tc.Assert(body, Not(Equals), \"\")\n\n\ter = json.Unmarshal([]byte(body), &sessionToken)\n\tc.Assert(er, IsNil)\n\tc.Assert(sessionToken.UserID, Equals, userFrom.ID)\n\tc.Assert(sessionToken.Token, Not(Equals), userFrom.SessionToken)\n\n\tuserFrom.SessionToken = sessionToken.Token\n\n\tpayload = fmt.Sprintf(`{\"user_to_id\":%d, \"type\": \"`+string(entity.ConnectionTypeFriend)+`\"}`, userTo.ID)\n\n\trouteName = \"createCurrentUserConnection\"\n\troute = getComposedRoute(routeName)\n\tcode, body, err = runRequest(routeName, route, payload, signApplicationRequest(application, userFrom, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n\tc.Assert(body, Not(Equals), \"\")\n\n\tconnection := &entity.Connection{}\n\ter = json.Unmarshal([]byte(body), connection)\n\tc.Assert(er, IsNil)\n\n\tc.Assert(connection.UserFromID, Equals, userFrom.ID)\n\tc.Assert(connection.UserToID, Equals, userTo.ID)\n}", "func TestToken(t *testing.T) {\n\n\ttoken := initToken()\n\tfmt.Println(token)\n}", "func Test4C_ConnectToGame(t *testing.T) {\n\n\tfmt.Println(\"Test4C: Connect to Game\")\n\n\t// assume we are connecting to example-gameserver\n\t// this server is an HTTP listen server\n\t// which simulates a long lived connection\n\t// on the endpoint POST http://address:port/connect\n\n\ttoken := ConnectToken{\n\t\tSessionKey: sessionKey,\n\t\tCharacterId: characterIds[0]}\n\n\tjson, err := json.Marshal(&token)\n\tif err != nil {\n\n\t\tlog.Print(err)\n\t\tt.FailNow()\n\t}\n\n\turl := fmt.Sprintf(\"http://%s:%d/connect\", gameServerAddress, gameServerPort)\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(json))\n\tif err != nil {\n\n\t\tlog.Print(err)\n\t\tt.FailNow()\n\t}\n\n\tc := &http.Client{}\n\tresp, err := c.Do(req)\n\tif err != nil {\n\n\t\tlog.Print(err)\n\t\tt.FailNow()\n\t}\n\n\tif resp.StatusCode != 200 {\n\n\t\tlog.Print(\"game server denied request. status \", resp.StatusCode)\n\t\tt.FailNow()\n\t}\n\n\tfmt.Println(\"Test 4C: Pass\")\n}", "func (s *ConnectionSuite) TestCreateConnectionAfterLoginRefreshOldToken_Works(c *C) {\n\taccounts := CorrectDeploy(1, 0, 1, 2, 0, false, false)\n\taccount := accounts[0]\n\tapplication := account.Applications[0]\n\tuserFrom := application.Users[0]\n\tuserTo := application.Users[1]\n\n\tpayload := fmt.Sprintf(\n\t\t`{\"email\": \"%s\", \"password\": \"%s\"}`,\n\t\tuserFrom.Email,\n\t\tuserFrom.OriginalPassword,\n\t)\n\n\trouteName := \"loginCurrentUserApplicationUser\"\n\troute := getComposedRoute(routeName)\n\tcode, body, err := runRequest(routeName, route, payload, signApplicationRequest(application, nil, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n\tc.Assert(body, Not(Equals), \"\")\n\n\tsessionToken := struct {\n\t\tUserID uint64 `json:\"id\"`\n\t\tToken string `json:\"session_token\"`\n\t}{}\n\ter := json.Unmarshal([]byte(body), &sessionToken)\n\tc.Assert(er, IsNil)\n\tc.Assert(sessionToken.UserID, Equals, userFrom.ID)\n\tc.Assert(sessionToken.Token, Not(Equals), \"\")\n\n\tuserFrom.SessionToken = sessionToken.Token\n\n\tpayload = fmt.Sprintf(`{\"session_token\": \"%s\"}`, userFrom.SessionToken)\n\n\trouteName = \"refreshCurrentUserApplicationUserSession\"\n\troute = getComposedRoute(routeName)\n\tcode, body, err = runRequest(routeName, route, payload, signApplicationRequest(application, userFrom, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n\tc.Assert(body, Not(Equals), \"\")\n\n\ter = json.Unmarshal([]byte(body), &sessionToken)\n\tc.Assert(er, IsNil)\n\tc.Assert(sessionToken.UserID, Equals, userFrom.ID)\n\tc.Assert(sessionToken.Token, Not(Equals), \"\")\n\n\tpayload = fmt.Sprintf(`{\"user_to_id\":%d, \"type\": %q}`, userTo.ID, entity.ConnectionTypeFriend)\n\n\trouteName = \"createCurrentUserConnection\"\n\troute = getComposedRoute(routeName)\n\tcode, body, err = runRequest(routeName, route, payload, signApplicationRequest(application, userFrom, true, true))\n\tc.Assert(err, IsNil)\n\tc.Assert(code, Equals, http.StatusCreated)\n}", "func SensuTestToken(sensuurl string, token string) bool {\n\tsensuRepository := domain.GetSensuRepository()\n\treturn sensuRepository.SensuTestToken(sensuurl, token)\n}", "func TestVerifyToken(t *testing.T) {\n t.Errorf(\"No tests written yet for VerifyToken()\")\n}", "func (s *gatewaySuite) TestLogon() {\n\t// assert FIX MD logon\n\tfixm, err := s.fixMd.WaitForMessage(s.MarketDataSessionID, 1)\n\ts.Require().Nil(err)\n\n\terr = s.checkFixTags(fixm, \"35=A\", \"49=BFXFIX\", \"56=EXORG_MD\")\n\ts.Require().Nil(err)\n\n\t// assert FIX order logon\n\tfixm, err = s.fixOrd.WaitForMessage(s.OrderSessionID, 1)\n\ts.Require().Nil(err)\n\n\terr = s.checkFixTags(fixm, \"35=A\", \"49=BFXFIX\", \"56=EXORG_ORD\")\n\ts.Require().Nil(err)\n\n\t// assume both ws clients connected in setup()\n\ts.srvWs.Broadcast(`{\"event\":\"info\",\"version\":2}`)\n\n\t// assert MD ws auth request\n\tmsg, err := s.srvWs.WaitForMessage(MarketDataClient, 0)\n\ts.Require().Nil(err)\n\ts.Require().EqualValues(`{\"subId\":\"nonce1\",\"event\":\"auth\",\"apiKey\":\"apiKey1\",\"authSig\":\"2744ec1afc974eadbda7e09efa03da80578628ba90e2aa5fcba8c2c61014b811f3a8be5a041c3ee35c464a59856b3869\",\"authPayload\":\"AUTHnonce1\",\"authNonce\":\"nonce1\"}`, msg)\n\n\t// assert order ws auth request\n\tmsg, err = s.srvWs.WaitForMessage(OrdersClient, 0)\n\ts.Require().Nil(err)\n\ts.Require().EqualValues(`{\"subId\":\"nonce1\",\"event\":\"auth\",\"apiKey\":\"apiKey1\",\"authSig\":\"2744ec1afc974eadbda7e09efa03da80578628ba90e2aa5fcba8c2c61014b811f3a8be5a041c3ee35c464a59856b3869\",\"authPayload\":\"AUTHnonce1\",\"authNonce\":\"nonce1\"}`, msg)\n}", "func TestWebhookTokenAuthn(t *testing.T) {\n\tauthServerWasCalled := false\n\tauthToken := \"Anything-goes!\"\n\tauthTestUser := \"testuser\"\n\tauthTestUID := \"42\"\n\tauthTestGroups := []string{\"testgroup\"}\n\t// openshift will add the authenticated virtual group\n\texpectedAuthTestGroups := append([]string{\"system:authenticated\"}, authTestGroups...)\n\n\texpectedTokenPost := kauthn.TokenReview{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"authentication.k8s.io/v1beta1\",\n\t\t\tKind: \"TokenReview\",\n\t\t},\n\t\tSpec: kauthn.TokenReviewSpec{Token: authToken},\n\t}\n\n\ttokenResponse := kauthn.TokenReview{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"authentication.k8s.io/v1beta1\",\n\t\t\tKind: \"TokenReview\",\n\t\t},\n\t\tStatus: kauthn.TokenReviewStatus{\n\t\t\tAuthenticated: true,\n\t\t\tUser: kauthn.UserInfo{\n\t\t\t\tUsername: authTestUser,\n\t\t\t\tUID: authTestUID,\n\t\t\t\tGroups: authTestGroups,\n\t\t\t\tExtra: map[string]kauthn.ExtraValue{\n\t\t\t\t\tauthorizationapi.ScopesKey: []string{\n\t\t\t\t\t\t\"user:info\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Write cert we're going to use to verify auth server requests\n\tcaFile, err := ioutil.TempFile(\"\", \"test.crt\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tdefer os.Remove(caFile.Name())\n\tif err := ioutil.WriteFile(caFile.Name(), authLocalhostCert, os.FileMode(0600)); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// Set up a dummy authenticator server\n\tauthServer := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.URL.Path {\n\t\tcase \"/authenticate\":\n\t\t\tauthServerWasCalled = true\n\t\t\tif r.Method != \"POST\" {\n\t\t\t\tt.Fatalf(\"Expected POST to /authenticate, got %s\", r.Method)\n\t\t\t}\n\t\t\tif err := r.ParseForm(); err != nil {\n\t\t\t\tt.Fatalf(\"Error parsing form POSTed to /token: %v\", err)\n\t\t\t}\n\t\t\tvar tokenPost kauthn.TokenReview\n\t\t\tif err = json.NewDecoder(r.Body).Decode(&tokenPost); err != nil {\n\t\t\t\tt.Fatalf(\"Expected TokenReview structure in POST request: %v\", err)\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(tokenPost, expectedTokenPost) {\n\t\t\t\tt.Fatalf(\"Expected\\n%#v\\ngot\\n%#v\", expectedTokenPost, tokenPost)\n\t\t\t}\n\t\t\tif err = json.NewEncoder(w).Encode(tokenResponse); err != nil {\n\t\t\t\tt.Fatalf(\"Failed to encode Token Review response: %v\", err)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tt.Fatalf(\"Unexpected Token Review request: %v\", r.URL.Path)\n\t\t}\n\t}))\n\tcert, err := tls.X509KeyPair(authLocalhostCert, authLocalhostKey)\n\tauthServer.TLS = &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\tauthServer.StartTLS()\n\tdefer authServer.Close()\n\n\tauthConfigFile, err := ioutil.TempFile(\"\", \"test.cfg\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tdefer os.Remove(authConfigFile.Name())\n\tauthConfigObj := kclientcmdapi.Config{\n\t\tClusters: map[string]*kclientcmdapi.Cluster{\n\t\t\t\"authService\": {\n\t\t\t\tCertificateAuthority: caFile.Name(),\n\t\t\t\tServer: authServer.URL + \"/authenticate\",\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*kclientcmdapi.AuthInfo{\n\t\t\t\"apiServer\": {\n\t\t\t\tClientCertificateData: authLocalhostCert,\n\t\t\t\tClientKeyData: authLocalhostKey,\n\t\t\t},\n\t\t},\n\t\tCurrentContext: \"webhook\",\n\t\tContexts: map[string]*kclientcmdapi.Context{\n\t\t\t\"webhook\": {\n\t\t\t\tCluster: \"authService\",\n\t\t\t\tAuthInfo: \"apiServer\",\n\t\t\t},\n\t\t},\n\t}\n\tif err := kclientcmd.WriteToFile(authConfigObj, authConfigFile.Name()); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// Get master config\n\tmasterOptions, err := testserver.DefaultMasterOptions()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tdefer testserver.CleanupMasterEtcd(t, masterOptions)\n\n\tmasterOptions.AuthConfig.WebhookTokenAuthenticators = []configapi.WebhookTokenAuthenticator{\n\t\t{\n\t\t\tConfigFile: authConfigFile.Name(),\n\t\t\tCacheTTL: \"10s\",\n\t\t},\n\t}\n\n\t// Start server\n\tclusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tclientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// Try to authenticate with a token that can be validated only by our\n\t// external token reviewer\n\tuserConfig := restclient.AnonymousClientConfig(clientConfig)\n\tuserConfig.BearerToken = authToken\n\n\tuserClient, err := userclient.NewForConfig(userConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tuserWhoamiOptions := whoami.WhoAmIOptions{UserInterface: userClient.Users(), IOStreams: genericclioptions.NewTestIOStreamsDiscard()}\n\tretrievedUser, err := userWhoamiOptions.WhoAmI()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif retrievedUser.Name != authTestUser {\n\t\tt.Errorf(\"expected username %v, got %v\", authTestUser, retrievedUser.Name)\n\t}\n\tif retrievedUser.UID != ktypes.UID(authTestUID) {\n\t\tt.Errorf(\"expected username %v, got %v\", authTestUID, retrievedUser.UID)\n\t}\n\tif !reflect.DeepEqual(retrievedUser.Groups, expectedAuthTestGroups) {\n\t\tt.Errorf(\"expected Groups %v, got %v\", expectedAuthTestGroups, retrievedUser.Groups)\n\t}\n\tif !authServerWasCalled {\n\t\tt.Errorf(\"Server was not called in the test\")\n\t}\n\n\toauthClient, err := oauthclient.NewForConfig(userConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\terr = oauthClient.Oauth().OAuthAccessTokens().Delete(\"XYZ\", &metav1.DeleteOptions{})\n\tif !kerrors.IsForbidden(err) {\n\t\tt.Errorf(\"expected a forbidden error, got %v\", err)\n\t}\n\tfor _, errstr := range []string{\"scope\", \"user:info\"} {\n\t\tif !strings.Contains(err.Error(), errstr) {\n\t\t\tt.Errorf(\"missing expected string '%s' in error message: %s\", errstr, err.Error())\n\t\t}\n\t}\n}", "func testEvent(\n\tt *testing.T,\n\tparseCallback func(toks Toks) (Args, error),\n\thandleCallback func(ctx Context) error,\n\tresolveCallback func(ctx Context),\n\tfilter Filter,\n\tmockSession *discordgo.Session,\n\tincomingMockMessage *discordgo.MessageCreate,\n\tmiddlewares []Middleware,\n) {\n\tr := &Router{\n\t\tSession: mockSession,\n\t\tp: nil,\n\t}\n\n\tevent := &testOnMsg{\n\t\tParseCallback: parseCallback,\n\t\tHandleCallback: handleCallback,\n\t\tResolveCallback: resolveCallback,\n\t}\n\n\tswitch {\n\tcase event.ParseCallback == nil:\n\t\tt.Fatal(\"ParseCallback cannot be nil\")\n\tcase event.HandleCallback == nil:\n\t\tt.Fatal(\"HandleCallback cannot be nil\")\n\tcase event.ResolveCallback == nil:\n\t\tt.Fatal(\"ResolveCallback cannot be nil\")\n\t}\n\n\tr.makeEvent(event, filter, middlewares)(mockSession, incomingMockMessage)\n}", "func TestMockOnConnect(t *testing.T) {\n\tmockServer := &MockRailsServer{T: t, Behaviour: MockConnect}\n\n\tdialer := wstest.NewDialer(mockServer)\n\tdialer.HandshakeTimeout = time.Second * 2\n\n\tclient := NewClient(fakeEndpoint).WithDialer(dialer)\n\n\tcalled := make(chan struct{})\n\n\tclient.OnConnect(func(conn *websocket.Conn) error {\n\t\tcalled <- struct{}{}\n\t\treturn nil\n\t})\n\terr := client.Serve()\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treceiveSleepMs(2000, called, t)\n}", "func TestEmittingMessage(t *testing.T) {\n\tsink := make(chan bool, 1)\n\tclient := NewClient()\n\n\ttimeout, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tdefer cancel()\n\n\tclient.Subscribe(Before, func(ctx context.Context, message interface{}) {\n\t\tsink <- true\n\t})\n\n\tclient.Emit(context.Background(), Before, nil)\n\n\tselect {\n\tcase <-timeout.Done():\n\t\tt.Fatal(\"Timeout reached\")\n\tcase <-sink:\n\t}\n}", "func SetToken(token string) {\n\tservchanToken = token\n}", "func RegisteringTokenTest(env *models.PhotonEnvReader, allowFail bool) {\n\t// 1. register a not-exist token\n\tcase1 := &APITestCase{\n\t\tCaseName: \"Register a not-exist token\",\n\t\tAllowFail: allowFail,\n\t\tReq: &models.Req{\n\t\t\tAPIName: \"RegisteringOneToken\",\n\t\t\tFullURL: env.RandomNode().Host + \"/api/1/tokens/0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF\",\n\t\t\tMethod: http.MethodPut,\n\t\t\tPayload: \"\",\n\t\t\tTimeout: time.Second * 120,\n\t\t},\n\t\tTargetStatusCode: 409,\n\t}\n\tcase1.Run()\n\t// 2. register a new token\n\tnewTokenAddress := deployNewToken()\n\tcase2 := &APITestCase{\n\t\tCaseName: \"Register a new token\",\n\t\tAllowFail: allowFail,\n\t\tReq: &models.Req{\n\t\t\tAPIName: \"RegisteringOneToken\",\n\t\t\tFullURL: env.RandomNode().Host + \"/api/1/tokens/\" + newTokenAddress,\n\t\t\tMethod: http.MethodPut,\n\t\t\tPayload: \"\",\n\t\t\tTimeout: time.Second * 180,\n\t\t},\n\t\tTargetStatusCode: 200,\n\t}\n\tcase2.Run()\n}", "func SimulateMintToken(k keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper) simtypes.Operation {\n\treturn func(\n\t\tr *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context,\n\t\taccs []simtypes.Account, chainID string,\n\t) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {\n\n\t\ttoken, maxFee := selectToken(ctx, k, ak, bk, true)\n\t\tsimToAccount, _ := simtypes.RandomAcc(r, accs)\n\n\t\tmsg := types.NewMsgMintToken(token.GetSymbol(), token.GetOwnerString(), simToAccount.Address.String(), 100)\n\n\t\townerAccount, found := simtypes.FindAccount(accs, token.GetOwner())\n\t\tif !found {\n\t\t\treturn simtypes.NoOpMsg(types.ModuleName, msg.Type(), fmt.Sprintf(\"account[%s] does not found\", token.GetOwnerString())), \n\t\t\t\tnil, fmt.Errorf(\"account[%s] does not found\", token.GetOwnerString())\n\t\t}\n\n\t\towner, _ := sdk.AccAddressFromBech32(msg.Owner)\n\t\taccount := ak.GetAccount(ctx, owner)\n\t\tfees, err := simtypes.RandomFees(r, ctx, maxFee)\n\t\tif err != nil {\n\t\t\treturn simtypes.NoOpMsg(types.ModuleName, msg.Type(), \"unable to generate fees\"), nil, err\n\t\t}\n\n\t\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\t\ttx, err := helpers.GenTx(\n\t\t\ttxGen,\n\t\t\t[]sdk.Msg{msg},\n\t\t\tfees,\n\t\t\thelpers.DefaultGenTxGas,\n\t\t\tchainID,\n\t\t\t[]uint64{account.GetAccountNumber()},\n\t\t\t[]uint64{account.GetSequence()},\n\t\t\townerAccount.PrivKey,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn simtypes.NoOpMsg(types.ModuleName, msg.Type(), \"unable to generate mock tx\"), nil, err\n\t\t}\n\n\t\tif _, _, err = app.Deliver(txGen.TxEncoder(), tx); err != nil {\n\t\t\treturn simtypes.NoOpMsg(types.ModuleName, msg.Type(), \"unable to deliver tx\"), nil, err\n\t\t}\n\n\t\treturn simtypes.NewOperationMsg(msg, true, \"simulate mint token\"), nil, nil\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenEvent with nil sends a connection token event with a nil token.
func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { s.Service().TokenEvent(mock.CID, nil) s.GetMsg().AssertTokenEvent(mock.CID, nil) }) }
[ "func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEventWithID(mock.CID, \"foo\", nil)\n\t\ts.GetMsg().AssertTokenEventWithID(mock.CID, \"foo\", nil)\n\t})\n}", "func TestConfigEmptyToken(t *testing.T) {\n\tconfig := Config{}\n\n\tif nullVOClient := config.VictorOpsClient; nullVOClient != nil {\n\t\tt.Fatalf(\"error: Expected the client to be empty: %v\", nullVOClient)\n\t}\n\n}", "func TestServiceTokenEvent_WithObjectToken_SendsToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, mock.Token)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, mock.Token)\n\t})\n}", "func TestAuthRequestTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(mock.Token)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, mock.Token)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func TestEmptyToken(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(true, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\tassert.NoError(err)\n\n\t// setup TA service to use JWT-based authentication\n\ttrustAgentService.router = mux.NewRouter()\n\ttrustAgentService.router.Use(middleware.NewTokenAuth(\"../test/mockJWTDir\", \"../test/mockCACertsDir\", mockRetrieveJWTSigningCerts, cacheTime))\n\ttrustAgentService.router.HandleFunc(\"/v2/tag\", errorHandler(requiresPermission(setAssetTag(CreateTestConfig(), mockedTpmFactory), []string{postDeployTagPerm}))).Methods(\"POST\")\n\n\tjsonString := `{\"tag\" : \"tHgfRQED1+pYgEZpq3dZC9ONmBCZKdx10LErTZs1k/k=\", \"hardware_uuid\" : \"7a569dad-2d82-49e4-9156-069b0065b262\"}`\n\n\trequest, err := http.NewRequest(\"POST\", \"/v2/tag\", bytes.NewBuffer([]byte(jsonString)))\n\tassert.NoError(err)\n\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", \"Bearer \"+EmptyJWTToken)\n\n\trecorder := httptest.NewRecorder()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tresponse := recorder.Result()\n\tfmt.Printf(\"StatusCode: %d\\n\", response.StatusCode)\n\tassert.Equal(http.StatusUnauthorized, response.StatusCode)\n}", "func TestAuthParseTokenWithNilToken(t *testing.T) {\n\tvar o struct {\n\t\tUser string `json:\"user\"`\n\t\tID int `json:\"id\"`\n\t}\n\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.ParseToken(&o)\n\t\t\trestest.AssertEqualJSON(t, \"o.User\", o.User, \"\")\n\t\t\trestest.AssertEqualJSON(t, \"o.ID\", o.ID, 0)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func noValidTokenTest(t *testing.T, r *http.Request, h http.Handler, auth *mock.Authenticator) {\n\toriginal := auth.AuthenticateFn\n\tauth.AuthenticateFn = authenticateGenerator(false, errors.New(\"An error\"))\n\tw := httptest.NewRecorder()\n\th.ServeHTTP(w, r)\n\ttest.Equals(t, http.StatusBadRequest, w.Result().StatusCode)\n\tauth.AuthenticateFn = authenticateGenerator(false, nil)\n\tw = httptest.NewRecorder()\n\th.ServeHTTP(w, r)\n\ttest.Equals(t, http.StatusUnauthorized, w.Result().StatusCode)\n\tauth.AuthenticateFn = original\n}", "func (fgs *FakeGraphSync) AssertNoCancelReceived(t *testing.T) {\n\trequire.Empty(t, fgs.cancels, \"should not cancel request\")\n}", "func TestTokenIsSet(t *testing.T) {\n\tconfiguration := ReadConfig()\n\ttoken := configuration.Token\n\n\tif token == \"\" {\n\t\tt.Error(\"Token misconfigured\")\n\t}\n\n\t// A dumb way to check if a dummy token has been used\n\tif len(token) < 16 {\n\t\tt.Error(\"Token misconfigured\")\n\t}\n\n\tt.Log(\"Token set\")\n}", "func (s *Service) TestToken(ctx context.Context, info *pushmdl.PushInfo, token string) (err error) {\n\tparams := url.Values{}\n\tparams.Add(\"app_id\", strconv.FormatInt(info.APPID, 10))\n\tparams.Add(\"alert_title\", info.Title)\n\tparams.Add(\"alert_body\", info.Summary)\n\tparams.Add(\"token\", token)\n\tparams.Add(\"link_type\", strconv.FormatInt(int64(info.LinkType), 10))\n\tparams.Add(\"link_value\", info.LinkValue)\n\tparams.Add(\"sound\", strconv.Itoa(info.Sound))\n\tparams.Add(\"vibration\", strconv.Itoa(info.Vibration))\n\tparams.Add(\"expire_time\", strconv.FormatInt(int64(info.ExpireTime), 10))\n\tparams.Add(\"image_url\", info.ImageURL)\n\tif err = s.httpClient.Post(ctx, _testTokenURL, \"\", params, nil); err != nil {\n\t\tlog.Error(\"s.TestToken(%+v) error(%v)\", info, err)\n\t}\n\treturn\n}", "func (s *osoSubscriptionServiceTestSuite) TestNoTokenManagerInContextFails() {\n\t_, err := s.Application.OSOSubscriptionService().LoadOSOSubscriptionStatus(context.Background(), oauth2.Token{})\n\trequire.Error(s.T(), err)\n}", "func TestServiceTokenEvent_WithInvalidCID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\trestest.AssertPanic(t, func() {\n\t\t\ts.Service().TokenEvent(\"invalid.*.cid\", nil)\n\t\t})\n\t})\n}", "func TestAuthRawTokenWithNoToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertEqualJSON(t, \"RawToken\", r.RawToken(), nil)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func (fgs *FakeGraphSync) AssertNoRequestReceived(t *testing.T) {\n\trequire.Empty(t, fgs.requests, \"should not receive request\")\n}", "func TestRequestEmpty(t *testing.T) {\n\t// Initialize server\n\tserver := setupServer(\n\t\tt,\n\t\t&serverImpl{\n\t\t\tonRequest: func(\n\t\t\t\t_ context.Context,\n\t\t\t\t_ webwire.Connection,\n\t\t\t\tmsg webwire.Message,\n\t\t\t) (webwire.Payload, error) {\n\t\t\t\t// Expect the following request to not even arrive\n\t\t\t\tt.Error(\"Not expected but reached\")\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\twebwire.ServerOptions{},\n\t)\n\n\t// Initialize client\n\tclient := newCallbackPoweredClient(\n\t\tserver.Addr().String(),\n\t\twebwireClient.Options{\n\t\t\tDefaultRequestTimeout: 2 * time.Second,\n\t\t},\n\t\tcallbackPoweredClientHooks{},\n\t)\n\n\t// Send request without a name and without a payload.\n\t// Expect a protocol error in return not sending the invalid request off\n\t_, err := client.connection.Request(context.Background(), \"\", nil)\n\tif _, isProtoErr := err.(webwire.ProtocolErr); !isProtoErr {\n\t\tt.Fatalf(\"Expected a protocol error, got: %v\", err)\n\t}\n}", "func TestGetEventStatusOKNoEvent(t *testing.T) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tassert.Equal(t, r.Method, \"GET\", \"Expect GET request\")\n\t\tassert.Equal(t, r.URL.EscapedPath(), \"/event\", \"Expect /event endpoint\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\teventList := `{\n\t\t\t\"events\":[],\n\t\t\t\t\"pageSize\":10,\n\t\t\t\t\"totalCount\":0\n\t\t\t}`\n\n\t\tw.Write([]byte(eventList))\n\t})\n\n\thttpClient, teardown := testingHTTPClient(handler)\n\tdefer teardown()\n\n\teventHandler := NewEventHandler(\"https://localhost\")\n\teventHandler.HTTPClient = httpClient\n\tcloudEvent, errObj := eventHandler.GetEvent(\"8929e5e5-3826-488f-9257-708bfa974909\", \"sh.keptn.events.evaluation-done\")\n\n\tif cloudEvent != nil {\n\t\tt.Error(\"do not expect a Keptn Cloud event\")\n\t}\n\n\tif errObj == nil {\n\t\tt.Errorf(\"an error occurred %v\", errObj.Message)\n\t}\n\n\tif *errObj.Message != \"No Keptn sh.keptn.events.evaluation-done event found for context: 8929e5e5-3826-488f-9257-708bfa974909\" {\n\t\tt.Error(\"response message has changed\")\n\t}\n}", "func TestToken(t *testing.T) {\n\n\ttoken := initToken()\n\tfmt.Println(token)\n}", "func TestNoSendNoError(t *testing.T) {\n\n\ttestErrorInit()\n\n\tgo notifyError(notifier, service)\n\n\ttime.Sleep(100 * time.Millisecond)\n\tif notifier.wasWritten {\n\t\tt.Error(\"There was no message to send for notification\")\n\t}\n}", "func (s *gatewaySuite) TestLogonNoCredentials() {\n\ts.TearDownTest()\n\toldSettings := s.settings\n\tdefer func() { s.settings = oldSettings }()\n\ts.settings = mockFixSettings{FixVersion: s.settings.FixVersion}\n\ts.SetupTest()\n\n\t// give clients an opportunity to connect, but they should NOT be established\n\terr := s.srvWs.WaitForClientCount(2)\n\ts.Require().NotNil(err)\n\n\tfixm, err := s.fixMd.WaitForMessage(s.MarketDataSessionID, 1)\n\ts.Require().Nil(err)\n\n\t// expect malformed logon\n\terr = s.checkFixTags(fixm, \"35=A\", \"49=BFXFIX\", \"56=EXORG_MD\")\n\ts.Require().Nil(err)\n\n\t// logon reject prevents websocket connections\n\terr = s.srvWs.WaitForClientCount(0)\n\ts.Require().Nil(err)\n\n\t// TODO assert reject?\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenEvent with an invalid cid causes panic.
func TestServiceTokenEventWithID_WithInvalidCID_CausesPanic(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { restest.AssertPanic(t, func() { s.Service().TokenEventWithID("invalid.*.cid", "foo", nil) }) }) }
[ "func TestServiceTokenEvent_WithInvalidCID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\trestest.AssertPanic(t, func() {\n\t\t\ts.Service().TokenEvent(\"invalid.*.cid\", nil)\n\t\t})\n\t})\n}", "func TestInvalidConsensusChangeSubscription(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tcst, err := createConsensusSetTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cst.Close()\n\n\tms := newMockSubscriber()\n\tbadCCID := modules.ConsensusChangeID{255, 255, 255}\n\terr = cst.cs.ConsensusSetSubscribe(&ms, badCCID, cst.cs.tg.StopChan())\n\tif err != modules.ErrInvalidConsensusChangeID {\n\t\tt.Error(\"consensus set returning the wrong error during an invalid subscription:\", err)\n\t}\n\n\tcst.cs.mu.Lock()\n\tfor i := range cst.cs.subscribers {\n\t\tif cst.cs.subscribers[i] == &ms {\n\t\t\tt.Fatal(\"subscriber was not removed from subscriber list after an erroneus subscription\")\n\t\t}\n\t}\n\tcst.cs.mu.Unlock()\n}", "func TestInvalidAuth(t *testing.T) {\n\tif _, err := ValidateYubiKey(yubiAuth, testInitialYKOTP); err == nil {\n\t\tt.Fatal(\"auth: expect failure with re-used OTP\")\n\t}\n}", "func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEventWithID(mock.CID, \"foo\", nil)\n\t\ts.GetMsg().AssertTokenEventWithID(mock.CID, \"foo\", nil)\n\t})\n}", "func TestVnicContainer_Invalid(t *testing.T) {\n\tvnic, err := newContainerVnic(\"testcvnic\")\n\n\tif err = vnic.getDevice(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.enable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.disable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.destroy(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n}", "func TestInvalidCollectInterval(t *testing.T) {\n\tensureProcessExit(t, \"TestNoDatadogAPIKey\",\n\t\tfalse, \"invalid duration\",\n\t\t\"C2D_COLLECT_INTERVAL=some_bogus_value\")\n}", "func TestBadToken(t *testing.T) {\n\n\t// Run the command with a bad token value\n\toutput := executeCommand(\"123\")\n\n\t// We should have a subcommand required command and a complete usage dump\n\trequire.NotNil(t, executeError, \"there should have been an error\")\n\trequire.Condition(t, func() bool {\n\t\treturn checkForExpectedSTSCallFailure(executeError)\n\t}, \"Error should have complained about nonexistent credentials file or invalid MFA token length\")\n\n\trequire.Empty(t, output, \"Output for an error condition should have been empty\")\n}", "func TestInvalidToValidSubscription(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tcst, err := createConsensusSetTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cst.Close()\n\n\t// Start by performing a bad subscribe.\n\tms := newMockSubscriber()\n\tbadCCID := modules.ConsensusChangeID{255, 255, 255}\n\terr = cst.cs.ConsensusSetSubscribe(&ms, badCCID, cst.cs.tg.StopChan())\n\tif err != modules.ErrInvalidConsensusChangeID {\n\t\tt.Error(\"consensus set returning the wrong error during an invalid subscription:\", err)\n\t}\n\n\t// Perform a correct subscribe.\n\terr = cst.cs.ConsensusSetSubscribe(&ms, modules.ConsensusChangeBeginning, cst.cs.tg.StopChan())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Mine a block and check that the mock subscriber only got a single\n\t// consensus change.\n\tnumPrevUpdates := len(ms.updates)\n\t_, err = cst.miner.AddBlock()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(ms.updates) != numPrevUpdates+1 {\n\t\tt.Error(\"subscriber received two consensus changes for a single block\")\n\t}\n}", "func TestVnic_Invalid(t *testing.T) {\n\tvnic, err := newVnic(\"testvnic\")\n\n\tif err = vnic.getDevice(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.enable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.disable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.destroy(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n}", "func TestConnectInvalidAddr(t *testing.T) {\n\t// connect\n\tctx := createContext(t, time.Second*20)\n\n\t_, errConnect := base.NewMilvusClient(ctx, client.Config{Address: \"aa\"})\n\tcommon.CheckErr(t, errConnect, false, \"context deadline exceeded\")\n}", "func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, nil)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t})\n}", "func Test_Middleware_RequestID_Panic(t *testing.T) {\n\tdefer func() {\n\t\tutils.AssertEqual(t,\n\t\t\t\"RequestID: the following option types are allowed: `string`, `func() string`, `func(*fiber.Ctx) bool`, `RequestIDConfig`\",\n\t\t\tfmt.Sprintf(\"%s\", recover()))\n\t}()\n\n\tRequestID(0)\n}", "func contextInvalid(context string) bool {\n\tif context != \".\" && !strings.Contains(context, \"cx-\") {\n\t\tlog.Warn(\"Context is malformed.\", \"context\", context)\n\t\treturn true\n\t}\n\treturn false\n}", "func testBatchCTXInvalidAddenda(t testing.TB) {\n\tmockBatch := NewBatchCTX(mockBatchCTXHeader())\n\tmockBatch.AddEntry(mockCTXEntryDetail())\n\taddenda05 := mockAddenda05()\n\taddenda05.TypeCode = \"63\"\n\tmockBatch.GetEntries()[0].AddAddenda05(addenda05)\n\tmockBatch.Entries[0].AddendaRecordIndicator = 1\n\terr := mockBatch.Create()\n\tif !base.Match(err, ErrAddendaTypeCode) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func TestNewIDAllocatorInvalidArgs(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\targs := [][]uint32{\n\t\t{0, 10}, // minID <= 0\n\t\t{2, 0}, // blockSize < 1\n\t}\n\tfor i := range args {\n\t\tif _, err := newIDAllocator(nil, nil, args[i][0], args[i][1], nil); err == nil {\n\t\t\tt.Errorf(\"expect to have error return, but got nil\")\n\t\t}\n\t}\n}", "func CheckTheValidityOfTheToken(token string) (newToken string, err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n err = createError(011)\n\n if v, ok := tokens[token]; ok {\n var expires = v.(map[string]interface{})[\"expires\"].(time.Time)\n var userID = v.(map[string]interface{})[\"id\"].(string)\n\n if expires.Sub(time.Now().Local()) < 0 {\n return\n }\n\n newToken = setToken(userID, token)\n\n err = nil\n\n } else {\n return\n }\n\n return\n}", "func ErrInvalidVin(codespace sdk.CodespaceType) sdk.Error {\n\treturn sdk.NewError(codespace, InvalidVin, InvalidVinMessage)\n}", "func TestConcurrencyFault(t *testing.T) {\n\tfault := NewConcurrencyFault(\"dummy-key\", 1234)\n\tassert.Equal(t, fault.Error(), \"ConcurrencyFault: dummy-key at 1234\", \"The ConcurrencyFault message should be correct.\")\n\tisConcurrencyFault, _ := IsConcurrencyFault(fault)\n\tassert.True(t, isConcurrencyFault, \"Should be a ConcurrencyFault\")\n\n\tisDomainFault, _ := IsDomainFault(fault)\n\tassert.False(t, isDomainFault, \"Should not be a DomainFault\")\n}", "func TestAuthResource_WithInvalidRID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertPanicNoRecover(t, func() {\n\t\t\t\tr.Resource(\"test..foo\")\n\t\t\t})\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertErrorCode(res.CodeInternalError)\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenEvent with nil sends a connection token event with a nil token.
func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { s.Service().TokenEventWithID(mock.CID, "foo", nil) s.GetMsg().AssertTokenEventWithID(mock.CID, "foo", nil) }) }
[ "func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, nil)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t})\n}", "func TestConfigEmptyToken(t *testing.T) {\n\tconfig := Config{}\n\n\tif nullVOClient := config.VictorOpsClient; nullVOClient != nil {\n\t\tt.Fatalf(\"error: Expected the client to be empty: %v\", nullVOClient)\n\t}\n\n}", "func TestServiceTokenEvent_WithObjectToken_SendsToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, mock.Token)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, mock.Token)\n\t})\n}", "func TestAuthRequestTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(mock.Token)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, mock.Token)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func TestEmptyToken(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(true, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\tassert.NoError(err)\n\n\t// setup TA service to use JWT-based authentication\n\ttrustAgentService.router = mux.NewRouter()\n\ttrustAgentService.router.Use(middleware.NewTokenAuth(\"../test/mockJWTDir\", \"../test/mockCACertsDir\", mockRetrieveJWTSigningCerts, cacheTime))\n\ttrustAgentService.router.HandleFunc(\"/v2/tag\", errorHandler(requiresPermission(setAssetTag(CreateTestConfig(), mockedTpmFactory), []string{postDeployTagPerm}))).Methods(\"POST\")\n\n\tjsonString := `{\"tag\" : \"tHgfRQED1+pYgEZpq3dZC9ONmBCZKdx10LErTZs1k/k=\", \"hardware_uuid\" : \"7a569dad-2d82-49e4-9156-069b0065b262\"}`\n\n\trequest, err := http.NewRequest(\"POST\", \"/v2/tag\", bytes.NewBuffer([]byte(jsonString)))\n\tassert.NoError(err)\n\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", \"Bearer \"+EmptyJWTToken)\n\n\trecorder := httptest.NewRecorder()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tresponse := recorder.Result()\n\tfmt.Printf(\"StatusCode: %d\\n\", response.StatusCode)\n\tassert.Equal(http.StatusUnauthorized, response.StatusCode)\n}", "func TestAuthParseTokenWithNilToken(t *testing.T) {\n\tvar o struct {\n\t\tUser string `json:\"user\"`\n\t\tID int `json:\"id\"`\n\t}\n\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.ParseToken(&o)\n\t\t\trestest.AssertEqualJSON(t, \"o.User\", o.User, \"\")\n\t\t\trestest.AssertEqualJSON(t, \"o.ID\", o.ID, 0)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func noValidTokenTest(t *testing.T, r *http.Request, h http.Handler, auth *mock.Authenticator) {\n\toriginal := auth.AuthenticateFn\n\tauth.AuthenticateFn = authenticateGenerator(false, errors.New(\"An error\"))\n\tw := httptest.NewRecorder()\n\th.ServeHTTP(w, r)\n\ttest.Equals(t, http.StatusBadRequest, w.Result().StatusCode)\n\tauth.AuthenticateFn = authenticateGenerator(false, nil)\n\tw = httptest.NewRecorder()\n\th.ServeHTTP(w, r)\n\ttest.Equals(t, http.StatusUnauthorized, w.Result().StatusCode)\n\tauth.AuthenticateFn = original\n}", "func (fgs *FakeGraphSync) AssertNoCancelReceived(t *testing.T) {\n\trequire.Empty(t, fgs.cancels, \"should not cancel request\")\n}", "func TestTokenIsSet(t *testing.T) {\n\tconfiguration := ReadConfig()\n\ttoken := configuration.Token\n\n\tif token == \"\" {\n\t\tt.Error(\"Token misconfigured\")\n\t}\n\n\t// A dumb way to check if a dummy token has been used\n\tif len(token) < 16 {\n\t\tt.Error(\"Token misconfigured\")\n\t}\n\n\tt.Log(\"Token set\")\n}", "func (s *Service) TestToken(ctx context.Context, info *pushmdl.PushInfo, token string) (err error) {\n\tparams := url.Values{}\n\tparams.Add(\"app_id\", strconv.FormatInt(info.APPID, 10))\n\tparams.Add(\"alert_title\", info.Title)\n\tparams.Add(\"alert_body\", info.Summary)\n\tparams.Add(\"token\", token)\n\tparams.Add(\"link_type\", strconv.FormatInt(int64(info.LinkType), 10))\n\tparams.Add(\"link_value\", info.LinkValue)\n\tparams.Add(\"sound\", strconv.Itoa(info.Sound))\n\tparams.Add(\"vibration\", strconv.Itoa(info.Vibration))\n\tparams.Add(\"expire_time\", strconv.FormatInt(int64(info.ExpireTime), 10))\n\tparams.Add(\"image_url\", info.ImageURL)\n\tif err = s.httpClient.Post(ctx, _testTokenURL, \"\", params, nil); err != nil {\n\t\tlog.Error(\"s.TestToken(%+v) error(%v)\", info, err)\n\t}\n\treturn\n}", "func (s *osoSubscriptionServiceTestSuite) TestNoTokenManagerInContextFails() {\n\t_, err := s.Application.OSOSubscriptionService().LoadOSOSubscriptionStatus(context.Background(), oauth2.Token{})\n\trequire.Error(s.T(), err)\n}", "func TestServiceTokenEvent_WithInvalidCID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\trestest.AssertPanic(t, func() {\n\t\t\ts.Service().TokenEvent(\"invalid.*.cid\", nil)\n\t\t})\n\t})\n}", "func TestAuthRawTokenWithNoToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertEqualJSON(t, \"RawToken\", r.RawToken(), nil)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func (fgs *FakeGraphSync) AssertNoRequestReceived(t *testing.T) {\n\trequire.Empty(t, fgs.requests, \"should not receive request\")\n}", "func TestRequestEmpty(t *testing.T) {\n\t// Initialize server\n\tserver := setupServer(\n\t\tt,\n\t\t&serverImpl{\n\t\t\tonRequest: func(\n\t\t\t\t_ context.Context,\n\t\t\t\t_ webwire.Connection,\n\t\t\t\tmsg webwire.Message,\n\t\t\t) (webwire.Payload, error) {\n\t\t\t\t// Expect the following request to not even arrive\n\t\t\t\tt.Error(\"Not expected but reached\")\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\twebwire.ServerOptions{},\n\t)\n\n\t// Initialize client\n\tclient := newCallbackPoweredClient(\n\t\tserver.Addr().String(),\n\t\twebwireClient.Options{\n\t\t\tDefaultRequestTimeout: 2 * time.Second,\n\t\t},\n\t\tcallbackPoweredClientHooks{},\n\t)\n\n\t// Send request without a name and without a payload.\n\t// Expect a protocol error in return not sending the invalid request off\n\t_, err := client.connection.Request(context.Background(), \"\", nil)\n\tif _, isProtoErr := err.(webwire.ProtocolErr); !isProtoErr {\n\t\tt.Fatalf(\"Expected a protocol error, got: %v\", err)\n\t}\n}", "func TestGetEventStatusOKNoEvent(t *testing.T) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tassert.Equal(t, r.Method, \"GET\", \"Expect GET request\")\n\t\tassert.Equal(t, r.URL.EscapedPath(), \"/event\", \"Expect /event endpoint\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\teventList := `{\n\t\t\t\"events\":[],\n\t\t\t\t\"pageSize\":10,\n\t\t\t\t\"totalCount\":0\n\t\t\t}`\n\n\t\tw.Write([]byte(eventList))\n\t})\n\n\thttpClient, teardown := testingHTTPClient(handler)\n\tdefer teardown()\n\n\teventHandler := NewEventHandler(\"https://localhost\")\n\teventHandler.HTTPClient = httpClient\n\tcloudEvent, errObj := eventHandler.GetEvent(\"8929e5e5-3826-488f-9257-708bfa974909\", \"sh.keptn.events.evaluation-done\")\n\n\tif cloudEvent != nil {\n\t\tt.Error(\"do not expect a Keptn Cloud event\")\n\t}\n\n\tif errObj == nil {\n\t\tt.Errorf(\"an error occurred %v\", errObj.Message)\n\t}\n\n\tif *errObj.Message != \"No Keptn sh.keptn.events.evaluation-done event found for context: 8929e5e5-3826-488f-9257-708bfa974909\" {\n\t\tt.Error(\"response message has changed\")\n\t}\n}", "func TestToken(t *testing.T) {\n\n\ttoken := initToken()\n\tfmt.Println(token)\n}", "func TestNoSendNoError(t *testing.T) {\n\n\ttestErrorInit()\n\n\tgo notifyError(notifier, service)\n\n\ttime.Sleep(100 * time.Millisecond)\n\tif notifier.wasWritten {\n\t\tt.Error(\"There was no message to send for notification\")\n\t}\n}", "func (s *gatewaySuite) TestLogonNoCredentials() {\n\ts.TearDownTest()\n\toldSettings := s.settings\n\tdefer func() { s.settings = oldSettings }()\n\ts.settings = mockFixSettings{FixVersion: s.settings.FixVersion}\n\ts.SetupTest()\n\n\t// give clients an opportunity to connect, but they should NOT be established\n\terr := s.srvWs.WaitForClientCount(2)\n\ts.Require().NotNil(err)\n\n\tfixm, err := s.fixMd.WaitForMessage(s.MarketDataSessionID, 1)\n\ts.Require().Nil(err)\n\n\t// expect malformed logon\n\terr = s.checkFixTags(fixm, \"35=A\", \"49=BFXFIX\", \"56=EXORG_MD\")\n\ts.Require().Nil(err)\n\n\t// logon reject prevents websocket connections\n\terr = s.srvWs.WaitForClientCount(0)\n\ts.Require().Nil(err)\n\n\t// TODO assert reject?\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenEvent with an invalid cid causes panic.
func TestServiceTokenEvent_WithInvalidCID_CausesPanic(t *testing.T) { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { restest.AssertPanic(t, func() { s.Service().TokenEvent("invalid.*.cid", nil) }) }) }
[ "func TestServiceTokenEventWithID_WithInvalidCID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\trestest.AssertPanic(t, func() {\n\t\t\ts.Service().TokenEventWithID(\"invalid.*.cid\", \"foo\", nil)\n\t\t})\n\t})\n}", "func TestInvalidConsensusChangeSubscription(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tcst, err := createConsensusSetTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cst.Close()\n\n\tms := newMockSubscriber()\n\tbadCCID := modules.ConsensusChangeID{255, 255, 255}\n\terr = cst.cs.ConsensusSetSubscribe(&ms, badCCID, cst.cs.tg.StopChan())\n\tif err != modules.ErrInvalidConsensusChangeID {\n\t\tt.Error(\"consensus set returning the wrong error during an invalid subscription:\", err)\n\t}\n\n\tcst.cs.mu.Lock()\n\tfor i := range cst.cs.subscribers {\n\t\tif cst.cs.subscribers[i] == &ms {\n\t\t\tt.Fatal(\"subscriber was not removed from subscriber list after an erroneus subscription\")\n\t\t}\n\t}\n\tcst.cs.mu.Unlock()\n}", "func TestInvalidAuth(t *testing.T) {\n\tif _, err := ValidateYubiKey(yubiAuth, testInitialYKOTP); err == nil {\n\t\tt.Fatal(\"auth: expect failure with re-used OTP\")\n\t}\n}", "func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEventWithID(mock.CID, \"foo\", nil)\n\t\ts.GetMsg().AssertTokenEventWithID(mock.CID, \"foo\", nil)\n\t})\n}", "func TestVnicContainer_Invalid(t *testing.T) {\n\tvnic, err := newContainerVnic(\"testcvnic\")\n\n\tif err = vnic.getDevice(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.enable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.disable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.destroy(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n}", "func TestInvalidCollectInterval(t *testing.T) {\n\tensureProcessExit(t, \"TestNoDatadogAPIKey\",\n\t\tfalse, \"invalid duration\",\n\t\t\"C2D_COLLECT_INTERVAL=some_bogus_value\")\n}", "func TestBadToken(t *testing.T) {\n\n\t// Run the command with a bad token value\n\toutput := executeCommand(\"123\")\n\n\t// We should have a subcommand required command and a complete usage dump\n\trequire.NotNil(t, executeError, \"there should have been an error\")\n\trequire.Condition(t, func() bool {\n\t\treturn checkForExpectedSTSCallFailure(executeError)\n\t}, \"Error should have complained about nonexistent credentials file or invalid MFA token length\")\n\n\trequire.Empty(t, output, \"Output for an error condition should have been empty\")\n}", "func TestInvalidToValidSubscription(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tcst, err := createConsensusSetTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cst.Close()\n\n\t// Start by performing a bad subscribe.\n\tms := newMockSubscriber()\n\tbadCCID := modules.ConsensusChangeID{255, 255, 255}\n\terr = cst.cs.ConsensusSetSubscribe(&ms, badCCID, cst.cs.tg.StopChan())\n\tif err != modules.ErrInvalidConsensusChangeID {\n\t\tt.Error(\"consensus set returning the wrong error during an invalid subscription:\", err)\n\t}\n\n\t// Perform a correct subscribe.\n\terr = cst.cs.ConsensusSetSubscribe(&ms, modules.ConsensusChangeBeginning, cst.cs.tg.StopChan())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Mine a block and check that the mock subscriber only got a single\n\t// consensus change.\n\tnumPrevUpdates := len(ms.updates)\n\t_, err = cst.miner.AddBlock()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(ms.updates) != numPrevUpdates+1 {\n\t\tt.Error(\"subscriber received two consensus changes for a single block\")\n\t}\n}", "func TestVnic_Invalid(t *testing.T) {\n\tvnic, err := newVnic(\"testvnic\")\n\n\tif err = vnic.getDevice(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.enable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.disable(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n\tif err = vnic.destroy(); err == nil {\n\t\tt.Errorf(\"Non existent device: %v\", vnic)\n\t}\n\tif !strings.HasPrefix(err.Error(), \"vnic error\") {\n\t\tt.Errorf(\"Invalid error format %v\", err)\n\t}\n\n}", "func TestConnectInvalidAddr(t *testing.T) {\n\t// connect\n\tctx := createContext(t, time.Second*20)\n\n\t_, errConnect := base.NewMilvusClient(ctx, client.Config{Address: \"aa\"})\n\tcommon.CheckErr(t, errConnect, false, \"context deadline exceeded\")\n}", "func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, nil)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t})\n}", "func Test_Middleware_RequestID_Panic(t *testing.T) {\n\tdefer func() {\n\t\tutils.AssertEqual(t,\n\t\t\t\"RequestID: the following option types are allowed: `string`, `func() string`, `func(*fiber.Ctx) bool`, `RequestIDConfig`\",\n\t\t\tfmt.Sprintf(\"%s\", recover()))\n\t}()\n\n\tRequestID(0)\n}", "func contextInvalid(context string) bool {\n\tif context != \".\" && !strings.Contains(context, \"cx-\") {\n\t\tlog.Warn(\"Context is malformed.\", \"context\", context)\n\t\treturn true\n\t}\n\treturn false\n}", "func testBatchCTXInvalidAddenda(t testing.TB) {\n\tmockBatch := NewBatchCTX(mockBatchCTXHeader())\n\tmockBatch.AddEntry(mockCTXEntryDetail())\n\taddenda05 := mockAddenda05()\n\taddenda05.TypeCode = \"63\"\n\tmockBatch.GetEntries()[0].AddAddenda05(addenda05)\n\tmockBatch.Entries[0].AddendaRecordIndicator = 1\n\terr := mockBatch.Create()\n\tif !base.Match(err, ErrAddendaTypeCode) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func TestNewIDAllocatorInvalidArgs(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\targs := [][]uint32{\n\t\t{0, 10}, // minID <= 0\n\t\t{2, 0}, // blockSize < 1\n\t}\n\tfor i := range args {\n\t\tif _, err := newIDAllocator(nil, nil, args[i][0], args[i][1], nil); err == nil {\n\t\t\tt.Errorf(\"expect to have error return, but got nil\")\n\t\t}\n\t}\n}", "func CheckTheValidityOfTheToken(token string) (newToken string, err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n err = createError(011)\n\n if v, ok := tokens[token]; ok {\n var expires = v.(map[string]interface{})[\"expires\"].(time.Time)\n var userID = v.(map[string]interface{})[\"id\"].(string)\n\n if expires.Sub(time.Now().Local()) < 0 {\n return\n }\n\n newToken = setToken(userID, token)\n\n err = nil\n\n } else {\n return\n }\n\n return\n}", "func ErrInvalidVin(codespace sdk.CodespaceType) sdk.Error {\n\treturn sdk.NewError(codespace, InvalidVin, InvalidVinMessage)\n}", "func TestConcurrencyFault(t *testing.T) {\n\tfault := NewConcurrencyFault(\"dummy-key\", 1234)\n\tassert.Equal(t, fault.Error(), \"ConcurrencyFault: dummy-key at 1234\", \"The ConcurrencyFault message should be correct.\")\n\tisConcurrencyFault, _ := IsConcurrencyFault(fault)\n\tassert.True(t, isConcurrencyFault, \"Should be a ConcurrencyFault\")\n\n\tisDomainFault, _ := IsDomainFault(fault)\n\tassert.False(t, isDomainFault, \"Should not be a DomainFault\")\n}", "func TestAuthResource_WithInvalidRID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertPanicNoRecover(t, func() {\n\t\t\t\tr.Resource(\"test..foo\")\n\t\t\t})\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertErrorCode(res.CodeInternalError)\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that Reset sends a system.reset event.
func TestServiceReset(t *testing.T) { tbl := []struct { Resources []string Access []string Expected interface{} }{ {nil, nil, nil}, {[]string{}, nil, nil}, {nil, []string{}, nil}, {[]string{}, []string{}, nil}, {[]string{"test.foo.>"}, nil, json.RawMessage(`{"resources":["test.foo.>"]}`)}, {nil, []string{"test.foo.>"}, json.RawMessage(`{"access":["test.foo.>"]}`)}, {[]string{"test.foo.>"}, []string{"test.bar.>"}, json.RawMessage(`{"resources":["test.foo.>"],"access":["test.bar.>"]}`)}, {[]string{"test.foo.>"}, []string{}, json.RawMessage(`{"resources":["test.foo.>"]}`)}, {[]string{}, []string{"test.foo.>"}, json.RawMessage(`{"access":["test.foo.>"]}`)}, } for _, l := range tbl { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { s.Service().Reset(l.Resources, l.Access) // Send token event to flush any system.reset event s.Service().TokenEvent(mock.CID, nil) if l.Expected != nil { s.GetMsg(). AssertSubject("system.reset"). AssertPayload(l.Expected) } s.GetMsg().AssertTokenEvent(mock.CID, nil) }) } }
[ "func TestReset(t *testing.T) {\n\ttestCancel(t, false)\n}", "func Reset() {\n\tfor {\n\t\t// enable software reset extension\n\t\treg.Set16(imx6.WDOG2_WCR, imx6.WCR_SRE)\n\n\t\t// assert system reset signal\n\t\treg.Clear16(imx6.WDOG2_WCR, imx6.WCR_SRS)\n\t}\n}", "func (s *Driver) reset() error {\n\tif err := s.writeRegister(regShutdown, 0); err != nil {\n\t\treturn err\n\t}\n\ttime.Sleep(time.Millisecond * 10)\n\treturn s.writeRegister(regShutdown, 1)\n}", "func (m *MockMachineErr) Reset() error {\n\treturn m.Start()\n}", "func (m *Machine) Reset() error {\n\tm.State = driver.Running\n\tfmt.Printf(\"Reset %s: %s\\n\", m.Name, m.State)\n\treturn nil\n}", "func MockOnResetSystem(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tsystemID string, requestBody *redfishClient.ResetRequestBody, redfishErr redfishClient.RedfishError,\n\thttpResponse *http.Response, err error) {\n\trequest := redfishClient.ApiResetSystemRequest{}.ResetRequestBody(*requestBody)\n\tmockAPI.On(\"ResetSystem\", ctx, systemID).Return(request).Times(1)\n\tmockAPI.On(\"ResetSystemExecute\", mock.Anything).Return(redfishErr, httpResponse, err).Times(1)\n}", "func TestResetReceive(tester *testing.T) {\n\n\tt := test.New(tester)\n\tcount := 0\n\n\tlistener, err := net.Listen(\"tcp\", \":11111\")\n\tt.AssertNil(err, \"net.Listen\")\n\n\tserver := &http.Server{Handler: websocket.Handler(accept(&count))}\n\tgo server.Serve(listener)\n\n\tsocket := &Socket{\n\t\tHostPort: \"localhost:11111\",\n\t\tPath: \"\",\n\t\tOrigin: fakeOrigin,\n\t}\n\n\trequest := new(Sync)\n\t_, err = socket.Send(request, 5, fakeOrigin)\n\tt.AssertNil(err, \"socket.Send\")\n\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tsocket.Reset(\"localhost:11112\")\n\t}()\n\n\terr = socket.Receive(new(Ack))\n\tt.AssertNotNil(err, \"socket.Receive\")\n\n\tlistener.Close()\n\n}", "func (w *FakeWindowsAPI) ResetEvent() error {\n\tw.eventSignalled = false\n\treturn nil\n}", "func Reset() {\n\tDefaultBus.Reset()\n}", "func (computersystem *ComputerSystem) Reset(resetType ResetType) error {\n\t// Make sure the requested reset type is supported by the system\n\tvalid := false\n\tif len(computersystem.SupportedResetTypes) > 0 {\n\t\tfor _, allowed := range computersystem.SupportedResetTypes {\n\t\t\tif resetType == allowed {\n\t\t\t\tvalid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// No allowed values supplied, assume we are OK\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\treturn fmt.Errorf(\"reset type '%s' is not supported by this service\",\n\t\t\tresetType)\n\t}\n\n\tt := struct {\n\t\tResetType ResetType\n\t}{ResetType: resetType}\n\n\treturn computersystem.Post(computersystem.resetTarget, t)\n}", "func Reset() {\n\treset.Set(true)\n}", "func TestServiceTokenReset(t *testing.T) {\n\ttbl := []struct {\n\t\tSubject string\n\t\tTIDs []string\n\t\tExpected interface{}\n\t}{\n\t\t{\"auth\", nil, nil},\n\t\t{\"auth\", []string{}, nil},\n\t\t{\"auth\", []string{\"foo\"}, json.RawMessage(`{\"tids\":[\"foo\"],\"subject\":\"auth\"}`)},\n\t\t{\"auth\", []string{\"foo\", \"bar\"}, json.RawMessage(`{\"tids\":[\"foo\",\"bar\"],\"subject\":\"auth\"}`)},\n\t\t{\"auth.test.method\", []string{\"foo\", \"bar\"}, json.RawMessage(`{\"tids\":[\"foo\",\"bar\"],\"subject\":\"auth.test.method\"}`)},\n\t}\n\n\tfor _, l := range tbl {\n\t\trunTest(t, func(s *res.Service) {\n\t\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t\t}, func(s *restest.Session) {\n\t\t\ts.Service().TokenReset(l.Subject, l.TIDs...)\n\t\t\t// Send token event to flush any system.tokenReset event\n\t\t\ts.Service().TokenEvent(mock.CID, nil)\n\n\t\t\tif l.Expected != nil {\n\t\t\t\ts.GetMsg().\n\t\t\t\t\tAssertSubject(\"system.tokenReset\").\n\t\t\t\t\tAssertPayload(l.Expected)\n\t\t\t}\n\n\t\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t\t})\n\t}\n}", "func (u *Unit) Reset() {\n\tu.pru.wr(u.ctlBase+c_CONTROL, 0)\n}", "func (event *Event) Reset() error {\n\tif err := ResetEvent(event.handle); err != nil {\n\t\treturn NewWindowsError(\"ResetEvent\", err)\n\t}\n\treturn nil\n}", "func (v *VsctlMock) Reset() {\n\tv.ReceivedArgs = [][]string{}\n}", "func (s *Server) OnReset() error { return nil }", "func RunTestReset(t *testing.T, e1, e2 streams.StreamProvider) {\n\tserver := func(provider streams.StreamProvider) error {\n\t\tlistener := provider.Listen(nil)\n\t\tfor {\n\t\t\tstream, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err := stream.Reset(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Fails due to spdystream bug\n\t\t\t// https://github.com/docker/spdystream/issues/45\n\t\t\tif _, err := stream.Write([]byte(\"some value\")); err == nil {\n\t\t\t\treturn fmt.Errorf(\"Expected error writing after reset\")\n\t\t\t}\n\t\t}\n\t}\n\tclient := func(provider streams.StreamProvider) error {\n\t\tstream, err := provider.NewStream(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb := make([]byte, 10)\n\t\tif n, err := stream.Read(b); err != nil && err != io.EOF {\n\t\t\treturn err\n\t\t} else if err == nil && n > 0 {\n\t\t\treturn fmt.Errorf(\"Expected read of %d bytes\", n)\n\t\t} else if err == nil {\n\t\t\treturn fmt.Errorf(\"Expected error reading from stream\")\n\t\t}\n\t\treturn nil\n\t}\n\trunTest(t, e1, e2, client, server)\n}", "func (d *Dev) Reset() error {\n\t// issue soft reset to initialize device\n\tif err := d.dev.WriteUint8(regSoftReset, softResetValue); err != nil {\n\t\treturn err\n\t}\n\n\t// wait for restart\n\ttime.Sleep(10 * time.Millisecond)\n\n\treturn nil\n}", "func (sm *StateMachine) Reset(in *Msg) {\n\tsm.state = 0\n\tsm.stateEntered = false\n\tsm.plugin.SetMemory(in, StateKey, 0)\n\tsm.plugin.SetMemory(in, stateEnteredKey, false)\n\tsm.resetFn(in)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that TokenReset sends a system.tokenReset event.
func TestServiceTokenReset(t *testing.T) { tbl := []struct { Subject string TIDs []string Expected interface{} }{ {"auth", nil, nil}, {"auth", []string{}, nil}, {"auth", []string{"foo"}, json.RawMessage(`{"tids":["foo"],"subject":"auth"}`)}, {"auth", []string{"foo", "bar"}, json.RawMessage(`{"tids":["foo","bar"],"subject":"auth"}`)}, {"auth.test.method", []string{"foo", "bar"}, json.RawMessage(`{"tids":["foo","bar"],"subject":"auth.test.method"}`)}, } for _, l := range tbl { runTest(t, func(s *res.Service) { s.Handle("model", res.GetResource(func(r res.GetRequest) { r.NotFound() })) }, func(s *restest.Session) { s.Service().TokenReset(l.Subject, l.TIDs...) // Send token event to flush any system.tokenReset event s.Service().TokenEvent(mock.CID, nil) if l.Expected != nil { s.GetMsg(). AssertSubject("system.tokenReset"). AssertPayload(l.Expected) } s.GetMsg().AssertTokenEvent(mock.CID, nil) }) } }
[ "func TestServiceReset(t *testing.T) {\n\ttbl := []struct {\n\t\tResources []string\n\t\tAccess []string\n\t\tExpected interface{}\n\t}{\n\t\t{nil, nil, nil},\n\t\t{[]string{}, nil, nil},\n\t\t{nil, []string{}, nil},\n\t\t{[]string{}, []string{}, nil},\n\n\t\t{[]string{\"test.foo.>\"}, nil, json.RawMessage(`{\"resources\":[\"test.foo.>\"]}`)},\n\t\t{nil, []string{\"test.foo.>\"}, json.RawMessage(`{\"access\":[\"test.foo.>\"]}`)},\n\t\t{[]string{\"test.foo.>\"}, []string{\"test.bar.>\"}, json.RawMessage(`{\"resources\":[\"test.foo.>\"],\"access\":[\"test.bar.>\"]}`)},\n\n\t\t{[]string{\"test.foo.>\"}, []string{}, json.RawMessage(`{\"resources\":[\"test.foo.>\"]}`)},\n\t\t{[]string{}, []string{\"test.foo.>\"}, json.RawMessage(`{\"access\":[\"test.foo.>\"]}`)},\n\t}\n\n\tfor _, l := range tbl {\n\t\trunTest(t, func(s *res.Service) {\n\t\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t\t}, func(s *restest.Session) {\n\t\t\ts.Service().Reset(l.Resources, l.Access)\n\t\t\t// Send token event to flush any system.reset event\n\t\t\ts.Service().TokenEvent(mock.CID, nil)\n\n\t\t\tif l.Expected != nil {\n\t\t\t\ts.GetMsg().\n\t\t\t\t\tAssertSubject(\"system.reset\").\n\t\t\t\t\tAssertPayload(l.Expected)\n\t\t\t}\n\n\t\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t\t})\n\t}\n}", "func TestAuthRequestTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(mock.Token)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, mock.Token)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func TestReset(t *testing.T) {\n\ttestCancel(t, false)\n}", "func TestServiceTokenEvent_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, nil)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, nil)\n\t})\n}", "func TestVerifyResetExpired(t *testing.T) {\n\tlog.UseTestLogger(t)\n\tdb := test.Setup(\"TestVerifyResetExpired\", t)\n\n\tu := &sdk.User{\n\t\tUsername: \"foo\",\n\t\tEmail: \"foo.bar@ovh.com\",\n\t\tFullname: \"foo bar\",\n\t}\n\n\ttoken, hashedToken, err := user.GeneratePassword()\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot create token: %s\", err)\n\t}\n\n\ta := &sdk.Auth{\n\t\tHashedTokenVerify: hashedToken,\n\t\tDateReset: 1,\n\t\tEmailVerified: true,\n\t}\n\n\terr = user.InsertUser(db, u, a)\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot insert user: %s\", err)\n\t}\n\n\tu2, err := user.LoadUserAndAuth(db, \"foo\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot load %s: %s\\n\", \"foo\", err)\n\t}\n\n\t_, _, err = user.Verify(u2, token)\n\tif err == nil {\n\t\tt.Fatalf(\"User shoud not be verified : %s\", err)\n\t}\n\tif err.Error() != \"Reset operation expired\" {\n\t\tt.Fatalf(\"Reset sould be expired\")\n\t}\n}", "func (m *MockSessionRunner) RetireResetToken(arg0 [16]byte) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"RetireResetToken\", arg0)\n}", "func MockOnResetSystem(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tsystemID string, requestBody *redfishClient.ResetRequestBody, redfishErr redfishClient.RedfishError,\n\thttpResponse *http.Response, err error) {\n\trequest := redfishClient.ApiResetSystemRequest{}.ResetRequestBody(*requestBody)\n\tmockAPI.On(\"ResetSystem\", ctx, systemID).Return(request).Times(1)\n\tmockAPI.On(\"ResetSystemExecute\", mock.Anything).Return(redfishErr, httpResponse, err).Times(1)\n}", "func TestServiceTokenEvent_WithObjectToken_SendsToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEvent(mock.CID, mock.Token)\n\t\ts.GetMsg().AssertTokenEvent(mock.CID, mock.Token)\n\t})\n}", "func TestResetReceive(tester *testing.T) {\n\n\tt := test.New(tester)\n\tcount := 0\n\n\tlistener, err := net.Listen(\"tcp\", \":11111\")\n\tt.AssertNil(err, \"net.Listen\")\n\n\tserver := &http.Server{Handler: websocket.Handler(accept(&count))}\n\tgo server.Serve(listener)\n\n\tsocket := &Socket{\n\t\tHostPort: \"localhost:11111\",\n\t\tPath: \"\",\n\t\tOrigin: fakeOrigin,\n\t}\n\n\trequest := new(Sync)\n\t_, err = socket.Send(request, 5, fakeOrigin)\n\tt.AssertNil(err, \"socket.Send\")\n\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tsocket.Reset(\"localhost:11112\")\n\t}()\n\n\terr = socket.Receive(new(Ack))\n\tt.AssertNotNil(err, \"socket.Receive\")\n\n\tlistener.Close()\n\n}", "func TestVerifyToken(t *testing.T) {\n t.Errorf(\"No tests written yet for VerifyToken()\")\n}", "func (w *FakeWindowsAPI) ResetEvent() error {\n\tw.eventSignalled = false\n\treturn nil\n}", "func TestServiceTokenEventWithID_WithNilToken_SendsNilToken(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.GetResource(func(r res.GetRequest) { r.NotFound() }))\n\t}, func(s *restest.Session) {\n\t\ts.Service().TokenEventWithID(mock.CID, \"foo\", nil)\n\t\ts.GetMsg().AssertTokenEventWithID(mock.CID, \"foo\", nil)\n\t})\n}", "func (m *MockSessionRunner) RemoveResetToken(arg0 [16]byte) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"RemoveResetToken\", arg0)\n}", "func TestRefreshToken(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tvar url string = \"/v1/refresh/token\"\n\tvar bearer = \"Bearer \" + user.Token\n\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"POST\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar refresh models.UserConnect\n\terr := json.Unmarshal([]byte(record.Body.String()), &refresh)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 200)\n\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func (r *RedisDL) resetToken() {\n\tr.currentToken = \"\"\n}", "func (m *MockSessionRunner) AddResetToken(arg0 [16]byte, arg1 packetHandler) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AddResetToken\", arg0, arg1)\n}", "func (s *Service) TestToken(ctx context.Context, info *pushmdl.PushInfo, token string) (err error) {\n\tparams := url.Values{}\n\tparams.Add(\"app_id\", strconv.FormatInt(info.APPID, 10))\n\tparams.Add(\"alert_title\", info.Title)\n\tparams.Add(\"alert_body\", info.Summary)\n\tparams.Add(\"token\", token)\n\tparams.Add(\"link_type\", strconv.FormatInt(int64(info.LinkType), 10))\n\tparams.Add(\"link_value\", info.LinkValue)\n\tparams.Add(\"sound\", strconv.Itoa(info.Sound))\n\tparams.Add(\"vibration\", strconv.Itoa(info.Vibration))\n\tparams.Add(\"expire_time\", strconv.FormatInt(int64(info.ExpireTime), 10))\n\tparams.Add(\"image_url\", info.ImageURL)\n\tif err = s.httpClient.Post(ctx, _testTokenURL, \"\", params, nil); err != nil {\n\t\tlog.Error(\"s.TestToken(%+v) error(%v)\", info, err)\n\t}\n\treturn\n}", "func TestTokenRefreshLimit(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tos.Setenv(\"TOKEN_LIMIT_HOURS\", \"0\")\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\ttime.Sleep(1 * time.Second)\n\n\tvar url string = \"/v1/refresh/token\"\n\tvar bearer = \"Bearer \" + user.Token\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"POST\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 401)\n\tassert.Equal(t, message.Message, \"Token has expired and cannot be refreshed, please reconnect\")\n\n\tos.Setenv(\"TOKEN_LIMIT_HOURS\", \"24\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func (s *Server) OnReset() error { return nil }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsAMPCustomElement returns true if the node is an AMP custom element.
func IsAMPCustomElement(n *html.Node) bool { return n.Type == html.ElementNode && strings.HasPrefix(n.Data, "amp-") }
[ "func (decl SomeDecl) IsCustom() bool {\n\t_, is := decl.Properties.(CustomProperties)\n\treturn is\n}", "func IsScriptAMPExtension(n *html.Node) bool {\n\t_, ok := AMPExtensionName(n)\n\treturn ok\n}", "func (t *Type) IsCustom() bool {\n\treturn !t.IsPrimitive() && !t.IsContainer()\n}", "func (ds *DialSettings) HasCustomAudience() bool {\n\treturn len(ds.Audiences) > 0\n}", "func IsScriptAMPRuntime(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", \"src\"); ok {\n\t\treturn htmlnode.HasAttribute(n, \"\", \"async\") &&\n\t\t\t!IsScriptAMPExtension(n) &&\n\t\t\tstrings.HasPrefix(v, AMPCacheRootURL) &&\n\t\t\t(strings.HasSuffix(v, \"/v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/v0.mjs\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.mjs\"))\n\t}\n\treturn false\n}", "func IsScriptAMPViewer(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\ta, ok := htmlnode.FindAttribute(n, \"\", \"src\")\n\treturn ok &&\n\t\t!IsScriptAMPExtension(n) &&\n\t\tstrings.HasPrefix(a.Val,\n\t\t\tAMPCacheSchemeAndHost+\"/v0/amp-viewer-integration-\") &&\n\t\tstrings.HasSuffix(a.Val, \".js\") &&\n\t\thtmlnode.HasAttribute(n, \"\", \"async\")\n}", "func (c *FieldBuildContext) IsCustomType() bool {\n\treturn c.f.IsCustomType()\n}", "func AMPExtensionName(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tfor _, attr := range n.Attr {\n\t\tfor _, k := range []string{AMPCustomElement, AMPCustomTemplate, AMPHostService} {\n\t\t\tif attr.Key == k {\n\t\t\t\treturn attr.Val, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}", "func (a Atom) IsEmbedded() bool {\n\treturn (uint32(a) & embeddedTag) != 0\n}", "func (o *FabricPortModeAllOf) HasCustomMode() bool {\n\tif o != nil && o.CustomMode != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p Protocol) IsCustomProtocol() bool {\n\treturn p != ProtocolICMPv4 && p != ProtocolTCP && p != ProtocolUDP && p != ProtocolICMPv6\n}", "func (ts TaskSpec) HasLaunchPolicyCustom() bool {\n\tif ts.LaunchPolicy == \"\" {\n\t\treturn len(ts.Inputs) == 0\n\t}\n\treturn ts.LaunchPolicy == LaunchPolicyCustom\n}", "func (o *WorkflowCustomDataProperty) HasCustomDataTypeName() bool {\n\tif o != nil && o.CustomDataTypeName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isEmbed(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"embed\"\n}", "func (o *DataExportQuery) HasCustomBitlink() bool {\n\tif o != nil && o.CustomBitlink != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isAtom(node *html.Node, atoms ...atom.Atom) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\tfor _, atom := range atoms {\n\t\tif atom == node.DataAtom {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (tm *CustagMan) GetCustomTag(elem jq.JQuery) (ct bind.CustomTag, ok bool) {\n\tct, ok = tm.custags[strings.ToUpper(elem.Prop(\"tagName\").(string))]\n\treturn\n}", "func (i *InternalLinkTypeStickerSet) GetExpectCustomEmoji() (value bool) {\n\tif i == nil {\n\t\treturn\n\t}\n\treturn i.ExpectCustomEmoji\n}", "func (o *Campaign) HasCustomEffectCount() bool {\n\tif o != nil && o.CustomEffectCount != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AMPExtensionScriptDefinition returns a unique script definition that takes into account the extension name, version and if it is module/nomodule. Example (ampad): ampad0.1.js (regular/nomodule), ampad0.1.mjs (module). The AMP Validator prevents a mix of regular and nomodule extensions. If the pattern is not found then uses value of "src" attribute. Returns ok=false if this isn't an extension.
func AMPExtensionScriptDefinition(n *html.Node) (string, bool) { if n.DataAtom != atom.Script { return "", false } src, hasSrc := htmlnode.GetAttributeVal(n, "", "src") if hasSrc { m := srcURLRE.FindStringSubmatch(src) if len(m) < 2 { return src, true } return m[1], true } return "", false }
[ "func IsScriptAMPExtension(n *html.Node) bool {\n\t_, ok := AMPExtensionName(n)\n\treturn ok\n}", "func AMPExtensionName(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tfor _, attr := range n.Attr {\n\t\tfor _, k := range []string{AMPCustomElement, AMPCustomTemplate, AMPHostService} {\n\t\t\tif attr.Key == k {\n\t\t\t\treturn attr.Val, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}", "func IsScriptAMPRuntime(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", \"src\"); ok {\n\t\treturn htmlnode.HasAttribute(n, \"\", \"async\") &&\n\t\t\t!IsScriptAMPExtension(n) &&\n\t\t\tstrings.HasPrefix(v, AMPCacheRootURL) &&\n\t\t\t(strings.HasSuffix(v, \"/v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/v0.mjs\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.mjs\"))\n\t}\n\treturn false\n}", "func IsExtension(buf []byte, ext string) bool {\n\treturn Is(buf, ext)\n}", "func (*Matcher) IsSupportedManifestFormat(filename string) bool {\n\tlog.Debug().Msgf(\"Executing: IsSupportedManifestFormat\")\n\tbasename := filepath.Base(filename)\n\tmatch, _ := regexp.MatchString(\"pom.xml$\", basename)\n\tlog.Debug().Bool(\"regex\", match).Str(\"path\", filename).Msg(\"IsSupportedManifest\")\n\treturn match\n}", "func isValidExtension(ext string, extensions []string) bool {\n\tfor _, ex := range extensions {\n\t\tif ex == ext {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func MatchExt(ext ...string) MatchFn {\n\treturn func(name string) bool {\n\t\tfor _, e := range ext {\n\t\t\tif strings.HasSuffix(name, e) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}", "func extensionPattern(pattern *regexp.Regexp) *regexp.Regexp {\n\treturn suffixPattern(regexp.MustCompile(\"(^|/)[^/]+.\" + pattern.String()))\n}", "func registerScript(n *html.Node, hn *headNodes) {\n\tif amphtml.IsScriptAMPRuntime(n) {\n\t\thn.scriptAMPRuntime = append(hn.scriptAMPRuntime, n)\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPViewer(n) {\n\t\thn.scriptAMPViewer = n\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPExtension(n) {\n\t\tif amphtml.IsScriptRenderDelaying(n) {\n\t\t\thn.scriptRenderDelaying = append(hn.scriptRenderDelaying, n)\n\t\t\treturn\n\t\t}\n\t\thn.scriptNonRenderDelaying = append(hn.scriptNonRenderDelaying, n)\n\t\treturn\n\t}\n\thn.other = append(hn.other, n)\n}", "func validateExtension(ext string) bool {\n\treturn cmn.StringInSlice(ext, supportedExtensions)\n}", "func (g *Greeting) SupportsExtension(uri string) bool {\n\tif g == nil {\n\t\treturn false\n\t}\n\tfor _, v := range g.Extensions {\n\t\tif v == uri {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsScriptAMPViewer(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\ta, ok := htmlnode.FindAttribute(n, \"\", \"src\")\n\treturn ok &&\n\t\t!IsScriptAMPExtension(n) &&\n\t\tstrings.HasPrefix(a.Val,\n\t\t\tAMPCacheSchemeAndHost+\"/v0/amp-viewer-integration-\") &&\n\t\tstrings.HasSuffix(a.Val, \".js\") &&\n\t\thtmlnode.HasAttribute(n, \"\", \"async\")\n}", "func (e *Extension) isExtensionRegistered(fusemlURL string) (bool, error) {\n\n\tfullURL := fmt.Sprintf(\"%s/extensions/%s\", fusemlURL, e.Desc.Name)\n\tresp, err := http.Get(fullURL)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == 200 {\n\t\treturn true, nil\n\t} else if resp.StatusCode == 404 {\n\t\treturn false, nil\n\t}\n\treturn false, errors.New(fmt.Sprintf(\"Unexpected response from registry: %d\", resp.StatusCode))\n}", "func (lm LinksManager) AutoAssignExtension(url *url.URL, t resource.Type) bool {\n\treturn true\n}", "func (*ElementDefinitionRegex) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_extensions_proto_rawDescGZIP(), []int{338}\n}", "func allowedExtension(ext string) bool {\n\tallowed := []string{\"jpg\", \"jpeg\", \"png\", \"gif\", \"webm\", \"mp4\", \"mov\", \"zip\", \"tar\", \"tar.gz\", \"tar.bz2\"}\n\n\tfor _, e := range allowed {\n\t\tif ext == e {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func IsManifest(filename string) (bool, error) {\n\tmatched, err := filepath.Match(machineConfigFileNamePattern, filename)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn matched, nil\n}", "func (m *Media) IsValid() bool {\n if ext := filepath.Ext(m.FullPath); len(ext) > 0 {\n for _, pattern := range extpatterns {\n match, err := filepath.Match(\".\"+pattern, ext)\n if err != nil {\n fmt.Println(\"malfoemd pattern?\")\n return false\n }\n if match {\n return true\n }\n }\n }\n\n return false\n}", "func MatchExt(exts ...string) MatcherFunc { return MatchExts(exts) }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AMPExtensionName returns the name of the extension this node represents. For most extensions this is the value of the "customelement" attribute. Returns ok=false if this isn't an extension.
func AMPExtensionName(n *html.Node) (string, bool) { if n.DataAtom != atom.Script { return "", false } for _, attr := range n.Attr { for _, k := range []string{AMPCustomElement, AMPCustomTemplate, AMPHostService} { if attr.Key == k { return attr.Val, true } } } return "", false }
[ "func IsScriptAMPExtension(n *html.Node) bool {\n\t_, ok := AMPExtensionName(n)\n\treturn ok\n}", "func (me TxsdImpactSimpleContentExtensionType) IsExtValue() bool { return me.String() == \"ext-value\" }", "func (me TxsdCounterSimpleContentExtensionType) IsExtValue() bool { return me.String() == \"ext-value\" }", "func IsExtension(buf []byte, ext string) bool {\n\treturn Is(buf, ext)\n}", "func IsAMPCustomElement(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && strings.HasPrefix(n.Data, \"amp-\")\n}", "func (me TactionType) IsExtValue() bool { return me.String() == \"ext-value\" }", "func (this *RTPPacket) HasExtension() bool {\n\treturn this.header.extension != 0\n}", "func (*visibilityExtension) Name() string {\n\treturn _extName\n}", "func (o *WhatsAppNameWhatsAppApiContent) GetNameSuffixOk() (*string, bool) {\n\tif o == nil || o.NameSuffix == nil {\n\t\treturn nil, false\n\t}\n\treturn o.NameSuffix, true\n}", "func (m middleware) ExtensionName() string {\n\treturn \"OperationsExtension\"\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsName() bool { return me.String() == \"name\" }", "func (me TxsdContactType) IsExtValue() bool { return me.String() == \"ext-value\" }", "func (fr *fakeResponse) Extension(name graphsync.ExtensionName) (datamodel.Node, bool) {\n\tdata, has := fr.extensions[name]\n\treturn data, has\n}", "func (o *ConditionFileExtensionCondition) GetFileExtensionOk() (*string, bool) {\n\tif o == nil || o.FileExtension == nil {\n\t\treturn nil, false\n\t}\n\treturn o.FileExtension, true\n}", "func (me TxsdTimeImpactSimpleContentExtensionMetric) IsExtValue() bool {\n\treturn me.String() == \"ext-value\"\n}", "func (c *Client) Extension(ext string) (bool, string) {\n\tif err := c.hello(); err != nil {\n\t\treturn false, \"\"\n\t}\n\tif c.ext == nil {\n\t\treturn false, \"\"\n\t}\n\text = strings.ToUpper(ext)\n\tparam, ok := c.ext[ext]\n\treturn ok, param\n}", "func (me TdurationType) IsExtValue() bool { return me.String() == \"ext-value\" }", "func (me TxsdContactRole) IsExtValue() bool { return me.String() == \"ext-value\" }", "func (me TxsdSystemCategory) IsExtValue() bool { return me.String() == \"ext-value\" }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsScriptAMPExtension returns true if the node is a script tag representing an extension.
func IsScriptAMPExtension(n *html.Node) bool { _, ok := AMPExtensionName(n) return ok }
[ "func IsScriptAMPRuntime(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", \"src\"); ok {\n\t\treturn htmlnode.HasAttribute(n, \"\", \"async\") &&\n\t\t\t!IsScriptAMPExtension(n) &&\n\t\t\tstrings.HasPrefix(v, AMPCacheRootURL) &&\n\t\t\t(strings.HasSuffix(v, \"/v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/v0.mjs\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.mjs\"))\n\t}\n\treturn false\n}", "func IsScriptAMPViewer(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\ta, ok := htmlnode.FindAttribute(n, \"\", \"src\")\n\treturn ok &&\n\t\t!IsScriptAMPExtension(n) &&\n\t\tstrings.HasPrefix(a.Val,\n\t\t\tAMPCacheSchemeAndHost+\"/v0/amp-viewer-integration-\") &&\n\t\tstrings.HasSuffix(a.Val, \".js\") &&\n\t\thtmlnode.HasAttribute(n, \"\", \"async\")\n}", "func AMPExtensionName(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tfor _, attr := range n.Attr {\n\t\tfor _, k := range []string{AMPCustomElement, AMPCustomTemplate, AMPHostService} {\n\t\t\tif attr.Key == k {\n\t\t\t\treturn attr.Val, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}", "func AMPExtensionScriptDefinition(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tsrc, hasSrc := htmlnode.GetAttributeVal(n, \"\", \"src\")\n\tif hasSrc {\n\t\tm := srcURLRE.FindStringSubmatch(src)\n\t\tif len(m) < 2 {\n\t\t\treturn src, true\n\t\t}\n\t\treturn m[1], true\n\t}\n\treturn \"\", false\n}", "func isScript(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"script\"\n}", "func IsExtension(buf []byte, ext string) bool {\n\treturn Is(buf, ext)\n}", "func IsAMPCustomElement(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && strings.HasPrefix(n.Data, \"amp-\")\n}", "func IsScriptRenderDelaying(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif IsScriptAMPViewer(n) {\n\t\treturn true\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", AMPCustomElement); ok {\n\t\t// TODO(b/77581738): Remove amp-story from this list.\n\t\treturn (v == AMPDynamicCSSClasses ||\n\t\t\tv == AMPExperiment ||\n\t\t\tv == AMPStory)\n\t}\n\treturn false\n}", "func Bpf_program__is_extension(prog *Struct_bpf_program) bool {\n\treturn C.bpf_program__is_extension()\n}", "func (this *RTPPacket) HasExtension() bool {\n\treturn this.header.extension != 0\n}", "func (me TxsdAddressSimpleContentExtensionCategory) IsAsn() bool { return me.String() == \"asn\" }", "func isEmbed(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"embed\"\n}", "func (p *CertProfile) IsAllowedExtention(oid csr.OID) bool {\n\tfor _, allowed := range p.AllowedExtensions {\n\t\tif allowed.Equal(oid) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsExtFunction(functionName string) bool {\n\t_, ok := XFunctions[functionName]\n\treturn ok\n}", "func (me TxsdImpactSimpleContentExtensionType) IsPolicy() bool { return me.String() == \"policy\" }", "func (me TxsdCounterSimpleContentExtensionType) IsEvent() bool { return me.String() == \"event\" }", "func isApplet(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"applet\"\n}", "func (me TxsdImpactSimpleContentExtensionType) IsExtortion() bool { return me.String() == \"extortion\" }", "func IsClaimSupportScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opSupportClaim\n\t}\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsScriptAMPRuntime returns true if the node is of the form <script async src=
func IsScriptAMPRuntime(n *html.Node) bool { if n.DataAtom != atom.Script { return false } if v, ok := htmlnode.GetAttributeVal(n, "", "src"); ok { return htmlnode.HasAttribute(n, "", "async") && !IsScriptAMPExtension(n) && strings.HasPrefix(v, AMPCacheRootURL) && (strings.HasSuffix(v, "/v0.js") || strings.HasSuffix(v, "/v0.mjs") || strings.HasSuffix(v, "/amp4ads-v0.js") || strings.HasSuffix(v, "/amp4ads-v0.mjs")) } return false }
[ "func IsScriptAMPViewer(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\ta, ok := htmlnode.FindAttribute(n, \"\", \"src\")\n\treturn ok &&\n\t\t!IsScriptAMPExtension(n) &&\n\t\tstrings.HasPrefix(a.Val,\n\t\t\tAMPCacheSchemeAndHost+\"/v0/amp-viewer-integration-\") &&\n\t\tstrings.HasSuffix(a.Val, \".js\") &&\n\t\thtmlnode.HasAttribute(n, \"\", \"async\")\n}", "func IsScriptAMPExtension(n *html.Node) bool {\n\t_, ok := AMPExtensionName(n)\n\treturn ok\n}", "func IsScriptRenderDelaying(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif IsScriptAMPViewer(n) {\n\t\treturn true\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", AMPCustomElement); ok {\n\t\t// TODO(b/77581738): Remove amp-story from this list.\n\t\treturn (v == AMPDynamicCSSClasses ||\n\t\t\tv == AMPExperiment ||\n\t\t\tv == AMPStory)\n\t}\n\treturn false\n}", "func isScript(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"script\"\n}", "func AMPExtensionScriptDefinition(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tsrc, hasSrc := htmlnode.GetAttributeVal(n, \"\", \"src\")\n\tif hasSrc {\n\t\tm := srcURLRE.FindStringSubmatch(src)\n\t\tif len(m) < 2 {\n\t\t\treturn src, true\n\t\t}\n\t\treturn m[1], true\n\t}\n\treturn \"\", false\n}", "func registerScript(n *html.Node, hn *headNodes) {\n\tif amphtml.IsScriptAMPRuntime(n) {\n\t\thn.scriptAMPRuntime = append(hn.scriptAMPRuntime, n)\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPViewer(n) {\n\t\thn.scriptAMPViewer = n\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPExtension(n) {\n\t\tif amphtml.IsScriptRenderDelaying(n) {\n\t\t\thn.scriptRenderDelaying = append(hn.scriptRenderDelaying, n)\n\t\t\treturn\n\t\t}\n\t\thn.scriptNonRenderDelaying = append(hn.scriptNonRenderDelaying, n)\n\t\treturn\n\t}\n\thn.other = append(hn.other, n)\n}", "func IsClaimSupportScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opSupportClaim\n\t}\n\treturn false\n}", "func IsClaimUpdateScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opUpdateClaim\n\t}\n\treturn false\n}", "func (me TxsdPresentationAttributesTextContentElementsDominantBaseline) IsAutosenseScript() bool {\n\treturn me.String() == \"autosense-script\"\n}", "func IsClaimScript(script []byte) bool {\n\treturn script[0] == opSupportClaim ||\n\t\tscript[0] == opClaimName ||\n\t\tscript[0] == opUpdateClaim\n}", "func IsAMPCustomElement(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && strings.HasPrefix(n.Data, \"amp-\")\n}", "func (m *Basic) IframeScript() []byte {\n\tdata, err := Asset(\"script.js\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn data\n}", "func TestIsPushOnlyScript(t *testing.T) {\n\tt.Parallel()\n\n\ttest := struct {\n\t\tname string\n\t\tscript []byte\n\t\texpected bool\n\t}{\n\t\tname: \"does not parse\",\n\t\tscript: mustParseShortForm(\"0x046708afdb0fe5548271967f1a67130\" +\n\t\t\t\"b7105cd6a828e03909a67962e0ea1f61d\"),\n\t\texpected: false,\n\t}\n\n\tif IsPushOnlyScript(test.script) != test.expected {\n\t\tt.Errorf(\"IsPushOnlyScript (%s) wrong result\\ngot: %v\\nwant: \"+\n\t\t\t\"%v\", test.name, true, test.expected)\n\t}\n}", "func (p *Probe) IsRuntimeCompiled() bool {\n\treturn p.runtimeCompiled\n}", "func isApplet(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"applet\"\n}", "func (s *Script) Equals(b *Script) bool {\r\n\treturn bytes.Equal(*s, *b)\r\n}", "func isEmbed(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"embed\"\n}", "func IsClaimNameScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opClaimName\n\t}\n\tlog.Error(\"script is nil or length 0!\")\n\treturn false\n}", "func IsCompletionScript(args []string) bool {\n\tvar found bool\n\tfor _, arg := range args {\n\t\tif completionScriptRegExp.MatchString(arg) {\n\t\t\tfound = true\n\t\t}\n\t}\n\treturn found\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsScriptAMPViewer returns true if the node is of the form <script async src=
func IsScriptAMPViewer(n *html.Node) bool { if n.DataAtom != atom.Script { return false } a, ok := htmlnode.FindAttribute(n, "", "src") return ok && !IsScriptAMPExtension(n) && strings.HasPrefix(a.Val, AMPCacheSchemeAndHost+"/v0/amp-viewer-integration-") && strings.HasSuffix(a.Val, ".js") && htmlnode.HasAttribute(n, "", "async") }
[ "func IsScriptAMPRuntime(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", \"src\"); ok {\n\t\treturn htmlnode.HasAttribute(n, \"\", \"async\") &&\n\t\t\t!IsScriptAMPExtension(n) &&\n\t\t\tstrings.HasPrefix(v, AMPCacheRootURL) &&\n\t\t\t(strings.HasSuffix(v, \"/v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/v0.mjs\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.mjs\"))\n\t}\n\treturn false\n}", "func IsScriptAMPExtension(n *html.Node) bool {\n\t_, ok := AMPExtensionName(n)\n\treturn ok\n}", "func IsScriptRenderDelaying(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif IsScriptAMPViewer(n) {\n\t\treturn true\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", AMPCustomElement); ok {\n\t\t// TODO(b/77581738): Remove amp-story from this list.\n\t\treturn (v == AMPDynamicCSSClasses ||\n\t\t\tv == AMPExperiment ||\n\t\t\tv == AMPStory)\n\t}\n\treturn false\n}", "func AMPExtensionScriptDefinition(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tsrc, hasSrc := htmlnode.GetAttributeVal(n, \"\", \"src\")\n\tif hasSrc {\n\t\tm := srcURLRE.FindStringSubmatch(src)\n\t\tif len(m) < 2 {\n\t\t\treturn src, true\n\t\t}\n\t\treturn m[1], true\n\t}\n\treturn \"\", false\n}", "func isScript(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"script\"\n}", "func (me TxsdPresentationAttributesTextContentElementsDominantBaseline) IsAutosenseScript() bool {\n\treturn me.String() == \"autosense-script\"\n}", "func isEmbed(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"embed\"\n}", "func IsAMPCustomElement(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && strings.HasPrefix(n.Data, \"amp-\")\n}", "func isApplet(n *html.Node) bool {\n\treturn n.Type == html.ElementNode && n.Data == \"applet\"\n}", "func IsClaimUpdateScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opUpdateClaim\n\t}\n\treturn false\n}", "func registerScript(n *html.Node, hn *headNodes) {\n\tif amphtml.IsScriptAMPRuntime(n) {\n\t\thn.scriptAMPRuntime = append(hn.scriptAMPRuntime, n)\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPViewer(n) {\n\t\thn.scriptAMPViewer = n\n\t\treturn\n\t}\n\tif amphtml.IsScriptAMPExtension(n) {\n\t\tif amphtml.IsScriptRenderDelaying(n) {\n\t\t\thn.scriptRenderDelaying = append(hn.scriptRenderDelaying, n)\n\t\t\treturn\n\t\t}\n\t\thn.scriptNonRenderDelaying = append(hn.scriptNonRenderDelaying, n)\n\t\treturn\n\t}\n\thn.other = append(hn.other, n)\n}", "func IsClaimSupportScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opSupportClaim\n\t}\n\treturn false\n}", "func (m *Basic) IframeScript() []byte {\n\tdata, err := Asset(\"script.js\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn data\n}", "func IsClaimScript(script []byte) bool {\n\treturn script[0] == opSupportClaim ||\n\t\tscript[0] == opClaimName ||\n\t\tscript[0] == opUpdateClaim\n}", "func AMPExtensionName(n *html.Node) (string, bool) {\n\tif n.DataAtom != atom.Script {\n\t\treturn \"\", false\n\t}\n\tfor _, attr := range n.Attr {\n\t\tfor _, k := range []string{AMPCustomElement, AMPCustomTemplate, AMPHostService} {\n\t\t\tif attr.Key == k {\n\t\t\t\treturn attr.Val, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}", "func streamcode_bodyscripts(qw422016 *qt422016.Writer, lang string) {\n//line template/code.qtpl:16\n\tqw422016.N().S(`\n `)\n//line template/code.qtpl:17\n\tqw422016.N().S(`<script src='`)\n//line template/code.qtpl:18\n\tqw422016.E().S(prefix)\n//line template/code.qtpl:18\n\tqw422016.N().S(`/prism.js'></script>`)\n//line template/code.qtpl:19\n\tif lang != \"\" && lang != \"none\" {\n//line template/code.qtpl:19\n\t\tqw422016.N().S(`<script src='`)\n//line template/code.qtpl:20\n\t\tqw422016.E().S(prefix)\n//line template/code.qtpl:20\n\t\tqw422016.N().S(`/components/prism-`)\n//line template/code.qtpl:20\n\t\tqw422016.E().S(lang)\n//line template/code.qtpl:20\n\t\tqw422016.N().S(`.js'></script>`)\n//line template/code.qtpl:21\n\t}\n//line template/code.qtpl:22\n\tqw422016.N().S(`\n`)\n//line template/code.qtpl:23\n}", "func IsClaimNameScript(script []byte) bool {\n\tif len(script) > 0 {\n\t\treturn script[0] == opClaimName\n\t}\n\tlog.Error(\"script is nil or length 0!\")\n\treturn false\n}", "func streamcode_scripts(qw422016 *qt422016.Writer, lang string) {\n//line template/code.qtpl:11\n\tqw422016.N().S(`\n <link rel='stylesheet' crossorigin='anonymous' href='`)\n//line template/code.qtpl:12\n\tqw422016.E().S(prefix)\n//line template/code.qtpl:12\n\tqw422016.N().S(`/themes/prism.css' />\n`)\n//line template/code.qtpl:13\n}", "func IsCompletionScript(args []string) bool {\n\tvar found bool\n\tfor _, arg := range args {\n\t\tif completionScriptRegExp.MatchString(arg) {\n\t\t\tfound = true\n\t\t}\n\t}\n\treturn found\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsScriptRenderDelaying returns true if the node has one of these values for attribute 'customelement': ampdynamiccssclasses, ampexperiment, ampstory.
func IsScriptRenderDelaying(n *html.Node) bool { if n.DataAtom != atom.Script { return false } if IsScriptAMPViewer(n) { return true } if v, ok := htmlnode.GetAttributeVal(n, "", AMPCustomElement); ok { // TODO(b/77581738): Remove amp-story from this list. return (v == AMPDynamicCSSClasses || v == AMPExperiment || v == AMPStory) } return false }
[ "func IsScriptAMPRuntime(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\tif v, ok := htmlnode.GetAttributeVal(n, \"\", \"src\"); ok {\n\t\treturn htmlnode.HasAttribute(n, \"\", \"async\") &&\n\t\t\t!IsScriptAMPExtension(n) &&\n\t\t\tstrings.HasPrefix(v, AMPCacheRootURL) &&\n\t\t\t(strings.HasSuffix(v, \"/v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/v0.mjs\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.js\") ||\n\t\t\t\tstrings.HasSuffix(v, \"/amp4ads-v0.mjs\"))\n\t}\n\treturn false\n}", "func (me TxsdPresentationAttributesColorColorRendering) IsAuto() bool { return me.String() == \"auto\" }", "func (m Task) IsDelayTask() bool {\n\treturn m.Metadata.Options.DelayDuration > 0\n}", "func (me TxsdAnimTimingAttrsRestart) IsWhenNotActive() bool { return me.String() == \"whenNotActive\" }", "func (me TxsdPresentationAttributesColorColorRendering) IsOptimizeSpeed() bool {\n\treturn me.String() == \"optimizeSpeed\"\n}", "func (me TxsdPresentationAttributesGraphicsTextRendering) IsAuto() bool { return me.String() == \"auto\" }", "func (me TxsdPresentationAttributesTextContentElementsDominantBaseline) IsAutosenseScript() bool {\n\treturn me.String() == \"autosense-script\"\n}", "func (me TxsdPresentationAttributesGraphicsTextRendering) IsOptimizeSpeed() bool {\n\treturn me.String() == \"optimizeSpeed\"\n}", "func (r *RenderThrottler) NeedRendering() bool {\n\tif !r.isActive {\n\t\treturn true // always render when throttler is disabled\n\t}\n\treturn r.needRendering\n}", "func IsScriptAMPViewer(n *html.Node) bool {\n\tif n.DataAtom != atom.Script {\n\t\treturn false\n\t}\n\ta, ok := htmlnode.FindAttribute(n, \"\", \"src\")\n\treturn ok &&\n\t\t!IsScriptAMPExtension(n) &&\n\t\tstrings.HasPrefix(a.Val,\n\t\t\tAMPCacheSchemeAndHost+\"/v0/amp-viewer-integration-\") &&\n\t\tstrings.HasSuffix(a.Val, \".js\") &&\n\t\thtmlnode.HasAttribute(n, \"\", \"async\")\n}", "func (this *TimeStamp) HasDelay() bool {\n\treturn this.delay != -1\n}", "func (me TxsdColorProfileTypeRenderingIntent) IsAuto() bool { return me.String() == \"auto\" }", "func (l *KraanLayer) IsDelayed() bool {\n\treturn l.delayed\n}", "func (me TxsdAnimTimingAttrsRestart) IsAlways() bool { return me.String() == \"always\" }", "func (me TxsdAnimTimingAttrsFill) IsFreeze() bool { return me.String() == \"freeze\" }", "func (me TxsdPresentationAttributesColorColorRendering) IsOptimizeQuality() bool {\n\treturn me.String() == \"optimizeQuality\"\n}", "func (me TxsdPresentationAttributesColorColorInterpolation) IsAuto() bool {\n\treturn me.String() == \"auto\"\n}", "func (t *Trigger) needsDelay() (bool, time.Duration) {\n\tif t.params.MinInterval == time.Duration(0) {\n\t\treturn false, 0\n\t}\n\n\tsleepTime := time.Since(t.lastTrigger.Add(t.params.MinInterval))\n\treturn sleepTime < 0, sleepTime * -1\n}", "func (me TxsdPresentationAttributesGraphicsShapeRendering) IsOptimizeSpeed() bool {\n\treturn me.String() == \"optimizeSpeed\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewDOM constructs and returns a pointer to a DOM struct by finding the HTML nodes relevant to an AMP Document or an error if there was a problem. TODO(alin04): I don't think this can EVER return an error. The golang parser creates all these nodes if they're missing.
func NewDOM(n *html.Node) (*DOM, error) { var ok bool d := &DOM{RootNode: n} if d.HTMLNode, ok = htmlnode.FindNode(n, atom.Html); !ok { return d, errors.New("missing <html> node") } if d.HeadNode, ok = htmlnode.FindNode(d.HTMLNode, atom.Head); !ok { return d, errors.New("missing <head> node") } if d.BodyNode, ok = htmlnode.FindNode(d.HTMLNode, atom.Body); !ok { return d, errors.New("missing <body> node") } return d, nil }
[ "func NewDOM(conn *rpcc.Conn) *DOM {\n\treturn &DOM{conn: conn}\n}", "func NewDOM() *DOM {\n\treturn &DOM{\n\t\tGlobalInst: map[string]*Instruction{},\n\t\tScenarios: map[string]*Instruction{},\n\t\tSubScenarios: map[string]*Instruction{},\n\t\tOtherScenarios: map[string]map[string]*Instruction{},\n\t\tOtherSubScenarios: map[string]map[string]*Instruction{},\n\t\tCoveredPaths: map[string]*Path{},\n\t}\n}", "func FromHTMLParseTree(h *html.Node, css cssom.StyleSheet) *W3CNode {\n\tif h == nil {\n\t\tT().Infof(\"Cannot create DOM for null-HTML\")\n\t\treturn nil\n\t}\n\tstyles := douceuradapter.ExtractStyleElements(h)\n\tT().Debugf(\"Extracted %d <style> elements\", len(styles))\n\ts := cssom.NewCSSOM(nil) // nil = no additional properties\n\tfor _, sty := range styles {\n\t\ts.AddStylesForScope(nil, sty, cssom.Script)\n\t}\n\tif css != nil {\n\t\ts.AddStylesForScope(nil, css, cssom.Author)\n\t}\n\tstytree, err := s.Style(h, styledtree.Creator())\n\tif err != nil {\n\t\tT().Errorf(\"Cannot style test document: %s\", err.Error())\n\t\treturn nil\n\t}\n\treturn domify(stytree)\n}", "func NewHTML(v HTML) *HTML { return &v }", "func NewDocForTesting(html string) js.Value {\n\tdom := jsdom.New(html, map[string]interface{}{\n\t\t\"runScripts\": \"dangerously\",\n\t\t\"resources\": \"usable\",\n\t})\n\n\t// Create doc, but then wait until loading is complete and constructed\n\t// doc is returned. By default, jsdom loads doc asynchronously:\n\t// https://oliverjam.es/blog/frontend-testing-node-jsdom/#waiting-for-external-resources\n\tc := make(chan js.Value)\n\tdom.Get(\"window\").Call(\n\t\t\"addEventListener\", \"load\",\n\t\tjsutil.OneTimeFuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\t\tc <- dom.Get(\"window\").Get(\"document\")\n\t\t\treturn nil\n\t\t}))\n\treturn <-c\n}", "func NewHTML(children ...Element) Element {\n\treturn newWithChildren(\"html\", children)\n}", "func GetHTML(url string) *goquery.Document {\n\n\tlogger := InitLogging()\n\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\tlogger.Printf(\"error: failed to get document from \" + url)\n\t\tlogger.Printf(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\treturn doc\n}", "func NewDOMDebugger(conn *rpcc.Conn) *DOMDebugger {\n\treturn &DOMDebugger{conn: conn}\n}", "func NewDOMStorage(conn *rpcc.Conn) *DOMStorage {\n\treturn &DOMStorage{conn: conn}\n}", "func ParseHTMLDocument(r io.ReadCloser) (*html.Node, error) {\n\tdoc, err := html.Parse(r)\n\n\tif err != nil {\n\t\tpanic(\"error parsing document\")\n\t}\n\n\treturn doc, nil\n}", "func ParseHTML(url string) *html.Node {\r\n\t_, body, err := fasthttp.Get(nil, url)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\tdocument, err := html.Parse(bytes.NewReader(body))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\treturn document\r\n}", "func GetParseableHTML(url string) (*html.Node, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn root, nil\n}", "func NewElementFromNode(node*html.Node, em ElementsMap) *Element {\n\telem := &Element{\n\t\tdata: strings.Trim(node.Data, \"\\n\\r\\t \"),\n\t\tAttributes: node.Attr,\n\t\tnodeType: node.Type,\n\t\tKids: make([]*Element, 0),\n\t\teventHandlers: make(map[string]EventHandler),\n\t}\n\tif em!=nil && elem.GetID()!=\"\"{\n\t\tem[elem.GetID()]=elem\n\t}\n\tfor c := node.FirstChild; c != nil; c = c.NextSibling {\n\t\telem.AddElement(NewElementFromNode(c,em));\n\t}\n\treturn elem\n}", "func NewDomVisit(badFname string) *DomVisit {\n\tvar itm *DomVisit\n\titm = new(DomVisit)\n\titm.sm = new(sync.RWMutex)\n\tdv := make(map[string]struct{})\n\tbd := make(map[string]struct{})\n\titm.wg = new(sync.WaitGroup)\n\titm.re = regexp.MustCompile(\"([a-zA-Z0-9_\\\\-\\\\.]+)(\\\\/[\\\\/\\\\w\\\\.]+)?$\")\n\titm.domainsVisited = &dv\n\titm.badDomains = &bd\n\tif badFname != \"\" {\n\t\tvar err error\n\t\titm.badFile, err = os.OpenFile(\"badf.txt\", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\t\tcheck(err)\n\t\titm.LoadBadFiles(badFname)\n\t}\n\n\treturn itm\n}", "func NewParserHTML(followExternalLinks bool) *ParserHTML {\n\treturn &ParserHTML{followExternalLinks}\n}", "func VerifyDOM(s string) bool { //(body io.ReadCloser) bool {\n\n\tbody := ioutil.NopCloser(strings.NewReader(s)) // r type is io.ReadCloser\n\tdefer body.Close()\n\n\t// Load the HTML document\n\tdoc, err := goquery.NewDocumentFromReader(body)\n\tcheck := false\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\t// Find the review items\n\tdoc.Find(\".dalfox\").Each(func(i int, s *goquery.Selection) {\n\t\tcheck = true\n\t})\n\tif !check {\n\t\tdoc.Find(\"dalfox\").Each(func(i int, s *goquery.Selection) {\n\t\t\t// For each item found, get the band and title\n\t\t\tcheck = true\n\t\t})\n\t}\n\treturn check\n}", "func (bow *Browser) DOM() *goquery.Document {\n\treturn bow.state.Dom\n}", "func NewElements() Elements {\n\treturn Elements{}\n}", "func ParseHTML(buf io.Reader) (*Object, error) {\n\tobj := newObject()\n\tisInsideHead := false\n\tisInsideTitle := false\n\tz := html.NewTokenizer(buf)\n\tfor {\n\t\ttt := z.Next()\n\t\tif tt == html.ErrorToken {\n\t\t\tif z.Err() == io.EOF {\n\t\t\t\treturn obj, nil\n\t\t\t}\n\n\t\t\treturn nil, z.Err()\n\t\t}\n\n\t\tisStartTagToken := tt == html.StartTagToken\n\t\tif !isInsideHead && !isStartTagToken {\n\t\t\tcontinue\n\t\t}\n\t\tif tt == html.CommentToken || tt == html.DoctypeToken {\n\t\t\tcontinue\n\t\t}\n\n\t\tif isInsideTitle {\n\t\t\tisInsideTitle = false\n\t\t\tif tt == html.TextToken {\n\t\t\t\ttitleText := string(z.Text())\n\t\t\t\tobj.Title = titleText\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tisEndTagToken := tt == html.EndTagToken\n\t\tisSelfClosingTagToken := tt == html.SelfClosingTagToken\n\t\tif isStartTagToken || isEndTagToken || isSelfClosingTagToken {\n\t\t\tname, hasAttr := z.TagName()\n\t\t\tnameAtom := atom.Lookup(name)\n\t\t\tif !isInsideHead {\n\t\t\t\tif nameAtom == atom.Head {\n\t\t\t\t\tif isStartTagToken {\n\t\t\t\t\t\tisInsideHead = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn obj, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif nameAtom == atom.Title && isStartTagToken {\n\t\t\t\tif isStartTagToken {\n\t\t\t\t\tisInsideTitle = true\n\t\t\t\t} else if isEndTagToken {\n\t\t\t\t\tisInsideTitle = false\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// skip if the current tag doesn't have any attributes or is an end\n\t\t\t// tag token\n\t\t\tif !hasAttr || isEndTagToken {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// base tag\n\t\t\tif nameAtom == atom.Base {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString string\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrHREF {\n\t\t\t\t\t\tif href := string(value); validator.ValidateHREF(href) {\n\t\t\t\t\t\t\tobj.Base = href\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// link tag\n\t\t\tif nameAtom == atom.Link {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString, relValue string\n\t\t\t\tlink := &Link{}\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrRel {\n\t\t\t\t\t\trelValue = string(value)\n\t\t\t\t\t} else if keyString == attrHREF {\n\t\t\t\t\t\tif href := string(value); validator.ValidateHREF(href) {\n\t\t\t\t\t\t\tlink.HREF = href\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if keyString == attrType {\n\t\t\t\t\t\t// TODO: validation\n\t\t\t\t\t\tlink.Type = string(value)\n\t\t\t\t\t} else if keyString == attrTitle {\n\t\t\t\t\t\tlink.Title = string(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif relValue != \"\" {\n\t\t\t\t\tobj.Links[relValue] = append(obj.Links[relValue], link)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// meta tag\n\t\t\tif nameAtom == atom.Meta {\n\t\t\t\tvar key, value []byte\n\t\t\t\tvar keyString, propertyValue, contentValue string\n\t\t\t\tvar hasCharset bool\n\t\t\t\tfor hasAttr {\n\t\t\t\t\tkey, value, hasAttr = z.TagAttr()\n\t\t\t\t\tkeyString = atom.String(key)\n\t\t\t\t\tif keyString == attrCharset {\n\t\t\t\t\t\t// TODO: validation\n\t\t\t\t\t\tobj.Charset = string(value)\n\t\t\t\t\t\thasCharset = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else if keyString == attrProperty ||\n\t\t\t\t\t\tkeyString == attrName ||\n\t\t\t\t\t\tkeyString == attrHTTPEquiv ||\n\t\t\t\t\t\tkeyString == attrItemProp {\n\t\t\t\t\t\tpropertyValue = string(value)\n\t\t\t\t\t} else if keyString == \"content\" {\n\t\t\t\t\t\tcontentValue = string(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !hasCharset && propertyValue != \"\" {\n\t\t\t\t\tobj.Metas[propertyValue] = contentValue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
InitStudentsSubscriptionsHandler initialize studentsSubscriptions router
func InitStudentsSubscriptionsHandler(r *atreugo.Router, s *service.Service) { r.GET("/", getAllStudentsSubscriptions(s)) }
[ "func InitSubscriptionsHandler(r *atreugo.Router, s *service.Service) {\n\tr.GET(\"/\", getAllSubscriptions(s))\n}", "func (s *StanServer) initSubscriptions() error {\n\n\t// Do not create internal subscriptions in clustered mode,\n\t// the leader will when it gets elected.\n\tif !s.isClustered {\n\t\tcreateSubOnClientPublish := true\n\n\t\tif s.partitions != nil {\n\t\t\t// Receive published messages from clients, but only on the list\n\t\t\t// of static channels.\n\t\t\tif err := s.partitions.initSubscriptions(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Since we create a subscription per channel, do not create\n\t\t\t// the internal subscription on the > wildcard\n\t\t\tcreateSubOnClientPublish = false\n\t\t}\n\n\t\tif err := s.initInternalSubs(createSubOnClientPublish); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ts.log.Debugf(\"Discover subject: %s\", s.info.Discovery)\n\t// For partitions, we actually print the list of channels\n\t// in the startup banner, so we don't need to repeat them here.\n\tif s.partitions != nil {\n\t\ts.log.Debugf(\"Publish subjects root: %s\", s.info.Publish)\n\t} else {\n\t\ts.log.Debugf(\"Publish subject: %s.>\", s.info.Publish)\n\t}\n\ts.log.Debugf(\"Subscribe subject: %s\", s.info.Subscribe)\n\ts.log.Debugf(\"Subscription Close subject: %s\", s.info.SubClose)\n\ts.log.Debugf(\"Unsubscribe subject: %s\", s.info.Unsubscribe)\n\ts.log.Debugf(\"Close subject: %s\", s.info.Close)\n\treturn nil\n}", "func (db *Database) GetAllStudentsSubscriptions() (pgx.Rows, error) {\n\treturn db.conn.Query(context.Background(), \"SELECT * FROM students_subscriptions\")\n}", "func NewSubscriptionHandler(store common.SubscriptionStore) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tswitch r.Method {\n\t\tcase http.MethodGet:\n\t\t\t{\n\t\t\t\tsubs := store.GetAll()\n\t\t\t\tbytes, err := json.Marshal(subs)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\twriteError(err, w)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Write(bytes)\n\t\t\t}\n\t\tdefault:\n\t\t\t{\n\t\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\t\tw.Write([]byte(\"not implemented\"))\n\t\t\t}\n\t\t}\n\t}\n}", "func (router *Router) Subscriptions() {\n\tfor {\n\t\tvar sub *Subscription\n\t\tselect {\n\t\tcase sub = <-router.channels.subAdd:\n\t\t\trouter.elog.Logf(elog.LogLevelInfo2, \"SubAdd\")\n\t\tcase sub = <-router.channels.subMod:\n\t\t\trouter.elog.Logf(elog.LogLevelInfo2, \"SubMod\")\n\t\tcase sub = <-router.channels.subDel:\n\t\t\trouter.elog.Logf(elog.LogLevelInfo2, \"SubDel\")\n\t\t}\n\n\t\tif sub.SubID == 0 {\n\t\t\trouter.elog.Logf(elog.LogLevelError, \"FIXME: Use sub to keep compiler happy\")\n\t\t}\n\n\t}\n}", "func (s *Subscription) Init(options ...func(*Subscription)) error {\n\tfor _, option := range options {\n\t\toption(s)\n\t}\n\n\tif s.client == nil {\n\t\treturn errors.New(\"invalid client\")\n\t}\n\n\tif s.resourceRepository == nil {\n\t\treturn errors.New(\"invalid resource repository\")\n\t}\n\n\ts.collection = \"subscriptions\"\n\ts.collectionTrigger = \"subscriptionTriggers\"\n\ts.database = s.client.database\n\n\treturn s.ensureIndex()\n}", "func (b *EventStreamBroker) UpdateSubscriptionsHandler(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Only POST method allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\th := w.Header()\n\th.Set(\"Cache-Control\", \"no-cache\")\n\th.Set(\"Connection\", \"keep-alive\")\n\th.Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t// Incoming request data\n\tvar reqData updateSubscriptionsData\n\n\t// Decode JSON body\n\tdec := json.NewDecoder(r.Body)\n\tif err := dec.Decode(&reqData); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// If the ID isn't provided, that means it is a new client\n\t// So generate an ID and create a new client.\n\tif reqData.SessID == \"\" {\n\t\thttp.Error(w, \"Session ID is required 'session_id'\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tb.mu.RLock()\n\tclient, ok := b.clients[reqData.SessID]\n\tb.mu.RUnlock()\n\tif !ok {\n\t\thttp.Error(w, \"Invalid session ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\n\tvar wg sync.WaitGroup\n\n\tfor _, topic := range reqData.Add {\n\t\twg.Add(1)\n\t\tgo func(t string) {\n\t\t\tif err := b.subscriptionBroker.SubscribeClient(client, t); err != nil {\n\t\t\t\tlog.Println(\"Error:\", err)\n\n\t\t\t\td, _ := json.Marshal(map[string]interface{}{\n\t\t\t\t\t\"error\": map[string]string{\n\t\t\t\t\t\t\"code\": \"subscription-failure\",\n\t\t\t\t\t\t\"message\": fmt.Sprintf(\"Cannot subscribe to topic %v\", t),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tclient.writeChannel <- d\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(topic)\n\t}\n\n\tfor _, topic := range reqData.Remove {\n\t\twg.Add(1)\n\t\tgo func(t string) {\n\t\t\tb.subscriptionBroker.UnsubscribeClient(ctx, client, t)\n\t\t\twg.Done()\n\t\t}(topic)\n\t}\n\n\twg.Wait()\n\n\tclient.mu.RLock()\n\tlog.Printf(\"Client '%v' subscriptions updated, total topics subscribed: %v \\n\", client.sessID, len(client.topics))\n\tclient.mu.RUnlock()\n\n\t// Return the ID of the client.\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(map[string]string{\"session_id\": reqData.SessID}); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func NewSubscriptions(client *gosip.SPClient, endpoint string, config *RequestConfig) *Subscriptions {\n\treturn &Subscriptions{\n\t\tclient: client,\n\t\tendpoint: endpoint,\n\t\tconfig: config,\n\t}\n}", "func UnsubscribeStudentFromCourse(w http.ResponseWriter, r *http.Request) {\n\n\t// For authentication purpose the access token is read from the Cookie header and validated, it's also verified if\n\t// requester is a student\n\ttokenString, err := GetToken(w, r)\n\tif err != nil {\n\t\tMakeErrorResponse(w, http.StatusUnauthorized, \"Permission denied\")\n\t\tlog.Println(\"Permission denied\")\n\t\treturn\n\t}\n\tdecodedToken, err := ValidateToken(tokenString, w)\n\tif err != nil {\n\t\tMakeErrorResponse(w, http.StatusUnauthorized, \"Permission denied\")\n\t\tlog.Println(\"Permission denied\")\n\t\treturn\n\t}\n\tif decodedToken.Type != \"student\" {\n\t\tMakeErrorResponse(w, http.StatusUnauthorized, \"Permission denied\")\n\t\tlog.Println(\"Permission denied\")\n\t\treturn\n\t}\n\n\t/* Upon successful validation a distributed transaction starts: api gateway send to course management and notification\n\tmanagement micro-services a request to deregister the user to course in their own data-store. The request succeeds only\n\tif the operation is completed by both micro-services. The requests are send in parallel using goroutines. */\n\n\t// Collecting parameters for requests to course management and notification management micro-services\n\tstudentUsername := mux.Vars(r)[\"username\"]\n\tstudentMail := decodedToken.Mail\n\tvar courseMinimized CourseMinimized\n\tvar course Course\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"API Gateway - Internal Server Error\")\n\t\tlog.Println(\"API Gateway - Internal Server Error\")\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, &courseMinimized)\n\tif err != nil {\n\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"API Gateway - Internal Server Error\")\n\t\tlog.Println(\"API Gateway - Internal Server Error\")\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, &course)\n\tif err != nil {\n\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"API Gateway - Internal Server Error\")\n\t\tlog.Println(\"API Gateway - Internal Server Error\")\n\t\treturn\n\t}\n\n\t//Initialize the channel to receive the exit of local transactions\n\tc := make(chan localTransaction, 2)\n\n\t//Launching goRoutines responsible to actuate local transaction\n\tgo removeSubscriptionInCourseManagement(studentUsername, courseMinimized.Id, c)\n\tgo removeSubscriptionInNotificationManagement(studentMail, course, c)\n\n\tisSentResponse := false // Indicate if an internal error occurred and client already received a response\n\tvar response *http.Response // The response for the client\n\tvar localTransaction localTransaction\n\tvar failingMicroservice []string // Contains the name of micro-service(s) that failed the execution of the request\n\tvar i int\n\n\tfor i = 0; i <= 1; i++ {\n\t\t// Waiting for the exit of local transactions\n\t\tlocalTransaction = <-c\n\t\tif localTransaction.Response == nil {\n\t\t\t// Any error occurred during forwarding of request: the client receive immediately an Internal Server Error\n\t\t\tfailingMicroservice = append(failingMicroservice, localTransaction.Microservice)\n\t\t\tif isSentResponse == false {\n\t\t\t\tisSentResponse = true\n\t\t\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"Api Gateway - Internal Server Error\")\n\t\t\t\tlog.Println(\"Api Gateway - Internal Server Error\")\n\t\t\t}\n\t\t} else if localTransaction.Response.StatusCode != http.StatusOK {\n\t\t\t// Failure: the client receive the last error response that the api-gateway obtained from micro-services\n\t\t\tfailingMicroservice = append(failingMicroservice, localTransaction.Microservice)\n\t\t\tresponse = localTransaction.Response\n\t\t} else {\n\t\t\t// Success: the client receive the success response from course management micro-service.\n\t\t\tif localTransaction.Microservice == \"courseManagement\" {\n\t\t\t\tif response == nil {\n\t\t\t\t\tresponse = localTransaction.Response\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If only a micro-service fail the other have to undo the action just completed\n\tif len(failingMicroservice) == 1 {\n\t\tif failingMicroservice[0] == \"courseManagement\" {\n\t\t\taddSubscriptionInNotificationManagement(studentMail, course, nil)\n\t\t} else {\n\t\t\taddSubscriptionInCourseManagement(studentUsername, \"\", \"\", courseMinimized.Id, nil)\n\t\t}\n\t}\n\n\t// If no Internal Server Error occurred the response from micro-services is forwarded to client\n\tif !isSentResponse {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(response.StatusCode)\n\t\tresponseBody, err := ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"Api Gateway - Internal Server Error\")\n\t\t\tlog.Println(\"Api Gateway - Internal Server Error\")\n\t\t\treturn\n\t\t}\n\t\t_, err = w.Write(responseBody)\n\t\tif err != nil {\n\t\t\tMakeErrorResponse(w, http.StatusInternalServerError, \"Api Gateway - Internal Server Error\")\n\t\t\tlog.Println(\"Api Gateway - Internal Server Error\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (ec *EngineCommunication) initReverseCommandSubscription() {\n\tconfig.Log.Debug(\"Subscribing to \" + naming.ReverseCommand + \" of \" + naming.Name(ec.Index))\n\tec.ReverseCommandSubscriber = communication.Subscribe(\n\t\tnaming.Topic(ec.Index, naming.ReverseCommand),\n\t\tnaming.Subscriber(ec.Index, naming.ReverseCommand),\n\t\tfunc (client mqtt.Client, msg mqtt.Message) {\n\t\t\treverseCommandRequest := reverseCommandRequest{}\n\t\t\terr := json.Unmarshal(msg.Payload(), &reverseCommandRequest)\n\t\t\tif err != nil {\n\t\t\t\tformatted := fmt.Sprintf(\"couldn't unmarshal reverse command request: %v\", err)\n\t\t\t\tconfig.Log.Debug(formatted)\n\t\t\t}\n\t\t\tec.ReverseCommandRequests <- reverseCommandRequest\n\t\t})\n}", "func init() {\n\n\t// Standard routes\n\trouter.Get(\"/backlog\", GetAllProductBackLogs)\n\trouter.Get(\"/backlog/:id\", GetProductBackLog)\n\trouter.Post(\"/backlog\", PostProductBackLog)\n\trouter.Put(\"/backlog/:id\", PutProductBackLog)\n\trouter.Delete(\"/backlog/:id\", DeleteProductBackLog)\n\n\trouter.Get(\"/backlog/:id/stories\", GetProductBackLogsAllStories)\n}", "func (ss *SNSServer) PrepareAndStart() {\n\n\tss.Subscribe()\n}", "func startSubscription(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tprotocol := vars[\"protocol\"]\n\tendpointType := vars[\"endpointType\"]\n\tvar keys []string\n\terr := json.NewDecoder(r.Body).Decode(&keys)\n\tif err != nil {\n\t\tsendResponse(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tvar subscriptionID string\n\tif protocol == \"http\" {\n\t\tsubscriptionID, err = subscribeHTTP(keys, endpointType)\n\t} else if protocol == \"grpc\" {\n\t\tsubscriptionID, err = subscribeGRPC(keys, endpointType)\n\t} else {\n\t\terr = fmt.Errorf(\"unknown protocol in Subscribe call: %s\", protocol)\n\t}\n\n\tif err != nil {\n\t\tsendResponse(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tsendResponse(w, http.StatusOK, subscriptionID)\n}", "func (r *Receivers) subscriptionPage(c *gin.Context) {\n\n\temail := checkSession(c)\n\n\tsubscribed := r.eb.userTopics[email]\n\n\ttRes := Topic{}\n\tvar results []Topic\n\n\tfor _, topic := range subscribed {\n\t\ttRes.Name = topic\n\t\ttRes.Flag = true\n\t\tresults = append(results, tRes)\n\t}\n\n\tnoSubscribed, err := r.dbServer.db.Query(\"select t.name from topics t where t.name \"+\n\t\t\"not in (select s.topic from subscriptions s where s.subscriber = $1)\", email)\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tfor noSubscribed.Next() {\n\t\tvar name string\n\t\t_ = noSubscribed.Scan(&name)\n\t\ttRes.Name = name\n\t\ttRes.Flag = false\n\t\tresults = append(results, tRes)\n\t}\n\n\tuserAgent := c.Request.Header.Get(\"User-Agent\")\n\n\tif strings.Contains(userAgent, \"curl\") {\n\n\t\tc.JSON(http.StatusOK, results)\n\n\t} else {\n\n\t\tredirect(c, \"subscribe.html\", \"logged\", results, true, http.StatusOK, \"Subscription Page\")\n\t}\n}", "func HandleSubscribedPublishers(env *config.Env) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuidStr := r.Header.Get(\"UID\")\n\t\tif uidStr == \"\" {\n\t\t\thttp.Error(w, \"A UID header's missing\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tuid, err := strconv.ParseUint(uidStr, 10, 64)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"An unexpected error occured. Please try again later.\", http.StatusInternalServerError)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tpublisherIds, err := env.DB.SubscribedPublishers(r.Context(), uid)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"An unexpected error has occured while retrieving the subscribed publishers\", http.StatusInternalServerError)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(publisherIds)\n\t}\n}", "func NewSubscriptionsHandler(prefix string, postfixOpts string) (*EventStreamBroker, error) {\n\n\tif prefix == \"\" {\n\t\treturn nil, errors.New(\"Prefix cannot be empty\")\n\t}\n\n\treturn &EventStreamBroker{\n\t\tsubscriptionBroker: &subscriptionsBroker{\n\t\t\tPrefix: prefix,\n\t\t\tPostfixOptions: postfixOpts,\n\t\t\tsubs: make(map[string]*subscription),\n\t\t},\n\t\tclients: make(map[string]*client),\n\t}, nil\n}", "func (p *SimpleProxy) init() error {\n\treturn p.registerSubscribers()\n}", "func init() {\n\tauth.Register(\"entitlement\", auth.InitFunc(newAccessController))\n}", "func subscriptionFilter(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tcontactID := middleware.GetSubscriptionId(request)\n\t\tuserLogin := middleware.GetLogin(request)\n\t\tsubscriptionData, err := controller.CheckUserPermissionsForSubscription(database, contactID, userLogin)\n\t\tif err != nil {\n\t\t\trender.Render(writer, request, err)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(request.Context(), subscriptionKey, subscriptionData)\n\t\tnext.ServeHTTP(writer, request.WithContext(ctx))\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compile will compile solution if not yet compiled. The compilation prosess will execute compile script of the language. It will use debugcompile script when debug parameter is true. When debug is true, but the language is not debuggable (doesn't contain debugcompile script), an ErrLanguageNotDebuggable error will returned. This function will execute the compilation script (could be compile/debugcompile) that defined in language definition. This execution could be skipped when the solution already compiled before.
func (cptool *CPTool) Compile(ctx context.Context, solution Solution, debug bool) (CompilationResult, error) { language := solution.Language if debug && !language.Debuggable { return CompilationResult{}, ErrLanguageNotDebuggable } targetDir := cptool.getCompiledDirectory(solution, debug) cptool.fs.MkdirAll(targetDir, os.ModePerm) targetPath := cptool.getCompiledTarget(solution, debug) if cptool.logger != nil { cptool.logger.Println(logger.VERBOSE, "Compiling to: ", targetPath) } info, err := cptool.fs.Stat(targetPath) if err == nil { compiledTime := info.ModTime() if compiledTime.After(solution.LastUpdated) { return CompilationResult{ Skipped: true, TargetPath: targetPath, }, nil } } commandPath := language.CompileScript if debug { commandPath = language.DebugScript } if cptool.logger != nil { cptool.logger.Println(logger.VERBOSE, "Compiling using script: ", commandPath) } cmd := cptool.exec.CommandContext(ctx, commandPath, solution.Path, targetPath) stderr, err := cmd.StderrPipe() if err != nil { return CompilationResult{}, err } err = cmd.Start() if err != nil { return CompilationResult{}, err } compilationError, err := ioutil.ReadAll(stderr) if err != nil { return CompilationResult{}, err } err = cmd.Wait() if err != nil { if cptool.logger != nil { cptool.logger.Print(logger.VERBOSE, "Compilation script execution giving error result") } return CompilationResult{ErrorMessage: string(compilationError)}, err } return CompilationResult{ Skipped: false, TargetPath: targetPath, }, nil }
[ "func (cptool *CPTool) CompileByName(ctx context.Context, languageName string, solutionName string, debug bool) (CompilationResult, error) {\n\tstart := time.Now()\n\n\tlanguage, err := cptool.GetLanguageByName(languageName)\n\tif err != nil {\n\t\treturn CompilationResult{}, err\n\t}\n\tif cptool.logger != nil {\n\t\tcptool.logger.Println(logger.VERBOSE, \"Compiling using language:\", language.Name)\n\t}\n\n\tsolution, err := cptool.GetSolution(solutionName, language)\n\tif err != nil {\n\t\treturn CompilationResult{}, err\n\t}\n\tif cptool.logger != nil {\n\t\tcptool.logger.Println(logger.VERBOSE, \"Compiling solution:\", solution.Name)\n\t}\n\n\tresult, err := cptool.Compile(ctx, solution, debug)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Duration = time.Since(start)\n\treturn result, nil\n}", "func (d *Runtime) CompileScript(ctx context.Context, args *cdpcmd.RuntimeCompileScriptArgs) (reply *cdpcmd.RuntimeCompileScriptReply, err error) {\n\treply = new(cdpcmd.RuntimeCompileScriptReply)\n\tif args != nil {\n\t\terr = rpcc.Invoke(ctx, cdpcmd.RuntimeCompileScript.String(), args, reply, d.conn)\n\t} else {\n\t\terr = rpcc.Invoke(ctx, cdpcmd.RuntimeCompileScript.String(), nil, reply, d.conn)\n\t}\n\tif err != nil {\n\t\terr = &opError{Domain: \"Runtime\", Op: \"CompileScript\", Err: err}\n\t}\n\treturn\n}", "func Compile(code string, ext vm.Externals) (vm.Program, parser.Messages) {\n\tinput := antlr.NewInputStream(code)\n\treturn compile(input, ext)\n}", "func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int {\n\tdebug.Println(\"running binary\", exePath)\n\tc := exec.Command(exePath, inv.Args...)\n\tc.Stderr = inv.Stderr\n\tc.Stdout = inv.Stdout\n\tc.Stdin = inv.Stdin\n\tc.Dir = inv.Dir\n\tif inv.WorkDir != inv.Dir {\n\t\tc.Dir = inv.WorkDir\n\t}\n\t// intentionally pass through unaltered os.Environ here.. your magefile has\n\t// to deal with it.\n\tc.Env = os.Environ()\n\tif inv.Verbose {\n\t\tc.Env = append(c.Env, \"MAGEFILE_VERBOSE=1\")\n\t}\n\tif inv.List {\n\t\tc.Env = append(c.Env, \"MAGEFILE_LIST=1\")\n\t}\n\tif inv.Help {\n\t\tc.Env = append(c.Env, \"MAGEFILE_HELP=1\")\n\t}\n\tif inv.Debug {\n\t\tc.Env = append(c.Env, \"MAGEFILE_DEBUG=1\")\n\t}\n\tif inv.GoCmd != \"\" {\n\t\tc.Env = append(c.Env, fmt.Sprintf(\"MAGEFILE_GOCMD=%s\", inv.GoCmd))\n\t}\n\tif inv.Timeout > 0 {\n\t\tc.Env = append(c.Env, fmt.Sprintf(\"MAGEFILE_TIMEOUT=%s\", inv.Timeout.String()))\n\t}\n\tdebug.Print(\"running magefile with mage vars:\\n\", strings.Join(filter(c.Env, \"MAGEFILE\"), \"\\n\"))\n\t// catch SIGINT to allow magefile to handle them\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT)\n\tdefer signal.Stop(sigCh)\n\terr := c.Run()\n\tif !sh.CmdRan(err) {\n\t\terrlog.Printf(\"failed to run compiled magefile: %v\", err)\n\t}\n\treturn sh.ExitStatus(err)\n}", "func (Build) Debug() error {\n\tcfg := newBuildConfig(runtime.GOOS, runtime.GOARCH)\n\tcfg.EnableDebug = true\n\treturn buildBackend(cfg)\n}", "func Compile(ctx context.Context, q string, runtime flux.Runtime, now time.Time, opts ...CompileOption) (*AstProgram, error) {\n\tastPkg, err := runtime.Parse(ctx, q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn CompileAST(astPkg, runtime, now, opts...), nil\n}", "func ExecGoCompiler(args ...string) *exec.Cmd {\n\tecmd := exec.Command(\"go\", args...)\n\tecmd.Dir, _ = os.Getwd()\n\tecmd.Env = make([]string, len(os.Environ()))\n\tcopy(ecmd.Env, os.Environ())\n\tecmd.Env = append(\n\t\tecmd.Env,\n\t\t\"GO111MODULE=on\",\n\t)\n\tecmd.Stderr = os.Stderr\n\tecmd.Stdout = os.Stdout\n\treturn ecmd\n}", "func (c *Compiler) Compile(ctx context.Context, stmtNode ast.StmtNode) (_ *ExecStmt, err error) {\n\tr, ctx := tracing.StartRegionEx(ctx, \"executor.Compile\")\n\tdefer r.End()\n\n\tdefer func() {\n\t\tr := recover()\n\t\tif r == nil {\n\t\t\treturn\n\t\t}\n\t\tif str, ok := r.(string); !ok || !strings.Contains(str, memory.PanicMemoryExceedWarnMsg) {\n\t\t\tpanic(r)\n\t\t}\n\t\terr = errors.Errorf(\"%v\", r)\n\t\tlogutil.Logger(ctx).Error(\"compile SQL panic\", zap.String(\"SQL\", stmtNode.Text()), zap.Stack(\"stack\"), zap.Any(\"recover\", r))\n\t}()\n\n\tc.Ctx.GetSessionVars().StmtCtx.IsReadOnly = plannercore.IsReadOnly(stmtNode, c.Ctx.GetSessionVars())\n\n\tret := &plannercore.PreprocessorReturn{}\n\terr = plannercore.Preprocess(ctx, c.Ctx,\n\t\tstmtNode,\n\t\tplannercore.WithPreprocessorReturn(ret),\n\t\tplannercore.InitTxnContextProvider,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfailpoint.Inject(\"assertTxnManagerInCompile\", func() {\n\t\tsessiontxn.RecordAssert(c.Ctx, \"assertTxnManagerInCompile\", true)\n\t\tsessiontxn.AssertTxnManagerInfoSchema(c.Ctx, ret.InfoSchema)\n\t\tif ret.LastSnapshotTS != 0 {\n\t\t\tstaleread.AssertStmtStaleness(c.Ctx, true)\n\t\t\tsessiontxn.AssertTxnManagerReadTS(c.Ctx, ret.LastSnapshotTS)\n\t\t}\n\t})\n\n\tis := sessiontxn.GetTxnManager(c.Ctx).GetTxnInfoSchema()\n\tsessVars := c.Ctx.GetSessionVars()\n\tstmtCtx := sessVars.StmtCtx\n\t// handle the execute statement\n\tvar (\n\t\tpointPlanShortPathOK bool\n\t\tpreparedObj *plannercore.PlanCacheStmt\n\t)\n\n\tif execStmt, ok := stmtNode.(*ast.ExecuteStmt); ok {\n\t\tif preparedObj, err = plannercore.GetPreparedStmt(execStmt, sessVars); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif pointPlanShortPathOK, err = plannercore.IsPointPlanShortPathOK(c.Ctx, is, preparedObj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfinalPlan, names, err := planner.Optimize(ctx, c.Ctx, stmtNode, is)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfailpoint.Inject(\"assertStmtCtxIsStaleness\", func(val failpoint.Value) {\n\t\tstaleread.AssertStmtStaleness(c.Ctx, val.(bool))\n\t})\n\n\tif preparedObj != nil {\n\t\tCountStmtNode(preparedObj.PreparedAst.Stmt, sessVars.InRestrictedSQL)\n\t} else {\n\t\tCountStmtNode(stmtNode, sessVars.InRestrictedSQL)\n\t}\n\tvar lowerPriority bool\n\tif c.Ctx.GetSessionVars().StmtCtx.Priority == mysql.NoPriority {\n\t\tlowerPriority = needLowerPriority(finalPlan)\n\t}\n\tstmtCtx.SetPlan(finalPlan)\n\tstmt := &ExecStmt{\n\t\tGoCtx: ctx,\n\t\tInfoSchema: is,\n\t\tPlan: finalPlan,\n\t\tLowerPriority: lowerPriority,\n\t\tText: stmtNode.Text(),\n\t\tStmtNode: stmtNode,\n\t\tCtx: c.Ctx,\n\t\tOutputNames: names,\n\t\tTi: &TelemetryInfo{},\n\t}\n\tif pointPlanShortPathOK {\n\t\tif ep, ok := stmt.Plan.(*plannercore.Execute); ok {\n\t\t\tif pointPlan, ok := ep.Plan.(*plannercore.PointGetPlan); ok {\n\t\t\t\tstmtCtx.SetPlan(stmt.Plan)\n\t\t\t\tstmtCtx.SetPlanDigest(preparedObj.NormalizedPlan, preparedObj.PlanDigest)\n\t\t\t\tstmt.Plan = pointPlan\n\t\t\t\tstmt.PsStmt = preparedObj\n\t\t\t} else {\n\t\t\t\t// invalid the previous cached point plan\n\t\t\t\tpreparedObj.PreparedAst.CachedPlan = nil\n\t\t\t}\n\t\t}\n\t}\n\tif err = sessiontxn.OptimizeWithPlanAndThenWarmUp(c.Ctx, stmt.Plan); err != nil {\n\t\treturn nil, err\n\t}\n\treturn stmt, nil\n}", "func ExecuteRuntime(lang string) *exec.Cmd {\n\n\tlanguages := map[string]string{\n\t\t\"python\": \"poetry run python main.py\",\n\t\t\"go\": \"go run *.go\",\n\t\t\"js\": \"node main.js\",\n\t\t\"vitejs\": \"ls && sleep 5 && npm run dev\",\n\t}\n\n\t// execute and get a pipe\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", languages[lang])\n\n\treturn cmd\n}", "func Compile(\n\tsourceCode []byte,\n\tentryPoint string,\n\ttarget string,\n\tcompileFlags uint,\n\teffectFlags uint,\n) ([]byte, error) {\n\tif dll == nil {\n\t\tif err := loadDLL(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar sourcePtr uintptr\n\tif len(sourceCode) != 0 {\n\t\tsourcePtr = uintptr(unsafe.Pointer(&sourceCode[0]))\n\t}\n\n\tvar entry uintptr\n\tentryPointBytes := append([]byte(entryPoint), 0)\n\tif entryPoint != \"\" {\n\t\tentry = uintptr(unsafe.Pointer(&entryPointBytes[0]))\n\t}\n\n\ttargetBytes := append([]byte(target), 0)\n\tvar output, err *blob\n\tret, _, _ := d3DCompile.Call(\n\t\tsourcePtr,\n\t\tuintptr(len(sourceCode)),\n\t\t0, // source name\n\t\t0, // defines\n\t\t1, // default include handler (D3D_COMPILE_STANDARD_FILE_INCLUDE)\n\t\tentry,\n\t\tuintptr(unsafe.Pointer(&targetBytes[0])),\n\t\tuintptr(compileFlags),\n\t\tuintptr(effectFlags),\n\t\tuintptr(unsafe.Pointer(&output)),\n\t\tuintptr(unsafe.Pointer(&err)),\n\t)\n\tif ret == 0 {\n\t\treturn output.bytes(), nil\n\t} else if err != nil {\n\t\treturn nil, errors.New(string(err.bytes()))\n\t} else {\n\t\treturn nil, errors.New(\"D3DCompile returned error code \" +\n\t\t\tstrconv.FormatUint(uint64(ret), 10))\n\t}\n}", "func (ex *Executor) Compile() *exec.Cmd {\n\targs := append(ex.compileArgs.commandArgs, ex.compileArgs.fileName)\n\tcmd := exec.Command(ex.compileArgs.commandName, args...)\n\tcmd.Dir = ex.compileArgs.workingDir\n\treturn cmd\n}", "func (c *client) Compile(v interface{}) (*pipeline.Build, error) {\n\tp, err := c.Parse(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// validate the yaml configuration\n\terr = c.Validate(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create map of templates for easy lookup\n\ttmpls := mapFromTemplates(p.Templates)\n\n\t// create the ruledata to purge steps\n\tr := &pipeline.RuleData{\n\t\tBranch: c.build.GetBranch(),\n\t\tComment: c.comment,\n\t\tEvent: c.build.GetEvent(),\n\t\tPath: c.files,\n\t\tRepo: c.repo.GetFullName(),\n\t\tTag: strings.TrimPrefix(c.build.GetRef(), \"refs/tags/\"),\n\t\tTarget: c.build.GetDeploy(),\n\t}\n\n\tif len(p.Stages) > 0 {\n\t\t// check if the pipeline disabled the clone\n\t\tif p.Metadata.Clone == nil || *p.Metadata.Clone {\n\t\t\t// inject the clone stage\n\t\t\tp, err = c.CloneStage(p)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// inject the init stage\n\t\tp, err = c.InitStage(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// inject the templates into the stages\n\t\tp.Stages, p.Secrets, p.Services, p.Environment, err = c.ExpandStages(p, tmpls)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif c.ModificationService.Endpoint != \"\" {\n\t\t\t// send config to external endpoint for modification\n\t\t\tp, err = c.modifyConfig(p, c.build, c.repo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// validate the yaml configuration\n\t\terr = c.Validate(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create some default global environment inject vars\n\t\t// these are used below to overwrite to an empty\n\t\t// map if they should not be injected into a container\n\t\tenvGlobalServices, envGlobalSecrets, envGlobalSteps := p.Environment, p.Environment, p.Environment\n\n\t\tif !p.Metadata.HasEnvironment(\"services\") {\n\t\t\tenvGlobalServices = make(raw.StringSliceMap)\n\t\t}\n\n\t\tif !p.Metadata.HasEnvironment(\"secrets\") {\n\t\t\tenvGlobalSecrets = make(raw.StringSliceMap)\n\t\t}\n\n\t\tif !p.Metadata.HasEnvironment(\"steps\") {\n\t\t\tenvGlobalSteps = make(raw.StringSliceMap)\n\t\t}\n\n\t\t// inject the environment variables into the services\n\t\tp.Services, err = c.EnvironmentServices(p.Services, envGlobalServices)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// inject the environment variables into the secrets\n\t\tp.Secrets, err = c.EnvironmentSecrets(p.Secrets, envGlobalSecrets)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// inject the environment variables into the stages\n\t\tp.Stages, err = c.EnvironmentStages(p.Stages, envGlobalSteps)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// inject the substituted environment variables into the stages\n\t\tp.Stages, err = c.SubstituteStages(p.Stages)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// inject the scripts into the stages\n\t\tp.Stages, err = c.ScriptStages(p.Stages)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// return executable representation\n\t\treturn c.TransformStages(r, p)\n\t}\n\n\t// check if the pipeline disabled the clone\n\tif p.Metadata.Clone == nil || *p.Metadata.Clone {\n\t\t// inject the clone step\n\t\tp, err = c.CloneStep(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// inject the init step\n\tp, err = c.InitStep(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// inject the templates into the steps\n\tp.Steps, p.Secrets, p.Services, p.Environment, err = c.ExpandSteps(p, tmpls)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.ModificationService.Endpoint != \"\" {\n\t\t// send config to external endpoint for modification\n\t\tp, err = c.modifyConfig(p, c.build, c.repo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// validate the yaml configuration\n\terr = c.Validate(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create some default global environment inject vars\n\t// these are used below to overwrite to an empty\n\t// map if they should not be injected into a container\n\tenvGlobalServices, envGlobalSecrets, envGlobalSteps := p.Environment, p.Environment, p.Environment\n\n\tif !p.Metadata.HasEnvironment(\"services\") {\n\t\tenvGlobalServices = make(raw.StringSliceMap)\n\t}\n\n\tif !p.Metadata.HasEnvironment(\"secrets\") {\n\t\tenvGlobalSecrets = make(raw.StringSliceMap)\n\t}\n\n\tif !p.Metadata.HasEnvironment(\"steps\") {\n\t\tenvGlobalSteps = make(raw.StringSliceMap)\n\t}\n\n\t// inject the environment variables into the services\n\tp.Services, err = c.EnvironmentServices(p.Services, envGlobalServices)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// inject the environment variables into the secrets\n\tp.Secrets, err = c.EnvironmentSecrets(p.Secrets, envGlobalSecrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// inject the environment variables into the steps\n\tp.Steps, err = c.EnvironmentSteps(p.Steps, envGlobalSteps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// inject the substituted environment variables into the steps\n\tp.Steps, err = c.SubstituteSteps(p.Steps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// inject the scripts into the steps\n\tp.Steps, err = c.ScriptSteps(p.Steps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return executable representation\n\treturn c.TransformSteps(r, p)\n}", "func (interp *Interpreter) Debug(ctx context.Context, prog *Program, events func(*DebugEvent), opts *DebugOptions) *Debugger {\n\tdbg := new(Debugger)\n\tdbg.interp = interp\n\tdbg.events = events\n\tdbg.context, dbg.cancel = context.WithCancel(ctx)\n\tdbg.gWait = new(sync.WaitGroup)\n\tdbg.gLock = new(sync.Mutex)\n\tdbg.gLive = make(map[int]*debugRoutine, 1)\n\n\tif opts == nil {\n\t\topts = new(DebugOptions)\n\t}\n\tif opts.GoRoutineStartAt1 {\n\t\tdbg.gID = 1\n\t}\n\n\tmainG := dbg.enterGoRoutine()\n\tmainG.mode = DebugEntry\n\n\tinterp.debugger = dbg\n\tinterp.frame.debug = &frameDebugData{kind: frameRoot, g: mainG}\n\n\tprog.root.Walk(func(n *node) bool {\n\t\tn.setProgram(prog)\n\t\treturn true\n\t}, nil)\n\n\tgo func() {\n\t\tdefer func() { interp.debugger = nil }()\n\t\tdefer events(&DebugEvent{reason: DebugTerminate})\n\t\tdefer dbg.cancel()\n\n\t\t<-mainG.resume\n\t\tdbg.events(&DebugEvent{dbg, DebugEnterGoRoutine, interp.frame})\n\t\tdbg.result, dbg.err = interp.ExecuteWithContext(ctx, prog)\n\t\tdbg.exitGoRoutine(mainG)\n\t\tdbg.events(&DebugEvent{dbg, DebugExitGoRoutine, interp.frame})\n\t\tdbg.gWait.Wait()\n\t}()\n\n\treturn dbg\n}", "func Compile(state *lua.LState, moonscriptCode string) (string, error) {\n\tmoonbundle, err := Asset(\"moon-bundle.lua\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstate.SetGlobal(\"_moonbundle_code\", lua.LString(moonbundle))\n\tstate.SetGlobal(\"__moonscript_code\", lua.LString(moonscriptCode))\n\n\terr = state.DoString(`\n package.loaded.moonscript = loadstring(_moonbundle_code)()\n\n local moonparse = require(\"moonscript.parse\")\n local mooncompile = require(\"moonscript.compile\")\n\n local tree, err = moonparse.string(__moonscript_code)\n if not tree then\n print(\"gmoonscript error: unable to parse moonscript, check formatting!\")\n else\n __output_lua_code_, err = mooncompile.tree(tree)\n end\n\n -- remove all created modules and vars\n package.loaded.moonscript = nil\n moonparse = nil\n mooncompile = nil\n\n _moonbundle_code = nil\n __moonscript_code = nil\n collectgarbage()\n `)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tluaOutput := state.GetGlobal(\"__output_lua_code_\")\n\tstate.SetGlobal(\"__output_lua_code\", lua.LNil)\n\n\treturn luaOutput.String(), nil\n}", "func noCompile(runCommandTemplate []string, include func(string) bool, language apipb.LanguageGroup) compileFunc {\n\treturn func(program *apipb.Program, outputBase util.FileBase) (*Compilation, error) {\n\t\tvar filteredPaths []string\n\t\tfor _, file := range program.Sources {\n\t\t\tif include(file.Path) {\n\t\t\t\tfilteredPaths = append(filteredPaths, file.Path)\n\t\t\t}\n\t\t}\n\t\tif len(filteredPaths) == 0 {\n\t\t\treturn &Compilation{CompilerErrors: \"No valid source files found\"}, nil\n\t\t}\n\n\t\trunCommand := substituteFiles(runCommandTemplate, filteredPaths)\n\t\treturn &Compilation{\n\t\t\tProgram: &apipb.CompiledProgram{\n\t\t\t\tProgramRoot: outputBase.Path(),\n\t\t\t\tRunCommand: runCommand,\n\t\t\t\tLanguage: language,\n\t\t\t}}, nil\n\t}\n}", "func (c *Compiler) Compile(path string) (err error, comp Compilation) {\n\n\t// The command context (ctx) is employed to terminate the fork after the duration defined in the\n\t// Compiler struct has elapsed.\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.Timeout)*time.Millisecond)\n\tdefer cancel() // The cancel function is deferred to when the function exits.\n\n\t// cmd is only a struct at this point, it will not do anything until with call Run or Start\n\tcmd := exec.CommandContext(ctx, \"bash\", \"-c\", c.Cmd)\n\tcmd.Dir = path // Dir is set to the path of the current submission\n\n\t// The Stdout and Stderr are piped to respective buffers.\n\t// The buffers are referenced so the buffers are appended while the running.\n\t// This reduces the amount of memory used by the fork.\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\terr = cmd.Run() // Run the command\n\n\t// Stdout and Stderr buffers are reduced to strings and split into lines\n\tcomp.Stdout = strings.Split(string(stdout.Bytes()), \"\\n\")\n\tcomp.Stderr = strings.Split(string(stderr.Bytes()), \"\\n\")\n\n\t// If the process exited without a fight, we can record some statistics\n\tif cmd.ProcessState != nil {\n\t\tcomp.Time = (cmd.ProcessState.UserTime() + cmd.ProcessState.SystemTime()).String()\n\t\tcomp.Exit = cmd.ProcessState.ExitCode()\n\t}\n\n\treturn // Exit the function\n}", "func Compile(goos, goarch, ldflags, magePath, goCmd, compileTo string, gofiles []string, isDebug bool, stderr, stdout io.Writer) error {\n\tdebug.Println(\"compiling to\", compileTo)\n\tdebug.Println(\"compiling using gocmd:\", goCmd)\n\tif isDebug {\n\t\tinternal.RunDebug(goCmd, \"version\")\n\t\tinternal.RunDebug(goCmd, \"env\")\n\t}\n\tenviron, err := internal.EnvWithGOOS(goos, goarch)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// strip off the path since we're setting the path in the build command\n\tfor i := range gofiles {\n\t\tgofiles[i] = filepath.Base(gofiles[i])\n\t}\n\tbuildArgs := []string{\"build\", \"-o\", compileTo}\n\tif ldflags != \"\" {\n\t\tbuildArgs = append(buildArgs, \"-ldflags\", ldflags)\n\t}\n\targs := append(buildArgs, gofiles...)\n\n\tdebug.Printf(\"running %s %s\", goCmd, strings.Join(args, \" \"))\n\tc := exec.Command(goCmd, args...)\n\tc.Env = environ\n\tc.Stderr = stderr\n\tc.Stdout = stdout\n\tc.Dir = magePath\n\tstart := time.Now()\n\terr = c.Run()\n\tdebug.Println(\"time to compile Magefile:\", time.Since(start))\n\tif err != nil {\n\t\treturn errors.New(\"error compiling magefiles\")\n\t}\n\treturn nil\n}", "func (c *ChromeDebugger) CompileScript(expression string, sourceURL string, executionContextId *types.ChromeRuntimeExecutionContextId, ) (*types.ChromeDebuggerScriptId, *types.ChromeDebuggerExceptionDetails, error) {\n\tparamRequest := make(map[string]interface{}, 3)\n\tparamRequest[\"expression\"] = expression\n\tparamRequest[\"sourceURL\"] = sourceURL\n\tparamRequest[\"executionContextId\"] = executionContextId\n\trecvCh, _ := sendCustomReturn(c.target.sendCh, &ParamRequest{Id: c.target.getId(), Method: \"Debugger.compileScript\", Params: paramRequest})\n\tresp := <-recvCh\n\n\tvar chromeData struct {\n\t\tResult struct { \n\t\t\tScriptId *types.ChromeDebuggerScriptId \n\t\t\tExceptionDetails *types.ChromeDebuggerExceptionDetails \n\t\t}\n\t}\n\t\t\n\terr := json.Unmarshal(resp.Data, &chromeData)\n\tif err != nil {\n\t\tcerr := &ChromeErrorResponse{}\n\t\tchromeError := json.Unmarshal(resp.Data, cerr)\n\t\tif chromeError == nil {\n\t\t\treturn nil, nil, &ChromeRequestErr{Resp: cerr}\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\treturn chromeData.Result.ScriptId, chromeData.Result.ExceptionDetails, nil\n}", "func (sc Scripting) ScriptDebug(ctx context.Context, mode string) error {\n\tif mode != \"YES\" && mode != \"SYNC\" && mode != \"NO\" {\n\t\treturn fmt.Errorf(\"unknown script debug mode: %s\", mode)\n\t}\n\treq := newRequest(\"*3\\r\\n$6\\r\\nSCRIPT\\r\\n$5\\r\\nDEBUG\\r\\n$\")\n\treq.addString(mode)\n\treturn sc.c.cmdSimple(ctx, req)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CompileByName will compile solution if not yet compiled. This method will search the language and solution by its name and then call Compile method. This method will return an error if the language or solution with it's name doesn't exist.
func (cptool *CPTool) CompileByName(ctx context.Context, languageName string, solutionName string, debug bool) (CompilationResult, error) { start := time.Now() language, err := cptool.GetLanguageByName(languageName) if err != nil { return CompilationResult{}, err } if cptool.logger != nil { cptool.logger.Println(logger.VERBOSE, "Compiling using language:", language.Name) } solution, err := cptool.GetSolution(solutionName, language) if err != nil { return CompilationResult{}, err } if cptool.logger != nil { cptool.logger.Println(logger.VERBOSE, "Compiling solution:", solution.Name) } result, err := cptool.Compile(ctx, solution, debug) if err != nil { return result, err } result.Duration = time.Since(start) return result, nil }
[ "func (cptool *CPTool) Compile(ctx context.Context, solution Solution, debug bool) (CompilationResult, error) {\n\tlanguage := solution.Language\n\tif debug && !language.Debuggable {\n\t\treturn CompilationResult{}, ErrLanguageNotDebuggable\n\t}\n\n\ttargetDir := cptool.getCompiledDirectory(solution, debug)\n\tcptool.fs.MkdirAll(targetDir, os.ModePerm)\n\n\ttargetPath := cptool.getCompiledTarget(solution, debug)\n\tif cptool.logger != nil {\n\t\tcptool.logger.Println(logger.VERBOSE, \"Compiling to: \", targetPath)\n\t}\n\n\tinfo, err := cptool.fs.Stat(targetPath)\n\tif err == nil {\n\t\tcompiledTime := info.ModTime()\n\t\tif compiledTime.After(solution.LastUpdated) {\n\t\t\treturn CompilationResult{\n\t\t\t\tSkipped: true,\n\t\t\t\tTargetPath: targetPath,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\tcommandPath := language.CompileScript\n\tif debug {\n\t\tcommandPath = language.DebugScript\n\t}\n\tif cptool.logger != nil {\n\t\tcptool.logger.Println(logger.VERBOSE, \"Compiling using script: \", commandPath)\n\t}\n\n\tcmd := cptool.exec.CommandContext(ctx, commandPath, solution.Path, targetPath)\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn CompilationResult{}, err\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn CompilationResult{}, err\n\t}\n\n\tcompilationError, err := ioutil.ReadAll(stderr)\n\tif err != nil {\n\t\treturn CompilationResult{}, err\n\t}\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\tif cptool.logger != nil {\n\t\t\tcptool.logger.Print(logger.VERBOSE, \"Compilation script execution giving error result\")\n\t\t}\n\t\treturn CompilationResult{ErrorMessage: string(compilationError)}, err\n\t}\n\n\treturn CompilationResult{\n\t\tSkipped: false,\n\t\tTargetPath: targetPath,\n\t}, nil\n}", "func (b *Box) Compile(name string) (Template, error) {\n\tvar compileFn compileFunc\n\tif strings.HasSuffix(name, \".html\") {\n\t\tcompileFn = compileHTML\n\t} else {\n\t\tcompileFn = compileText\n\t}\n\n\tbuf, err := b.assets.Get(name)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get source for specified template\")\n\t}\n\n\treturn compileFn(name, buf, b.funcs)\n}", "func FromName(name string) (*Project, error) {\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"name is empty\")\n\t}\n\tdir := workdir.ProjectDir(name)\n\tif !fileExists(dir) {\n\t\treturn nil, errors.New(\"project directory does not exist\")\n\t}\n\treturn &Project{Name: name}, nil\n}", "func New(language string) (Compiler, error) {\n\tif len(language) <= 0 {\n\t\treturn nil, compiler_error.ErrEmptyLanguage\n\t}\n\n\tcnst := constructor(language)\n\tif cnst == nil {\n\t\treturn nil, fmt.Errorf(\"invalid compiler language: %s\", language)\n\t}\n\n\tcmp, err := cnst()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create compiler: %s\", err)\n\t}\n\n\treturn cmp, nil\n}", "func (p *Project) Build(name string) (string, error) {\n\t// check layout\n\tif !(slices.Contains(p.Layout, V3) || slices.Contains(p.Layout, V4alpha)) {\n\t\treturn \"\", fmt.Errorf(\"project layout %v is not supported\", p.Layout)\n\t}\n\n\tk, err := kustomize.ParseKustomization(filepath.Join(p.path, defaultKustomization))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// create output folders\n\tpieces := strings.Split(name, \"/\")\n\tmoduleName := pieces[len(pieces)-1] // always return the last part of the path\n\tmanifestsPath := filepath.Join(p.path, OutputPath, moduleName)\n\n\tif err := os.MkdirAll(manifestsPath, os.ModePerm); err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not create chart templates output dir: %w\", err)\n\t}\n\n\t// do build\n\tyml, err := kustomize.Build(k)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trenderedManifestPath := filepath.Join(manifestsPath, \"rendered.yaml\")\n\tif err := os.WriteFile(renderedManifestPath, yml, os.ModePerm); err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not write rendered kustomization as yml to %s: %w\", manifestsPath, err)\n\t}\n\n\treturn renderedManifestPath, nil\n}", "func (p rProjects) ByName(name, owner string) (*schema.Project, error) {\n\tvar project schema.Project\n\trql := model.Projects.T().GetAllByIndex(\"name\", name).Filter(r.Row.Field(\"owner\").Eq(owner))\n\tif err := model.Projects.Qs(p.session).Row(rql, &project); err != nil {\n\t\treturn nil, mcerr.ErrNotFound\n\t}\n\treturn &project, nil\n}", "func Compile(ctx context.Context, cln *client.Client, w io.Writer, mod *ast.Module, targets []codegen.Target) (solver.Request, error) {\n\terr := checker.SemanticPass(mod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = linter.Lint(ctx, mod)\n\tif err != nil {\n\t\tfor _, span := range diagnostic.Spans(err) {\n\t\t\tfmt.Fprintln(w, span.Pretty(ctx))\n\t\t}\n\t}\n\n\terr = checker.Check(mod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolver, err := module.NewResolver(cln)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcg := codegen.New(cln, resolver)\n\tif solver.ConcurrencyLimiter(ctx) == nil {\n\t\tctx = solver.WithConcurrencyLimiter(ctx, semaphore.NewWeighted(defaultMaxConcurrency))\n\t}\n\treturn cg.Generate(ctx, mod, targets)\n}", "func (c *Compiler) CompileOne(query Body) (Body, error) {\n\n\tkey := string(Wildcard.Value.(Var))\n\n\tmod := &Module{\n\t\tPackage: &Package{\n\t\t\tPath: Ref{DefaultRootDocument},\n\t\t\tLocation: query.Loc(),\n\t\t},\n\t\tRules: []*Rule{\n\t\t\t&Rule{\n\t\t\t\tName: Var(key),\n\t\t\t\tBody: query,\n\t\t\t\tLocation: query.Loc(),\n\t\t\t},\n\t\t},\n\t}\n\n\tc.Modules[key] = mod\n\tc.compile()\n\n\tif c.Failed() {\n\t\treturn nil, c.Errors[0]\n\t}\n\n\treturn c.Modules[key].Rules[0].Body, nil\n}", "func (mem *Mem) Compile() error {\n\tchanged := true\n\tvisited := make(map[int]bool)\n\tfor changed {\n\t\tchanged = false\n\t\tfor state := range mem.patterns {\n\t\t\tif visited[state] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvisited[state] = true\n\t\t\tif err := compile(mem, state); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tchanged = true\n\t\t}\n\t}\n\treturn nil\n}", "func (c *CompiledTemplatesProgram) Compile(config *compiled.Configuration) (string, error) {\n\tif err := updateOutPkg(config); err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttemplatesToCompile, err := c.getTemplatesToCompile(config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn c.compileTemplates(config.OutPkg, templatesToCompile)\n}", "func (domain *Domain) GetSolution(name string) (*Solution, error) {\n\t// determine solution\n\tdomain.SolutionsX.RLock()\n\tsolution, ok := domain.Solutions[name]\n\tdomain.SolutionsX.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"solution not found\")\n\t}\n\n\t// success\n\treturn solution, nil\n}", "func (l *loader) compile(name string) (string, error) {\n // Copy the file to the objects directory with a different name\n // each time, to avoid retrieving the cached version.\n // Apparently the cache key is the path of the file compiled and\n // there's no way to invalidate it.\n\n f, err := ioutil.ReadFile(filepath.Join(l.pluginsDir, name + \".go\"))\n if err != nil {\n return \"\", fmt.Errorf(\"Cannot read %s.go: %v\", name, err)\n }\n\n name = fmt.Sprintf(\"%d.go\", rand.Int())\n srcPath := filepath.Join(l.objectsDir, name)\n if err := ioutil.WriteFile(srcPath, f, 0666); err != nil {\n return \"\", fmt.Errorf(\"Cannot write %s: %v\", name, err)\n }\n\n objectPath := srcPath[:len(srcPath)-3] + \".so\"\n\n cmd := exec.Command(\"go\", \"build\", \"-buildmode=plugin\", \"-o=\"+objectPath, srcPath)\n cmd.Stderr = os.Stderr\n cmd.Stdout = os.Stdout\n if err := cmd.Run(); err != nil {\n return \"\", fmt.Errorf(\"Cannot compile %s: %v\", name, err)\n }\n\n return objectPath, nil\n}", "func Create(ctx context.Context, name string, opts map[string]interface{}) (Solver, error) {\n\tcreatorMu.RLock()\n\tc, ok := creators[name]\n\tcreatorMu.RUnlock()\n\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%s solver creator not registered\", name)\n\t}\n\n\ts, err := c.Create(ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Logger.Debugf(\"%s solver created\", name)\n\treturn s, nil\n}", "func CompileSingle(fname, s string, golike bool) (\n\t[]byte, []*lex8.Error, []byte,\n) {\n\treturn buildSingle(fname, s, Lang(golike), new(build8.Options))\n}", "func (_BREMFactory *BREMFactoryCaller) GetProjectByName(opts *bind.CallOpts, _projectName string) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _BREMFactory.contract.Call(opts, out, \"getProjectByName\", _projectName)\n\treturn *ret0, err\n}", "func (s *Service) FindByName(name string) ([]*entity.Project, error) {\n\treturn s.repo.FindByName(name)\n}", "func MustCompile(name, src string, strict bool) *Program {\n\tprg, err := Compile(name, src, strict)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn prg\n}", "func (repo *repo) GetProjectByName(projectName string) (*models.Project, error) {\n\tlog.Debugf(\"GetProject - projectName: %s\", projectName)\n\ttableName := fmt.Sprintf(\"cla-%s-projects\", repo.stage)\n\n\t// This is the key we want to match\n\tcondition := expression.Key(\"project_name_lower\").Equal(expression.Value(strings.ToLower(projectName)))\n\n\t// Use the builder to create the expression\n\texpr, err := expression.NewBuilder().WithKeyCondition(condition).WithProjection(buildProjection()).Build()\n\tif err != nil {\n\t\tlog.Warnf(\"error building expression for Project query, projectName: %s, error: %v\",\n\t\t\tprojectName, err)\n\t\treturn nil, err\n\t}\n\n\t// Assemble the query input parameters\n\tqueryInput := &dynamodb.QueryInput{\n\t\tKeyConditionExpression: expr.KeyCondition(),\n\t\tExpressionAttributeNames: expr.Names(),\n\t\tExpressionAttributeValues: expr.Values(),\n\t\tProjectionExpression: expr.Projection(),\n\t\tTableName: aws.String(tableName),\n\t\tIndexName: aws.String(\"project-name-lower-search-index\"),\n\t}\n\n\t// Make the DynamoDB Query API call\n\tresults, queryErr := repo.dynamoDBClient.Query(queryInput)\n\tif queryErr != nil {\n\t\tlog.Warnf(\"error retrieving project by projectName: %s, error: %v\", projectName, queryErr)\n\t\treturn nil, queryErr\n\t}\n\n\t// Should only have one result\n\tif *results.Count > 1 {\n\t\tlog.Warnf(\"Project scan by name returned more than one result using projectName: %s\", projectName)\n\t}\n\n\t// Didn't find it...\n\tif *results.Count == 0 {\n\t\tlog.Debugf(\"Project scan by name returned no results using projectName: %s\", projectName)\n\t\treturn nil, nil\n\t}\n\n\t// Found it...\n\tvar dbModel DBProjectModel\n\terr = dynamodbattribute.UnmarshalMap(results.Items[0], &dbModel)\n\tif err != nil {\n\t\tlog.Warnf(\"error unmarshalling db project model, error: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\t// Convert the database model to an API response model\n\treturn repo.buildProjectModel(dbModel), nil\n}", "func (l *Result) Compiler() (*ast.Compiler, error) {\n\tcompiler := ast.NewCompiler()\n\tcompiler.Compile(l.ParsedModules())\n\tif compiler.Failed() {\n\t\treturn nil, compiler.Errors\n\t}\n\treturn compiler, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetCompilationRootDir returns directory of all compiled solutions.
func (cptool *CPTool) GetCompilationRootDir() string { return path.Join(cptool.workingDirectory, ".cptool/solutions") }
[ "func GetRootProjectDir() (string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor !strings.HasSuffix(wd, \"git2consul-go\") {\n\t\tif wd == \"/\" {\n\t\t\treturn \"\", errors.New(`cannot find project directory, \"/\" reached`)\n\t\t}\n\t\twd = filepath.Dir(wd)\n\t}\n\treturn wd, nil\n}", "func (pr *SProjectRoot) GetProjectRootDirectory() string {\n\tprojectRootDirectory := pr.projectRootDirectory\n\n\treturn projectRootDirectory\n}", "func (d Dependency) WorkdirRoot() string {\n\treturn filepath.Join(d.Gopath(), \"src\", d.repoRoot.Root)\n}", "func (pr *SProjectRoot) GetProjectRootDirectoryName() string {\n\treturn pr.projectRootDirectoryName\n}", "func GetGoRootDir() string {\n\troseDir := GetRosieDir()\n\treturn path.Join(roseDir, goDirName)\n}", "func (o *Project) GetRootDirectory() string {\n\tif o == nil || o.RootDirectory == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.RootDirectory\n}", "func getProjectRoot() (string, error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error getting pwd: %s\", err)\n\t}\n\tfor {\n\t\tparent, name := filepath.Split(dir)\n\t\tif name == \"acr-builder\" {\n\t\t\tbreak\n\t\t}\n\t\tparent = filepath.Clean(parent)\n\t\tif parent == \"\" {\n\t\t\tpanic(\"no acr-builder directory find on pwd\")\n\t\t}\n\t\tdir = parent\n\t}\n\treturn dir, nil\n}", "func RootDir() string {\n\treturn environ.GetValueStrOrPanic(\"ROOT_DIR\")\n}", "func ProjectRoot() (path string) {\n\t_, err := ioutil.ReadFile(RootConfigFile)\n\tif err != nil {\n\t\tpath = setroot.Set(RootConfigFile, GlobalConfigDir())\n\t} else {\n\t\tdata, err := ioutil.ReadFile(RootConfigFile)\n\t\tif err != nil {\n\t\t\tstatuser.Error(\"Failed to read from global config file\", err, 1)\n\t\t}\n\t\tglobalConfig := struct {\n\t\t\tPath string `yaml:\"path\"`\n\t\t}{}\n\t\terr = yaml.Unmarshal(data, &globalConfig)\n\t\tif err != nil {\n\t\t\tstatuser.Error(\"Failed to parse yaml from global config file\", err, 1)\n\t\t}\n\t\tpath = globalConfig.Path\n\t}\n\treturn path\n}", "func repoRoot() (string, error) {\n\trepoRootState.once.Do(func() {\n\t\tif wsDir := os.Getenv(\"BUILD_WORKSPACE_DIRECTORY\"); wsDir != \"\" {\n\t\t\trepoRootState.dir = wsDir\n\t\t\treturn\n\t\t}\n\t\tdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\trepoRootState.err = err\n\t\t\treturn\n\t\t}\n\t\tfor {\n\t\t\t_, err := os.Stat(filepath.Join(dir, \"WORKSPACE\"))\n\t\t\tif err == nil {\n\t\t\t\trepoRootState.dir = dir\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != os.ErrNotExist {\n\t\t\t\trepoRootState.err = err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparent := filepath.Dir(dir)\n\t\t\tif parent == dir {\n\t\t\t\trepoRootState.err = errors.New(\"could not find workspace directory\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdir = parent\n\t\t}\n\t})\n\treturn repoRootState.dir, repoRootState.err\n}", "func RootDir() string {\r\n\treturn rootDir\r\n}", "func GetConfigRootDir() string {\n\tconfigFile := viper.GetString(\"viper.config_file\")\n\tif configFile == \"\" {\n\t\tcwd, _ := os.Getwd()\n\t\treturn cwd\n\t}\n\n\treturn path.Dir(configFile)\n}", "func (f *EnvTestFixture) RootDir() string {\n\treturn filepath.Join(f.State.Root(), \"pkg\")\n}", "func GetProjectRoot(wd string) (string, error) {\n\tsep := string(os.PathSeparator)\n\tparts := append(strings.SplitAfter(wd, sep), sep)\n\n\tfor i := len(parts) - 1; i >= 0; i-- {\n\t\tdir := filepath.Join(parts[:i]...)\n\t\tfile := filepath.Join(dir, projectFileName)\n\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\tlog.Debugf(\"Found project file at %s\", dir)\n\t\t\treturn dir, nil\n\t\t} else if os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn \"\", ErrNoProject\n}", "func (this *WorkDir) RootPath() string {\n\treturn this.path\n}", "func getBuildBaseDirectory(options *Options) (string, error) {\n\tbuildDirectory := filepath.Join(options.ProjectData.Path, \"build\")\n\tif !fs.DirExists(buildDirectory) {\n\t\terr := os.MkdirAll(buildDirectory, 0700)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn buildDirectory, nil\n}", "func (c *Container) RootDirectory() (string, error) {\n\t// The root directory of this container's runtime.\n\trootDir := fmt.Sprintf(\"/var/run/docker/runtime-%s/moby\", c.runtime)\n\t_, err := os.Stat(rootDir)\n\tif err == nil {\n\t\treturn rootDir, nil\n\t}\n\t// In docker v20+, due to https://github.com/moby/moby/issues/42345 the\n\t// rootDir seems to always be the following.\n\tconst defaultDir = \"/var/run/docker/runtime-runc/moby\"\n\t_, derr := os.Stat(defaultDir)\n\tif derr == nil {\n\t\treturn defaultDir, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"cannot stat %q: %v or %q: %v\", rootDir, err, defaultDir, derr)\n}", "func TemplateRootDir() (string, error) {\n\tconfig, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to get UserConfigDir\")\n\t}\n\n\ttmplPath := filepath.Join(config, \"suborbital\", \"templates\")\n\n\tif os.Stat(tmplPath); err != nil {\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\tif err := os.MkdirAll(tmplPath, os.ModePerm); err != nil {\n\t\t\t\treturn \"\", errors.Wrap(err, \"failed to MkdirAll template directory\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\", errors.Wrap(err, \"failed to Stat template directory\")\n\t\t}\n\t}\n\n\treturn tmplPath, nil\n}", "func GetRootPath() string {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn strings.Replace(dir, \"\\\\\", \"/\", -1)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if two query terms are equal
func (qt *queryTerm) equals(qt2 *queryTerm) bool { return qt.Subject == qt2.Subject && qt.Object == qt2.Object && reflect.DeepEqual(qt.Predicates, qt2.Predicates) }
[ "func isEqualTerms(a, b map[string]bool) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif !b[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (ref *Reference) IsEqual(other Query) bool {\n\tr := other.Ref()\n\n\t// check app instance\n\tif ref.database.app != r.database.app {\n\t\treturn false\n\t}\n\n\t// check location\n\tif ref.path != r.path {\n\t\treturn false\n\t}\n\n\t// check queries\n\tq1, q2 := url.Values{}, url.Values{}\n\tref.buildQuery(q1)\n\tr.buildQuery(q2)\n\tif len(q1) != len(q2) || q1.Encode() != q2.Encode() {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (term *Term) Equal(other *Term) bool {\n\tif term == nil && other != nil {\n\t\treturn false\n\t}\n\tif term != nil && other == nil {\n\t\treturn false\n\t}\n\tif term == other {\n\t\treturn true\n\t}\n\n\t// TODO(tsandall): This early-exit avoids allocations for types that have\n\t// Equal() functions that just use == underneath. We should revisit the\n\t// other types and implement Equal() functions that do not require\n\t// allocations.\n\tswitch v := term.Value.(type) {\n\tcase Null:\n\t\treturn v.Equal(other.Value)\n\tcase Boolean:\n\t\treturn v.Equal(other.Value)\n\tcase Number:\n\t\treturn v.Equal(other.Value)\n\tcase String:\n\t\treturn v.Equal(other.Value)\n\tcase Var:\n\t\treturn v.Equal(other.Value)\n\t}\n\n\treturn term.Value.Compare(other.Value) == 0\n}", "func allEq(doc string) bool {\n\n\tbase := doc[0]\n\tfor i := 1; i < len(doc); i++ {\n\t\tif base != doc[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (t Tags) eq(u Tags) bool {\n\tif len(t) != len(u) {\n\t\treturn false\n\t}\n\tfor i := range t {\n\t\tif t[i] != u[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func FQNameEquals(fqNameA, fqNameB []string) bool {\n\tif len(fqNameA) != len(fqNameB) {\n\t\treturn false\n\t}\n\tfor i, v := range fqNameA {\n\t\tif v != fqNameB[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func BoundQueriesEqual(x, y []BoundQuery) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tfor i := range x {\n\t\tif !BoundQueryEqual(&x[i], &y[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Eq(obj1 any, obj2 any) bool", "func (recv *TypeQuery) Equals(other *TypeQuery) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func QueryResponsesEqual(r1, r2 []QueryResponse) bool {\n\tif len(r1) != len(r2) {\n\t\treturn false\n\t}\n\tfor i, r := range r1 {\n\t\tif !r.QueryResult.Equal(r2[i].QueryResult) {\n\t\t\treturn false\n\t\t}\n\t\tif !reflect.DeepEqual(r.QueryError, r2[i].QueryError) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (e Word) EqualsTo(another *Word) bool {\n\tif e.text != another.text {\n\t\treturn false\n\t} else if !e.grammemes.EqualTo(another.grammemes) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (q Query) SequenceEqual(q2 Query) bool {\n\tnext := q.Iterate()\n\tnext2 := q2.Iterate()\n\n\tfor item, ok := next(); ok; item, ok = next() {\n\t\titem2, ok2 := next2()\n\t\tif !ok2 || item != item2 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t_, ok2 := next2()\n\treturn !ok2\n}", "func Equal(t1, t2 Token) bool {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tif t1 == nil && t2 == nil {\n\t\treturn true\n\t}\n\n\t// we already checked for t1 == t2 == nil, so safe to do this\n\tif t1 == nil || t2 == nil {\n\t\treturn false\n\t}\n\n\tm1, err := t1.AsMap(ctx)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfor iter := t2.Iterate(ctx); iter.Next(ctx); {\n\t\tpair := iter.Pair()\n\n\t\tv1 := m1[pair.Key.(string)]\n\t\tv2 := pair.Value\n\t\tswitch tmp := v1.(type) {\n\t\tcase time.Time:\n\t\t\ttmp2, ok := v2.(time.Time)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\ttmp = tmp.Round(0).Truncate(time.Second)\n\t\t\ttmp2 = tmp2.Round(0).Truncate(time.Second)\n\t\t\tif !tmp.Equal(tmp2) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tdefault:\n\t\t\tif v1 != v2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tdelete(m1, pair.Key.(string))\n\t}\n\n\treturn len(m1) == 0\n}", "func Quat2Equals(a, b []float64) bool {\n\treturn equals(a[0], b[0]) &&\n\t\tequals(a[1], b[1]) &&\n\t\tequals(a[2], b[2]) &&\n\t\tequals(a[3], b[3]) &&\n\t\tequals(a[4], b[4]) &&\n\t\tequals(a[5], b[5]) &&\n\t\tequals(a[6], b[6]) &&\n\t\tequals(a[7], b[7])\n}", "func (recv *SignalQuery) Equals(other *SignalQuery) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func IsEqual(eq string) bool {\n var equalsIndex int = strings.Index(eq, \"=\")\n var lhs string = eq[0:equalsIndex]\n var rhs string = eq[equalsIndex + 1:]\n var side1 float64 = NotateToDouble(Pemdas(lhs))\n var side2 float64 = NotateToDouble(Pemdas(rhs))\n\n return side1 == side2\n}", "func equalsRest(a, b language.Tag) bool {\n\t// TODO: don't include extensions in this comparison. To do this efficiently,\n\t// though, we should handle private tags separately.\n\treturn a.ScriptID == b.ScriptID && a.RegionID == b.RegionID && a.VariantOrPrivateUseTags() == b.VariantOrPrivateUseTags()\n}", "func (q Quat) Equals(other Quat) bool {\n\treturn q.EqualsEps(other, Epsilon)\n}", "func Quat2ExactEquals(a, b []float64) bool {\n\treturn a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] && a[4] == b[4] && a[5] == b[5] && a[6] == b[6] && a[7] == b[7]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EditRelease edit a release object within the GitHub API
func (c *Client) EditRelease(ctx context.Context, releaseID int64, req *github.RepositoryRelease) (*github.RepositoryRelease, error) { var release *github.RepositoryRelease err := retry.Retry(3, 3*time.Second, func() error { var ( res *github.Response err error ) release, res, err = c.Repositories.EditRelease(context.TODO(), c.Owner, c.Repo, releaseID, req) if err != nil { return errors.Wrapf(err, "failed to edit release: %d", releaseID) } if res.StatusCode != http.StatusOK { return errors.Errorf("edit release: invalid status: %s", res.Status) } return nil }) return release, err }
[ "func EditRelease(ctx *context.APIContext) {\n\t// swagger:operation PATCH /repos/{owner}/{repo}/releases/{id} repository repoEditRelease\n\t// ---\n\t// summary: Update a release\n\t// consumes:\n\t// - application/json\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: id\n\t// in: path\n\t// description: id of the release to edit\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// - name: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/EditReleaseOption\"\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Release\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/notFound\"\n\n\tform := web.GetForm(ctx).(*api.EditReleaseOption)\n\tid := ctx.ParamsInt64(\":id\")\n\trel, err := repo_model.GetReleaseByID(ctx, id)\n\tif err != nil && !repo_model.IsErrReleaseNotExist(err) {\n\t\tctx.Error(http.StatusInternalServerError, \"GetReleaseByID\", err)\n\t\treturn\n\t}\n\tif err != nil && repo_model.IsErrReleaseNotExist(err) ||\n\t\trel.IsTag || rel.RepoID != ctx.Repo.Repository.ID {\n\t\tctx.NotFound()\n\t\treturn\n\t}\n\n\tif len(form.TagName) > 0 {\n\t\trel.TagName = form.TagName\n\t}\n\tif len(form.Target) > 0 {\n\t\trel.Target = form.Target\n\t}\n\tif len(form.Title) > 0 {\n\t\trel.Title = form.Title\n\t}\n\tif len(form.Note) > 0 {\n\t\trel.Note = form.Note\n\t}\n\tif form.IsDraft != nil {\n\t\trel.IsDraft = *form.IsDraft\n\t}\n\tif form.IsPrerelease != nil {\n\t\trel.IsPrerelease = *form.IsPrerelease\n\t}\n\tif err := release_service.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, nil, nil, nil); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"UpdateRelease\", err)\n\t\treturn\n\t}\n\n\t// reload data from database\n\trel, err = repo_model.GetReleaseByID(ctx, id)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetReleaseByID\", err)\n\t\treturn\n\t}\n\tif err := rel.LoadAttributes(ctx); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"LoadAttributes\", err)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, convert.ToAPIRelease(ctx, ctx.Repo.Repository, rel))\n}", "func (a *Client) RepoEditRelease(params *RepoEditReleaseParams, authInfo runtime.ClientAuthInfoWriter) (*RepoEditReleaseOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRepoEditReleaseParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"repoEditRelease\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/repos/{owner}/{repo}/releases/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &RepoEditReleaseReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*RepoEditReleaseOK), nil\n\n}", "func (s *ReleaseService) UpdateRelease(id uint, r *Release, t ReleaseType, authToken string) (*Release, error) {\n\tvar (\n\t\tmethod = http.MethodPatch\n\t\tpath = fmt.Sprintf(\"/releases/%d\", id)\n\t)\n\treq := s.client.newRequest(path, method)\n\taddJWTToRequest(req, authToken)\n\tr.Type = t\n\terr := addBodyToRequestAsJSON(req, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.updateRelease(req)\n}", "func (client *ClientImpl) UpdateRelease(ctx context.Context, args UpdateReleaseArgs) (*Release, error) {\n\tif args.Release == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.Release\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.Project == nil || *args.Project == \"\" {\n\t\treturn nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.Project\"}\n\t}\n\trouteValues[\"project\"] = *args.Project\n\tif args.ReleaseId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ReleaseId\"}\n\t}\n\trouteValues[\"releaseId\"] = strconv.Itoa(*args.ReleaseId)\n\n\tbody, marshalErr := json.Marshal(*args.Release)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"a166fde7-27ad-408e-ba75-703c2cc9d500\")\n\tresp, err := client.Client.Send(ctx, http.MethodPut, locationId, \"7.1-preview.8\", routeValues, nil, bytes.NewReader(body), \"application/json\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue Release\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (operator *AccessOperator) UpdateRelease(cxt context.Context, option *ReleaseOption) error {\n\t//business first\n\tbusiness, _, err := getBusinessAndApp(operator, operator.Business, option.AppName)\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest := &accessserver.UpdateReleaseReq{\n\t\tSeq: pkgcommon.Sequence(),\n\t\tBid: business.Bid,\n\t\tReleaseid: option.ReleaseID,\n\t\tName: option.Name,\n\t\tOperator: operator.User,\n\t}\n\tgrpcOptions := []grpc.CallOption{\n\t\tgrpc.WaitForReady(true),\n\t}\n\tresponse, err := operator.Client.UpdateRelease(cxt, request, grpcOptions...)\n\tif err != nil {\n\t\tlogger.V(3).Infof(\"UpdateRelease %s failed, %s\", option.Name, err.Error())\n\t\treturn err\n\t}\n\tif response.ErrCode != common.ErrCode_E_OK {\n\t\tlogger.V(3).Infof(\"UpdateRelease %s successfully, but response Err, %s\", option.ReleaseID, response.ErrMsg)\n\t\treturn fmt.Errorf(\"%s\", response.ErrMsg)\n\t}\n\treturn nil\n\n}", "func (a *Client) UpdateReleaseResource(params *UpdateReleaseResourceParams, authInfo runtime.ClientAuthInfoWriter) (*UpdateReleaseResourceOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateReleaseResourceParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Update Release Resource\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/{organization}/{project}/_apis/release/releases/{releaseId}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &UpdateReleaseResourceReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*UpdateReleaseResourceOK), nil\n\n}", "func (client *ClientImpl) UpdateReleaseResource(ctx context.Context, args UpdateReleaseResourceArgs) (*Release, error) {\n\tif args.ReleaseUpdateMetadata == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ReleaseUpdateMetadata\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.Project == nil || *args.Project == \"\" {\n\t\treturn nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.Project\"}\n\t}\n\trouteValues[\"project\"] = *args.Project\n\tif args.ReleaseId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ReleaseId\"}\n\t}\n\trouteValues[\"releaseId\"] = strconv.Itoa(*args.ReleaseId)\n\n\tbody, marshalErr := json.Marshal(*args.ReleaseUpdateMetadata)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"a166fde7-27ad-408e-ba75-703c2cc9d500\")\n\tresp, err := client.Client.Send(ctx, http.MethodPatch, locationId, \"7.1-preview.8\", routeValues, nil, bytes.NewReader(body), \"application/json\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue Release\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (c *Client) Release(ctx context.Context, repo *gogh.Repo, tag string) (*github.RepositoryRelease, error) {\n\trelease, _, err := c.client.Repositories.GetReleaseByTag(ctx, repo.Owner(), repo.Name(), tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn release, nil\n}", "func (c *githubNotesReplayClient) UpdateReleasePage(\n\tctx context.Context, owner, repo string, releaseID int64, releaseData *github.RepositoryRelease, //nolint: revive\n) (*github.RepositoryRelease, error) {\n\treturn &github.RepositoryRelease{}, nil\n}", "func (p Database) Edit(d interface{}) (string, error) {\n\tjsonBuf, err := json.Marshal(d)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tidRev := idAndRev{}\n\tmust(json.Unmarshal(jsonBuf, &idRev))\n\tif idRev.ID == \"\" {\n\t\treturn \"\", errNoID\n\t}\n\tif idRev.Rev == \"\" {\n\t\treturn \"\", errNoRev\n\t}\n\tu := fmt.Sprintf(\"%s/%s\", p.DBURL(), url.QueryEscape(idRev.ID))\n\tir := Response{}\n\tif _, err = interact(\"PUT\", u, p.defaultHdrs, jsonBuf, &ir); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ir.Rev, nil\n}", "func Release(version, commit, date string) {\n\tif version == \"\" {\n\t\tversion = \"dev\"\n\t} else if version[0] == 'v' {\n\t\tversion = version[1:]\n\t}\n\tif commit == \"\" {\n\t\tcommit = \"-\"\n\t}\n\tif date == \"\" {\n\t\tdate = \"-\"\n\t}\n\tVersion, Commit, Date = version, commit, date\n}", "func (c *gitlabClient) CreateRelease(ctx *context.Context, body string) (releaseID string, err error) {\n\ttitle, err := tmpl.New(ctx).Apply(ctx.Config.Release.NameTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprojectID := ctx.Config.Release.GitLab.Owner + \"/\" + ctx.Config.Release.GitLab.Name\n\tlog.WithFields(log.Fields{\n\t\t\"owner\": ctx.Config.Release.GitLab.Owner,\n\t\t\"name\": ctx.Config.Release.GitLab.Name,\n\t}).Debug(\"projectID\")\n\n\tname := title\n\ttagName := ctx.Git.CurrentTag\n\trelease, resp, err := c.client.Releases.GetRelease(projectID, tagName)\n\tif err != nil && resp.StatusCode != 403 {\n\t\treturn \"\", err\n\t}\n\n\tif resp.StatusCode == 403 {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t}).Debug(\"get release\")\n\n\t\tdescription := body\n\t\tref := ctx.Git.Commit\n\t\tgitURL := ctx.Git.URL\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"name\": name,\n\t\t\t\"description\": description,\n\t\t\t\"ref\": ref,\n\t\t\t\"url\": gitURL,\n\t\t}).Debug(\"creating release\")\n\t\trelease, _, err = c.client.Releases.CreateRelease(projectID, &gitlab.CreateReleaseOptions{\n\t\t\tName: &name,\n\t\t\tDescription: &description,\n\t\t\tRef: &ref,\n\t\t\tTagName: &tagName,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Debug(\"error create release\")\n\t\t\treturn \"\", err\n\t\t}\n\t\tlog.WithField(\"name\", release.Name).Info(\"release created\")\n\t} else {\n\t\tdesc := body\n\t\tif release != nil && release.DescriptionHTML != \"\" {\n\t\t\tdesc = release.DescriptionHTML\n\t\t}\n\n\t\trelease, _, err = c.client.Releases.UpdateRelease(projectID, tagName, &gitlab.UpdateReleaseOptions{\n\t\t\tName: &name,\n\t\t\tDescription: &desc,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Debug(\"error update release\")\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tlog.WithField(\"name\", release.Name).Info(\"release updated\")\n\t}\n\n\treturn tagName, err // gitlab references a tag in a repo by its name\n}", "func (s *Services) Release(ctx context.Context, request *proto.ReleaseRequest) (*proto.ReleaseResponse, error) {\n\tvar result models.Release\n\tquery := s.DB\n\n\tif request.Id != 0 {\n\t\tquery = query.Where(\"id = ?\", request.Id)\n\t}\n\n\tif err := query.First(&result).Error; err != nil {\n\n\t\t// If nothing was found\n\t\tif gorm.IsRecordNotFoundError(err) {\n\t\t\treturn &proto.ReleaseResponse{Release: nil}, nil\n\t\t}\n\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\treturn &proto.ReleaseResponse{Release: result.ToProto()}, nil\n}", "func handleGithubRelease(wh Webhook) {\n\tif wh.Action != \"published\" {\n\t\treturn\n\t}\n\tvar payload discord.APIEmbedPayload\n\t_ = payload.Prepare(map[string]interface{}{\n\t\t\"color\": 0xF9B200,\n\t\t\"title\": fmt.Sprintf(\"%v (%v)\", wh.Release.Name, wh.Release.TagName),\n\t\t// \"url\": \"https://jexia.com\",\n\t\t\"author\": map[string]string{\n\t\t\t\"name\": fmt.Sprintf(\"New release of %v\", wh.Repository.FullName),\n\t\t\t\"icon_url\": wh.Repository.Owner.AvatarURL,\n\t\t\t\"url\": wh.Release.HTMLURL,\n\t\t},\n\t\t\"timestamp\": wh.Release.PublishedAt,\n\t\t\"description\": wh.Release.Body,\n\t\t// TODO: Loop though download links / files\n\t\t// \"fields\": []interface{}{\n\t\t// \tmap[string]interface{}{\n\t\t// \t\t\"name\": \"Assets\",\n\t\t// \t\t\"value\": \"Some value here\",\n\t\t// \t\t\"inline\": false,\n\t\t// \t},\n\t\t// },\n\t\t\"footer\": map[string]string{\n\t\t\t\"text\": \"Sent via Github\",\n\t\t},\n\t}, wh.ChannelID)\n\n\tevents.Queue.Publish(\"discord.send_response\", payload)\n}", "func (a *Client) RepoEditReleaseAttachment(params *RepoEditReleaseAttachmentParams, authInfo runtime.ClientAuthInfoWriter) (*RepoEditReleaseAttachmentCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewRepoEditReleaseAttachmentParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"repoEditReleaseAttachment\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/repos/{owner}/{repo}/releases/{id}/assets/{attachment_id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &RepoEditReleaseAttachmentReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*RepoEditReleaseAttachmentCreated), nil\n\n}", "func (h *handler) Release(ctx context.Context, evt *github.ReleaseEvent) error {\n\tif evt.GetAction() != \"released\" {\n\t\tlogrus.WithField(\"action\", evt.GetAction()).Info(\"ignoring release event\")\n\t\treturn nil\n\t}\n\tnotifyRepos := h.cfg.ReleaseDispatchRepos()\n\tlogrus.WithField(\"repos\", len(notifyRepos)).Info(\"notifying repositories of release\")\n\tif len(notifyRepos) == 0 {\n\t\treturn nil\n\t}\n\n\tgh := repo.NewGitHubClient(h.cfg.GitHubToken)\n\tfeedbackIssue, err := releaseFeedbackIssue(ctx, gh, evt, notifyRepos)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogrus.WithField(\"issue_number\", feedbackIssue.Number).Debug(\"created feedback issue\")\n\n\tdispatchOpts, err := h.releaseDispatchOptions(evt, feedbackIssue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, notifyRepo := range notifyRepos {\n\t\tnotifyRepoParts := strings.SplitN(notifyRepo, \"/\", 2)\n\t\towner := notifyRepoParts[0]\n\t\tname := notifyRepoParts[1]\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"owner\": owner,\n\t\t\t\"name\": name,\n\t\t}).Debug(\"dispatching release to repository\")\n\t\tif _, _, err := gh.Repositories.Dispatch(ctx, owner, name, dispatchOpts); err != nil {\n\t\t\tlogrus.WithError(err).Warn(\"error dispatching update\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func createRelease(auth *UserAuth, gURL *gitURL, tag, tagMessage, commitish string, draft, prerelease bool) (*release, error) {\n\tvar newRelease release\n\n\t// TEMP RELEASES URL HERE; LEARN TO TEMPLATE AND USE githubEndpoint.ReleasesURL\n\treleasesURL := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/releases\", gURL.organization, gURL.repository)\n\n\theaders := make(map[string]string)\n\theaders[\"Authorization\"] = fmt.Sprintf(\"%s %s\", auth.TokenType, auth.AccessToken)\n\n\treleaseRequest := &newReleaseRequest{\n\t\tTagName: tag,\n\t\tName: tag,\n\t\tBody: tagMessage,\n\t\tDraft: draft,\n\t\tPrerelease: prerelease,\n\t}\n\n\tif commitish != \"\" {\n\t\treleaseRequest.TargetCommitish = commitish\n\t}\n\n\tdata, err := json.Marshal(releaseRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := newPostRequest(releasesURL, bytes.NewBuffer(data), headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// make the request\n\t// If there's an error here, wait until after trying to unmarshal the body from JSON\n\t// so we might get an indication of the issue\n\tbody, requestErr := makeHTTPRequest(req)\n\n\tif err := json.Unmarshal(body, &newRelease); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// unmarshal the raw data\n\tif err = json.Unmarshal(body, &newRelease.raw); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif requestErr != nil {\n\t\tif verbose {\n\t\t\tnoteErr(fmt.Sprintf(\"%s - %v\", requestErr, &newRelease.raw))\n\t\t}\n\t\treturn &newRelease, requestErr\n\t}\n\n\treturn &newRelease, nil\n}", "func PostAdminEditVersion(c *gin.Context) {\n\tvar Version database.Version\n\tdatabase.Db.First(&Version, \"ID = ?\", c.Param(\"id\"))\n\tVersion.Slug = c.PostForm(\"slug\")\n\tVersion.Name = c.PostForm(\"name\")\n\tVersion.GitRepo = c.PostForm(\"gitrepo\")\n\tif ign := c.DefaultPostForm(\"ignore\", \"off\"); ign == \"off\" {\n\t\tVersion.Ignore = false\n\t} else {\n\t\tVersion.Ignore = true\n\t}\n\tid, err := uuid.FromString(c.PostForm(\"product\"))\n\tif err != nil {\n\t\tc.AbortWithError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tVersion.ProductID = id\n\tdatabase.Db.Save(&Version)\n\tc.Redirect(http.StatusFound, \"/admin/versions\")\n}", "func EditPost(req *http.Request, params martini.Params, res render.Render) {\n\tvar post Post\n\tpost.Slug = params[\"slug\"]\n\tpost, err := post.Get()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tres.JSON(500, map[string]interface{}{\"error\": \"Internal server error\"})\n\t\treturn\n\t}\n\tres.HTML(200, \"post/edit\", post)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UploadAsset uploads specified assets to a given release object
func (c *Client) UploadAsset(ctx context.Context, releaseID int64, filename string) (*github.ReleaseAsset, error) { filename, err := filepath.Abs(filename) if err != nil { return nil, errors.Wrap(err, "failed to get abs path") } f, err := os.Open(filename) if err != nil { return nil, errors.Wrap(err, "failed to open file") } opts := &github.UploadOptions{ // Use base name by default Name: filepath.Base(filename), } var asset *github.ReleaseAsset err = retry.Retry(3, 3*time.Second, func() error { var ( res *github.Response err error ) asset, res, err = c.Repositories.UploadReleaseAsset(context.TODO(), c.Owner, c.Repo, releaseID, opts, f) if err != nil { return errors.Wrapf(err, "failed to upload release asset: %s", filename) } switch res.StatusCode { case http.StatusCreated: return nil case 422: return errors.Errorf( "upload release asset: invalid status code: %s", "422 (this is probably because the asset already uploaded)") default: return errors.Errorf( "upload release asset: invalid status code: %s", res.Status) } }) return asset, err }
[ "func (r *Release) UploadAsset(path string) error {\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tasset, _, err := r.client.Repositories.UploadReleaseAsset(context.Background(), r.owner, r.repository, r.ID, &gogithub.UploadOptions{\n\t\tName: filepath.Base(file.Name()),\n\t}, file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"uploaded asset \", *asset.Name)\n\treturn nil\n}", "func (c *githubNotesReplayClient) UploadReleaseAsset(\n\tcontext.Context, string, string, int64, *github.UploadOptions, *os.File,\n) (*github.ReleaseAsset, error) {\n\treturn &github.ReleaseAsset{}, nil\n}", "func (g *GHR) UploadAssets(ctx context.Context, releaseID int64, localAssets []string, parallel int) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tDebugf(\"UploadAssets: time: %d ms\", int(time.Since(start).Seconds()*1000))\n\t}()\n\n\teg, ctx := errgroup.WithContext(ctx)\n\tsemaphore := make(chan struct{}, parallel)\n\tfor _, localAsset := range localAssets {\n\t\tlocalAsset := localAsset\n\t\teg.Go(func() error {\n\t\t\tsemaphore <- struct{}{}\n\t\t\tdefer func() {\n\t\t\t\t<-semaphore\n\t\t\t}()\n\n\t\t\tfmt.Fprintf(g.outStream, \"--> Uploading: %15s\\n\", filepath.Base(localAsset))\n\t\t\t_, err := g.GitHub.UploadAsset(ctx, releaseID, localAsset)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to upload asset: %s %w\", localAsset, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif err := eg.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"one of the goroutines failed: %w\", err)\n\t}\n\n\treturn nil\n}", "func (c *gitlabClient) Upload(\n\tctx *context.Context,\n\treleaseID string,\n\tname string,\n\tfile *os.File,\n) error {\n\tprojectID := ctx.Config.Release.GitLab.Owner + \"/\" + ctx.Config.Release.GitLab.Name\n\n\tlog.WithField(\"file\", file.Name()).Debug(\"uploading file\")\n\tprojectFile, _, err := c.client.Projects.UploadFile(\n\t\tprojectID,\n\t\tfile.Name(),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"file\": file.Name(),\n\t\t\"url\": projectFile.URL,\n\t}).Debug(\"uploaded file\")\n\n\tgitlabBaseURL := ctx.Config.GitLabURLs.Download\n\t// projectFile from upload: /uploads/<sha>/filename.txt\n\trelativeUploadURL := projectFile.URL\n\tlinkURL := gitlabBaseURL + \"/\" + projectID + relativeUploadURL\n\treleaseLink, _, err := c.client.ReleaseLinks.CreateReleaseLink(\n\t\tprojectID,\n\t\treleaseID,\n\t\t&gitlab.CreateReleaseLinkOptions{\n\t\t\tName: &name,\n\t\t\tURL: &linkURL,\n\t\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"id\": releaseLink.ID,\n\t\t\"url\": releaseLink.URL,\n\t}).Debug(\"created release link\")\n\n\treturn err\n}", "func PutAssets(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {\n\treturn handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {\n\t\trequestBody := client.PutGraphAssetRequestBody{}\n\t\tif err := json.NewDecoder(body).Decode(&requestBody); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO(c.michaud): verify compatibility of the schema with graph updates\n\t\terr := graphUpdater.InsertAssets(ctx, source, requestBody.Assets)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to insert assets: %v\", err)\n\t\t}\n\t\tlabels := prometheus.Labels{\"source\": source}\n\t\tmetrics.GraphUpdateAssetsInsertedCounter.\n\t\t\tWith(labels).\n\t\t\tAdd(float64(len(requestBody.Assets)))\n\n\t\treturn nil\n\t}, sem, \"insert_assets\")\n}", "func (u *UploadsService) UploadAsset(asset io.ReadCloser, contentType string, contentLength int64) (result *Result) {\n\treturn u.client.upload(u.URL, asset, contentType, contentLength)\n}", "func (m *MockRealmClient) UploadAsset(groupID, appID, path, hash string, size int64, body io.Reader, attributes ...hosting.AssetAttribute) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{groupID, appID, path, hash, size, body}\n\tfor _, a := range attributes {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UploadAsset\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func UploadReleaseAttachment(ctx *context.Context) {\n\tuploadAttachment(ctx, ctx.Repo.Repository.ID, setting.Repository.Release.AllowedTypes)\n}", "func UploadAssets(app *parser.MobileApp, bucket, destBaseDir string) ([]string, error) {\n\t// create the site path names and assume the url before uploaded for templating\n\tbuildDir := destBaseDir + \"/\" + app.Version + \"/\" + app.Build\n\tappIconPath := buildDir + \"/\" + parser.AppIconFile\n\tappSitePath := buildDir + \"/\" + filepath.Base(app.File)\n\tappIndexHTMLSitePath := buildDir + \"/\" + parser.IndexHTMLFile\n\tbucketHTTPSurl := \"https://\" + bucket + \".s3.amazonaws.com\"\n\tapp.DownloadURL = bucketHTTPSurl + \"/\" + appSitePath\n\n\t// default directory of assets\n\tassetsDir := parser.AndroidAssetsDir\n\t// specific for ios\n\tvar appPlistSitePath string\n\tif app.IsIOS() {\n\t\tassetsDir = parser.IOSAssetsDir\n\t\tappPlistSitePath = buildDir + \"/\" + parser.IOSPlistFile\n\t\tapp.PlistURL = htmltemp.URL(bucketHTTPSurl + \"/\" + appPlistSitePath)\n\t}\n\n\t// create the assets\n\tassets := []string{}\n\tif err := app.GenerateAssets(); err != nil {\n\t\treturn assets, err\n\t}\n\n\tuploads := []Upload{\n\t\t{bucket, assetsDir + \"/\" + parser.AppIconFile, appIconPath},\n\t\t{bucket, assetsDir + \"/\" + parser.VersionJsonFile, destBaseDir + \"/\" + app.Version + \"/\" + parser.VersionJsonFile},\n\t\t{bucket, assetsDir + \"/\" + parser.IndexHTMLFile, appIndexHTMLSitePath},\n\t\t{bucket, app.File, appSitePath},\n\t}\n\n\tif app.IsIOS() {\n\t\tuploads = append(uploads, Upload{bucket, assetsDir + \"/\" + parser.IOSPlistFile, appPlistSitePath})\n\t}\n\n\tfor _, upload := range uploads {\n\t\tfileURL, err := UploadFile(upload)\n\t\tif err != nil {\n\t\t\treturn assets, err\n\t\t}\n\t\t// Ensure the returned string is a decoded url\n\t\tdecodedURL, err := url.QueryUnescape(fileURL)\n\t\tif err != nil {\n\t\t\treturn assets, err\n\t\t}\n\t\tassets = append(assets, decodedURL)\n\t}\n\n\treturn assets, nil\n}", "func (h Hosting) UploadHostingAssets(realmClient realm.Client, groupID, appID string, hostingDiffs HostingDiffs, errHandler func(err error)) error {\n\tvar wg sync.WaitGroup\n\n\tjobCh := make(chan func())\n\terrCh := make(chan error)\n\tdoneCh := make(chan struct{})\n\n\tvar errs []error\n\tgo func() {\n\t\tfor err := range errCh {\n\t\t\terrHandler(err)\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\tdoneCh <- struct{}{}\n\t}()\n\n\tfor n := 0; n < numHostingWorkers; n++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor job := range jobCh {\n\t\t\t\tjob()\n\t\t\t}\n\t\t}()\n\t}\n\n\tassetsDir := filepath.Join(h.RootDir, NameFiles)\n\n\tfor _, added := range hostingDiffs.Added {\n\t\tasset := added // the closure otherwise sees the same value for `added` each iteration\n\t\tjobCh <- func() {\n\t\t\tif err := realmClient.HostingAssetUpload(groupID, appID, assetsDir, asset); err != nil {\n\t\t\t\terrCh <- fmt.Errorf(\"failed to add %s: %w\", asset.FilePath, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, deleted := range hostingDiffs.Deleted {\n\t\tasset := deleted // the closure otherwise sees the same value for `added` each iteration\n\t\tjobCh <- func() {\n\t\t\tif err := realmClient.HostingAssetRemove(groupID, appID, asset.FilePath); err != nil {\n\t\t\t\terrCh <- fmt.Errorf(\"failed to remove %s: %w\", asset.FilePath, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, modified := range hostingDiffs.Modified {\n\t\tasset := modified // the closure otherwise sees the same value for `added` each iteration\n\t\tjobCh <- func() {\n\t\t\tif asset.AttrsModified && !asset.BodyModified {\n\t\t\t\tif err := realmClient.HostingAssetAttributesUpdate(groupID, appID, asset.FilePath, asset.Attrs...); err != nil {\n\t\t\t\t\terrCh <- fmt.Errorf(\"failed to update attributes for %s: %w\", asset.FilePath, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := realmClient.HostingAssetUpload(groupID, appID, assetsDir, asset.HostingAsset); err != nil {\n\t\t\t\t\terrCh <- fmt.Errorf(\"failed to update %s: %w\", asset.FilePath, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tclose(jobCh)\n\twg.Wait()\n\n\tclose(errCh)\n\t<-doneCh\n\n\tif len(errs) > 0 {\n\t\treturn fmt.Errorf(\"%d error(s) occurred while importing hosting assets\", len(errs))\n\t}\n\treturn nil\n}", "func uploadRemoteBoshAssets(dm *enaml.DeploymentManifest, boshClient *enamlbosh.Client, poll bool) (err error) {\n\tvar errStemcells error\n\tvar errReleases error\n\tvar remoteStemcells []enaml.Stemcell\n\tdefer UIPrint(\"remote asset check complete.\")\n\tUIPrint(\"Checking product deployment for remote assets...\")\n\n\tif remoteStemcells, err = stemcellsToUpload(dm.Stemcells, boshClient); err == nil {\n\t\tif errStemcells = uploadRemoteStemcells(remoteStemcells, boshClient, poll); errStemcells != nil {\n\t\t\tlo.G.Info(\"issues processing stemcell: \", errStemcells)\n\t\t}\n\t}\n\n\tif errReleases = uploadRemoteReleases(dm.Releases, boshClient, poll); errReleases != nil {\n\t\tlo.G.Info(\"issues processing release: \", errReleases)\n\t}\n\n\tif errReleases != nil || errStemcells != nil {\n\t\terr = fmt.Errorf(\"stemcell err: %v release err: %v\", errStemcells, errReleases)\n\t}\n\treturn\n}", "func BlobsUpload(mods *tools.Modules, destination string) (Upload, error) {\n\treturn blobsUpload(mods, destination)\n}", "func (provider *AWSS3ReleasesProvider) Set(applicationName string, releases []domain.Release) error {\n\tbs, err := json.Marshal(releases)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"marshalling releases: %s\", err)\n\t}\n\n\tkey := fmt.Sprintf(\"/releases/%v/manifest.json\", applicationName)\n\n\tputInput := &s3.PutObjectInput{\n\t\tBucket: aws.String(provider.bucket),\n\t\tKey: aws.String(key),\n\t\tBody: bytes.NewReader(bs),\n\t\tContentLength: aws.Int64(int64(len(bs))),\n\t\tContentType: aws.String(\"application/json\"),\n\t}\n\n\tresp, err := provider.svc.PutObject(putInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"uploading manifest.json: %s\", err)\n\t}\n\tlog.WithField(\"app\", applicationName).Debugf(\"Upload releases manifest response: %s\", awsutil.StringValue(resp))\n\treturn nil\n}", "func PrepareReleaseBundle(awsc aws.AwsClients, release *deployer.Release, zip_file_path *string) error {\n\tif err := PrepareRelease(release, zip_file_path); err != nil {\n\t\treturn err\n\t}\n\n\terr := s3.PutFile(\n\t\tawsc.S3Client(nil, nil, nil),\n\t\tzip_file_path,\n\t\trelease.Bucket,\n\t\trelease.LambdaZipPath(),\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// reset CreateAt because it can take a while to upload the lambda\n\trelease.CreatedAt = to.Timep(time.Now())\n\n\t// Uploading the Release to S3 to match SHAs\n\tif err := s3.PutStruct(awsc.S3Client(nil, nil, nil), release.Bucket, release.ReleasePath(), release); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *GitHub) SetAsset(name string) {\n\tg.releaseAsset = name\n}", "func (svc *AwsS3) UploadObject(fileName string) {\n\n\tres, _ := ListBuckets(svc.S3)\n\tvar bucketName string\n\t// Later replace with a customized struct.\n\tfor _, b := range res.Buckets {\n\t\tbucketName = aws.StringValue(b.Name)\n\t}\n\tlog.Println(\"Uploading Object \" + fileName + \" into bucket \" + bucketName)\n\tsvc.uploadObject(bucketName, fileName)\n}", "func (c *GitHub) CreateReleaseAsset(ctx context.Context, a git.ReleaseAsset) error {\n\tc.Logger.Debugf(\"Creating a release asset %+v\", a)\n\tf, err := os.Open(a.RealPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open the file: %w\", err)\n\t}\n\tdefer f.Close()\n\t_, _, err = c.Client.UploadReleaseAsset(ctx, a.Release.Repository.Owner, a.Release.Repository.Name, a.Release.InternalID, &github.UploadOptions{\n\t\tName: a.Name,\n\t}, f)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GitHub API error: %w\", err)\n\t}\n\treturn nil\n}", "func (mr *MockRealmClientMockRecorder) UploadAsset(groupID, appID, path, hash, size, body interface{}, attributes ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{groupID, appID, path, hash, size, body}, attributes...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UploadAsset\", reflect.TypeOf((*MockRealmClient)(nil).UploadAsset), varargs...)\n}", "func (c *Client) Upload(relPath, fieldname, filename string, resource interface{}) error {\n\treq, err := c.NewfileUploadRequest(relPath, fieldname, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err:=c.doGetHeaders(req, resource, true);err!=nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ListAssets lists assets associated with a given release
func (c *Client) ListAssets(ctx context.Context, releaseID int64) ([]*github.ReleaseAsset, error) { result := []*github.ReleaseAsset{} page := 1 for { assets, res, err := c.Repositories.ListReleaseAssets(context.TODO(), c.Owner, c.Repo, releaseID, &github.ListOptions{Page: page}) if err != nil { return nil, errors.Wrap(err, "failed to list assets") } if res.StatusCode != http.StatusOK { return nil, errors.Errorf("list release assets: invalid status code: %s", res.Status) } result = append(result, assets...) if res.NextPage <= page { break } page = res.NextPage } return result, nil }
[ "func (s *SmartContract) ListAssets(ctx contractapi.TransactionContextInterface) ([]Asset, error) {\n\tstartKey := fmt.Sprintf(KEY_ASSET_NO, 1)\n\tendKey := fmt.Sprintf(KEY_ASSET_NO, 9999)\n\n\tresultsIterator, err := ctx.GetStub().GetStateByRange(startKey, endKey)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//noinspection GoUnhandledErrorResult\n\tdefer resultsIterator.Close()\n\n\tvar results []Asset\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tasset := new(Asset)\n\t\terr = json.Unmarshal(queryResponse.Value, asset)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults = append(results, *asset)\n\t}\n\n\treturn results, nil\n}", "func (provider *AWSS3ReleasesProvider) List(applicationName string) ([]domain.Release, error) {\n\tvar (\n\t\tkey = fmt.Sprintf(\"/releases/%v/manifest.json\", applicationName)\n\t\treleases []domain.Release\n\t)\n\n\tinput := &s3.GetObjectInput{\n\t\tBucket: aws.String(provider.bucket),\n\t\tKey: aws.String(key),\n\t}\n\n\tresp, err := provider.svc.GetObject(input)\n\tif err != nil {\n\t\treturn releases, fmt.Errorf(\"retrieving key=%q: %s\", key, err)\n\t}\n\n\tbs, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn releases, fmt.Errorf(\"reading response body for key=%q: %s\", key, err)\n\t}\n\tresp.Body.Close()\n\n\tif err := json.Unmarshal(bs, &releases); err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling key=%q: %s\", key, err)\n\t}\n\treturn releases, nil\n}", "func (s *AssetServiceOp) List(themeID int64, options interface{}) ([]Asset, error) {\n\tpath := fmt.Sprintf(\"%s/%d/assets.json\", assetsBasePath, themeID)\n\tresource := new(AssetsResource)\n\terr := s.client.Get(path, resource, options)\n\treturn resource.Assets, err\n}", "func (c *Client) ListReleases(ctx context.Context) ([]*types.Release, error) {\n\tif c.client == nil {\n\t\treturn nil, trace.BadParameter(\"client not initialized\")\n\t}\n\n\tresp, err := c.client.Get(ctx, c.client.Endpoint(types.EnterpriseReleaseEndpoint), nil)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"failed to retrieve releases from release server\")\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif resp.Code() == http.StatusUnauthorized {\n\t\treturn nil, trace.AccessDenied(\"access denied by the release server\")\n\t}\n\n\tif resp.Code() != http.StatusOK {\n\t\treturn nil, trace.Errorf(\"release server responded with status %d\", resp.Code())\n\t}\n\n\tvar releases []Release\n\terr = json.Unmarshal(resp.Bytes(), &releases)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar responseReleases []*types.Release\n\tfor _, r := range releases {\n\t\tvar releaseAssets []*types.Asset\n\t\tfor _, a := range r.Assets {\n\t\t\treleaseAssets = append(releaseAssets, &types.Asset{\n\t\t\t\tArch: a.Arch,\n\t\t\t\tDescription: a.Description,\n\t\t\t\tName: a.Name,\n\t\t\t\tOS: a.OS,\n\t\t\t\tSHA256: a.SHA256,\n\t\t\t\tAssetSize: a.Size,\n\t\t\t\tDisplaySize: utils.ByteCount(a.Size),\n\t\t\t\tReleaseIDs: a.ReleaseIDs,\n\t\t\t\tPublicURL: a.PublicURL,\n\t\t\t})\n\t\t}\n\n\t\tresponseReleases = append(responseReleases, &types.Release{\n\t\t\tNotesMD: r.NotesMD,\n\t\t\tProduct: r.Product,\n\t\t\tReleaseID: r.ReleaseID,\n\t\t\tStatus: r.Status,\n\t\t\tVersion: r.Version,\n\t\t\tAssets: releaseAssets,\n\t\t})\n\t}\n\n\treturn responseReleases, err\n}", "func ListReleases(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/releases repository repoListReleases\n\t// ---\n\t// summary: List a repo's releases\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: draft\n\t// in: query\n\t// description: filter (exclude / include) drafts, if you dont have repo write access none will show\n\t// type: boolean\n\t// - name: pre-release\n\t// in: query\n\t// description: filter (exclude / include) pre-releases\n\t// type: boolean\n\t// - name: per_page\n\t// in: query\n\t// description: page size of results, deprecated - use limit\n\t// type: integer\n\t// deprecated: true\n\t// - name: page\n\t// in: query\n\t// description: page number of results to return (1-based)\n\t// type: integer\n\t// - name: limit\n\t// in: query\n\t// description: page size of results\n\t// type: integer\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/ReleaseList\"\n\tlistOptions := utils.GetListOptions(ctx)\n\tif listOptions.PageSize == 0 && ctx.FormInt(\"per_page\") != 0 {\n\t\tlistOptions.PageSize = ctx.FormInt(\"per_page\")\n\t}\n\n\topts := repo_model.FindReleasesOptions{\n\t\tListOptions: listOptions,\n\t\tIncludeDrafts: ctx.Repo.AccessMode >= perm.AccessModeWrite || ctx.Repo.UnitAccessMode(unit.TypeReleases) >= perm.AccessModeWrite,\n\t\tIncludeTags: false,\n\t\tIsDraft: ctx.FormOptionalBool(\"draft\"),\n\t\tIsPreRelease: ctx.FormOptionalBool(\"pre-release\"),\n\t}\n\n\treleases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"GetReleasesByRepoID\", err)\n\t\treturn\n\t}\n\trels := make([]*api.Release, len(releases))\n\tfor i, release := range releases {\n\t\tif err := release.LoadAttributes(ctx); err != nil {\n\t\t\tctx.Error(http.StatusInternalServerError, \"LoadAttributes\", err)\n\t\t\treturn\n\t\t}\n\t\trels[i] = convert.ToAPIRelease(ctx, ctx.Repo.Repository, release)\n\t}\n\n\tfilteredCount, err := repo_model.CountReleasesByRepoID(ctx.Repo.Repository.ID, opts)\n\tif err != nil {\n\t\tctx.InternalServerError(err)\n\t\treturn\n\t}\n\n\tctx.SetLinkHeader(int(filteredCount), listOptions.PageSize)\n\tctx.SetTotalCountHeader(filteredCount)\n\tctx.JSON(http.StatusOK, rels)\n}", "func cmdListReleases(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\toutput := runListCommand(&releaseParams, aplSvc.Releases.List)\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"StackID\", \"Version\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.Release), fields)\n\t}\n}", "func (c *Client) List(p ListParameters) ([]Release, error) {\n\tresponse, err := c.client.ListReleases(p.Options()...) // TODO Paging.\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tvar releases []Release\n\tif response != nil && response.Releases != nil {\n\t\tfor _, item := range response.Releases {\n\t\t\treleases = append(releases, *(fromHelm(item)))\n\t\t}\n\t}\n\treturn releases, nil\n}", "func (s *sensuAssetLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func (r *GitLabRelease) ListReleases(ctx context.Context) ([]string, error) {\n\tversions := []string{}\n\topt := &gitlab.ListReleasesOptions{\n\t\tPerPage: 100, // max\n\t}\n\n\tfor {\n\t\treleases, resp, err := r.api.ProjectListReleases(ctx, r.owner, r.project, opt)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list releases for %s/%s: %s\", r.owner, r.project, err)\n\t\t}\n\n\t\tfor _, release := range releases {\n\t\t\tv := tagNameToVersion(release.TagName)\n\t\t\tversions = append(versions, v)\n\t\t}\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\n\treturn versions, nil\n}", "func getLinkAssets() []Asset {\n\tres, err := http.Get(ASSET_URL)\n\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\r\\n\", err)\n\t}\n\n\tfmt.Println(res.Body)\n\tjsonResponses, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\r\\n\", err)\n\t}\n\n\tfmt.Println(jsonResponses, \"\\n\")\n\tres.Body.Close()\n\tfmt.Printf(\"JSON:\\r\\n%s\\r\\n\", jsonResponses)\n\n\tassetsJson := Assets{}\n\terr1 := json.Unmarshal([]byte(jsonResponses), &assetsJson)\n\n\tif err1 != nil {\n\t\tfmt.Println(err1)\n\t}\n\n\treturn assetsJson\n}", "func ListAssetNames() []string {\n\treturn assetNames\n}", "func (r *GitHubRelease) ListReleases(ctx context.Context) ([]string, error) {\n\tversions := []string{}\n\topt := &github.ListOptions{\n\t\tPerPage: 100, // max\n\t}\n\n\tfor {\n\t\treleases, resp, err := r.api.RepositoriesListReleases(ctx, r.owner, r.repo, opt)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list releases for %s/%s: %s\", r.owner, r.repo, err)\n\t\t}\n\n\t\tfor _, release := range releases {\n\t\t\tv := tagNameToVersion(*release.TagName)\n\t\t\tversions = append(versions, v)\n\t\t}\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\n\treturn versions, nil\n}", "func (s *ReleaseTagService) List(ctx context.Context, releaseID int64) ([]*ReleaseTagResponse, error) {\n\tquery := \"%24filter=release/id+eq+%27\" + strconv.FormatInt(releaseID, 10) + \"%27\"\n\treturn s.GetWithQuery(ctx, query)\n}", "func (s sensuAssetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func readReleases(dir string) (result []Release) {\n\tf, err := os.Open(dir)\n\tif err != nil {\n\t\tdie(\"unable to open dir: %v\", err)\n\t}\n\n\tentries, err := f.Readdir(-1)\n\tif err != nil {\n\t\tdie(\"unable to list directory: %v\", err)\n\t}\n\n\terr = f.Close()\n\tif err != nil {\n\t\tdie(\"close dir: %v\", err)\n\t}\n\n\tfor _, entry := range entries {\n\t\tif !entry.Mode().IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif entry.Name() == \"unreleased\" {\n\t\t\trel := Release{\n\t\t\t\tpath: filepath.Join(dir, entry.Name()),\n\t\t\t\tVersion: \"unreleased\",\n\t\t\t}\n\t\t\tresult = append(result, rel)\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := versionRegex.FindStringSubmatch(entry.Name())\n\t\tif len(data) == 0 {\n\t\t\tdie(\"invalid subdir name %v\", filepath.Join(dir, entry.Name()))\n\t\t\tcontinue\n\t\t}\n\n\t\tver := data[1]\n\t\tdate := data[3]\n\n\t\trel := Release{\n\t\t\tpath: filepath.Join(dir, entry.Name()),\n\t\t\tVersion: ver,\n\t\t}\n\n\t\tif date != \"\" {\n\t\t\tt, err := time.Parse(\"2006-01-02\", date)\n\t\t\tif err != nil {\n\t\t\t\tdie(\"unable to parse date %q: %v\", date, err)\n\t\t\t}\n\t\t\trel.Date = &t\n\t\t}\n\n\t\tresult = append(result, rel)\n\t}\n\n\tsort.Sort(ReleaseSlice(result))\n\n\treturn result\n}", "func (d *AppReleases) List(filter func(*rspb.Release) bool) ([]*rspb.Release, error) {\n\tvar list driversapi.AppReleaseList\n\terr := d.kc.List(context.Background(), &list, client.MatchingLabels{\n\t\t\"owner\": \"helm\",\n\t})\n\tif err != nil {\n\t\td.Log(\"list: failed to list: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tvar results []*rspb.Release\n\n\t// iterate over the configmaps object list\n\t// and decode each release\n\tfor _, item := range list.Items {\n\t\trls, err := decodeReleaseFromApp(d.kc, &item)\n\t\tif err != nil {\n\t\t\td.Log(\"list: failed to decode release: %v: %s\", item, err)\n\t\t\tcontinue\n\t\t}\n\t\tif filter(rls) {\n\t\t\tresults = append(results, rls)\n\t\t}\n\t}\n\treturn results, nil\n}", "func releases(ctx context.Context, c *github.Client, org string, project string) ([]*release, error) {\n\tvar result []*release\n\n\topts := &github.ListOptions{PerPage: 100}\n\n\tklog.Infof(\"Downloading releases for %s/%s ...\", org, project)\n\n\tfor page := 1; page != 0; {\n\t\topts.Page = page\n\t\trs, resp, err := c.Repositories.ListReleases(ctx, org, project, opts)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\n\t\tpage = resp.NextPage\n\t\tuntil := time.Now()\n\n\t\tfor _, r := range rs {\n\t\t\tname := r.GetName()\n\t\t\tif name == \"\" {\n\t\t\t\tname = r.GetTagName()\n\t\t\t}\n\n\t\t\trel := &release{\n\t\t\t\tName: name,\n\t\t\t\tDraft: r.GetDraft(),\n\t\t\t\tPrerelease: r.GetPrerelease(),\n\t\t\t\tPublishedAt: r.GetPublishedAt().Time,\n\t\t\t\tActiveUntil: until,\n\t\t\t\tDownloads: map[string]int{},\n\t\t\t\tDownloadRatios: map[string]float64{},\n\t\t\t}\n\n\t\t\tfor _, a := range r.Assets {\n\t\t\t\tif ignoreAssetRe.MatchString(a.GetName()) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trel.Downloads[a.GetName()] = a.GetDownloadCount()\n\t\t\t\trel.DownloadsTotal += int64(a.GetDownloadCount())\n\t\t\t}\n\n\t\t\tif !rel.Draft && !rel.Prerelease {\n\t\t\t\tuntil = rel.PublishedAt\n\t\t\t}\n\n\t\t\tresult = append(result, rel)\n\t\t}\n\t}\n\n\tfor _, r := range result {\n\t\tr.DaysActive = r.ActiveUntil.Sub(r.PublishedAt).Hours() / 24\n\t\tr.DownloadsPerDay = float64(r.DownloadsTotal) / r.DaysActive\n\n\t\tfor k, v := range r.Downloads {\n\t\t\tr.DownloadRatios[k] = float64(v) / float64(r.DownloadsTotal)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func GetAssets(ctx context.Context, store store.Store, assetList []string) []types.Asset {\n\tassets := []types.Asset{}\n\n\tfor _, assetName := range assetList {\n\t\tasset, err := store.GetAssetByName(ctx, assetName)\n\t\tif err != nil {\n\t\t\tlogger.WithField(\"asset\", assetName).WithError(err).Error(\"error fetching asset from store\")\n\t\t} else if asset == nil {\n\t\t\tlogger.WithField(\"asset\", assetName).Info(\"asset does not exist\")\n\t\t} else {\n\t\t\tassets = append(assets, *asset)\n\t\t}\n\t}\n\n\treturn assets\n}", "func (a *Agent) ListReleases(\n\tctx context.Context,\n\tnamespace string,\n\tfilter *types.ReleaseListFilter,\n) ([]*release.Release, error) {\n\tctx, span := telemetry.NewSpan(ctx, \"helm-list-releases\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"namespace\", Value: namespace},\n\t)\n\n\tlsel := fmt.Sprintf(\"owner=helm,status in (%s)\", strings.Join(filter.StatusFilter, \",\"))\n\n\t// list secrets\n\tsecretList, err := a.K8sAgent.Clientset.CoreV1().Secrets(namespace).List(\n\t\tcontext.Background(),\n\t\tv1.ListOptions{\n\t\t\tLabelSelector: lsel,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error getting secret list\")\n\t}\n\n\t// before decoding to helm release, only keep the latest releases for each chart\n\tlatestMap := make(map[string]corev1.Secret)\n\n\tfor _, secret := range secretList.Items {\n\t\trelName, relNameExists := secret.Labels[\"name\"]\n\n\t\tif !relNameExists {\n\t\t\tcontinue\n\t\t}\n\n\t\tid := fmt.Sprintf(\"%s/%s\", secret.Namespace, relName)\n\n\t\tif currLatest, exists := latestMap[id]; exists {\n\t\t\t// get version\n\t\t\tcurrVersionStr, currVersionExists := currLatest.Labels[\"version\"]\n\t\t\tversionStr, versionExists := secret.Labels[\"version\"]\n\n\t\t\tif versionExists && currVersionExists {\n\t\t\t\tcurrVersion, currErr := strconv.Atoi(currVersionStr)\n\t\t\t\tversion, err := strconv.Atoi(versionStr)\n\t\t\t\tif currErr == nil && err == nil && currVersion < version {\n\t\t\t\t\tlatestMap[id] = secret\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlatestMap[id] = secret\n\t\t}\n\t}\n\n\tchartList := []string{}\n\tres := make([]*release.Release, 0)\n\n\tfor _, secret := range latestMap {\n\t\trel, isErr, err := kubernetes.ParseSecretToHelmRelease(secret, chartList)\n\n\t\tif !isErr && err == nil {\n\t\t\tres = append(res, rel)\n\t\t}\n\t}\n\n\treturn res, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TrustAnchorString convert a TrustAnchor to a string encoded as XML.
func TrustAnchorString(t []*TrustAnchor) string { xta := new(XMLTrustAnchor) xta.KeyDigest = make([]*XMLKeyDigest, 0) for _, ta := range t { xta.Id = ta.Id // Sets the everytime, but that is OK. xta.Source = ta.Source xta.Zone = ta.Anchor.Hdr.Name xkd := new(XMLKeyDigest) xkd.Id = ta.AnchorId xkd.ValidFrom = ta.ValidFrom.Format("2006-01-02T15:04:05-07:00") if !ta.ValidUntil.IsZero() { xkd.ValidUntil = ta.ValidUntil.Format("2006-01-02T15:04:05-07:00") } xkd.KeyTag = ta.Anchor.KeyTag xkd.Algorithm = ta.Anchor.Algorithm xkd.DigestType = ta.Anchor.DigestType xkd.Digest = ta.Anchor.Digest xta.KeyDigest = append(xta.KeyDigest, xkd) } b, _ := xml.MarshalIndent(xta, "", "\t") return string(b) }
[ "func (me TxsdPresentationAttributesTextContentElementsTextAnchor) ToXsdtString() xsdt.String {\n\treturn xsdt.String(me)\n}", "func (me TxsdPresentationAttributesTextContentElementsTextAnchor) String() string {\n\treturn xsdt.String(me).String()\n}", "func (o LookupCustomKeyStoreResultOutput) TrustAnchorCertificate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCustomKeyStoreResult) string { return v.TrustAnchorCertificate }).(pulumi.StringOutput)\n}", "func getTrustAnchor() (*trustAnchor, error) {\n\tresp, err := http.Get(trustAnchorURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad http response: %d\", resp.StatusCode)\n\t}\n\tbyteValue, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar anchor trustAnchor\n\tif err := xml.Unmarshal(byteValue, &anchor); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &anchor, nil\n}", "func (c certificate) String() string {\n\tb, err := asn1.Marshal(c)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Failed marshaling cert: %v\", err)\n\t}\n\tblock := &pem.Block{\n\t\tBytes: b,\n\t\tType: \"CERTIFICATE\",\n\t}\n\tb = pem.EncodeToMemory(block)\n\treturn string(b)\n}", "func (n *Netconf) ToXMLString() (string, error) {\n\tdoc := etree.NewDocument()\n\toperation := doc.CreateElement(n.Operation)\n\tswitch n.Operation {\n\tcase \"get-config\":\n\t\tsource := operation.CreateElement(\"source\")\n\t\tif n.Source != nil {\n\t\t\tsource.CreateElement(*n.Source)\n\t\t} else {\n\t\t\tsource.CreateElement(\"running\")\n\t\t}\n\t\taddFilterIfPresent(n, operation)\n\tcase \"get\":\n\t\taddFilterIfPresent(n, operation)\n\tcase \"edit-config\":\n\t\tsource := operation.CreateElement(\"target\")\n\t\tif n.Target != nil {\n\t\t\tsource.CreateElement(*n.Target)\n\t\t} else {\n\t\t\tsource.CreateElement(\"running\")\n\t\t}\n\t\tconfig := operation.CreateElement(\"config\")\n\t\tif n.Config != nil {\n\t\t\tinner := etree.NewDocument()\n\t\t\terr := inner.ReadFromString(*n.Config)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Config data is not valid xml\")\n\t\t\t}\n\t\t\tconfig.AddChild(inner.Root().Copy())\n\t\t}\n\tdefault:\n\t\treturn \"\", errors.New(n.Operation + \" is not a supported operation\")\n\n\t}\n\treturn doc.WriteToString()\n}", "func AstToString(a *Ast) (string, error) {\n\texpr := a.Expr()\n\tinfo := a.SourceInfo()\n\treturn parser.Unparse(expr, info)\n}", "func Anchorize(text string) string {\n\treturn string(anchorize([]byte(text), false))\n}", "func (n *Node) toxstring() string {\n\treturn strings.Replace(n.Nodestr, \"/\", \"+\", -1)\n}", "func (a *Addr) ToStr() string {\n\treturn fmt.Sprintf(\"%s:%s\", a.IP, a.Port)\n}", "func ReadTrustAnchor(q io.Reader) ([]*TrustAnchor, error) {\n\td := xml.NewDecoder(q)\n\tt := new(XMLTrustAnchor)\n\tif e := d.Decode(t); e != nil {\n\t\treturn nil, e\n\t}\n\tta := make([]*TrustAnchor, 0)\n\tvar err error\n\tfor _, digest := range t.KeyDigest {\n\t\tt1 := new(TrustAnchor)\n\t\tt1.Id = t.Id\n\t\tt1.Source = t.Source\n\t\tt1.AnchorId = digest.Id\n\t\tif t1.ValidFrom, err = time.Parse(\"2006-01-02T15:04:05-07:00\", digest.ValidFrom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif digest.ValidUntil != \"\" {\n\t\t\tif t1.ValidUntil, err = time.Parse(\"2006-01-02T15:04:05-07:00\", digest.ValidUntil); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\td := new(RR_DS)\n\t\td.Hdr = RR_Header{Name: t.Zone, Class: ClassINET, Rrtype: TypeDS}\n\t\td.KeyTag = digest.KeyTag\n\t\td.Algorithm = digest.Algorithm\n\t\td.DigestType = digest.DigestType\n\t\td.Digest = digest.Digest\n\t\tt1.Anchor = d\n\t\t// Some checks here too?\n\t\tta = append(ta, t1)\n\t}\n\treturn ta, nil\n}", "func (me TLinkTargetType) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func XmlEntitiesString(s string) string {\n\tw := bytes.NewBuffer([]byte{})\n\txml.Escape(w, []byte(s))\n\treturn w.String()\n}", "func EncodedSignedString(data interface{}, privateKeyPath string) (string, error) {\n\tsigned, err := SignedString(data, privateKeyPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb64XML := EncodeString([]byte(signed))\n\treturn b64XML, nil\n}", "func (a Address) ToString() string {\n\treturn base64.StdEncoding.EncodeToString(a)\n}", "func ConvertAclToXml(input AccessControlPolicy, returnMd5 bool, isObs bool) (data string, md5 string) {\n\txml := make([]string, 0, 4+len(input.Grants))\n\townerID := XmlTranscoding(input.Owner.ID)\n\txml = append(xml, fmt.Sprintf(\"<AccessControlPolicy><Owner><ID>%s</ID>\", ownerID))\n\tif !isObs && input.Owner.DisplayName != \"\" {\n\t\townerDisplayName := XmlTranscoding(input.Owner.DisplayName)\n\t\txml = append(xml, fmt.Sprintf(\"<DisplayName>%s</DisplayName>\", ownerDisplayName))\n\t}\n\tif isObs && input.Delivered != \"\" {\n\t\tobjectDelivered := XmlTranscoding(input.Delivered)\n\t\txml = append(xml, fmt.Sprintf(\"</Owner><Delivered>%s</Delivered><AccessControlList>\", objectDelivered))\n\t} else {\n\t\txml = append(xml, \"</Owner><AccessControlList>\")\n\t}\n\tfor _, grant := range input.Grants {\n\t\txml = append(xml, convertGrantToXML(grant, isObs, false))\n\t}\n\txml = append(xml, \"</AccessControlList></AccessControlPolicy>\")\n\tdata = strings.Join(xml, \"\")\n\tif returnMd5 {\n\t\tmd5 = Base64Md5([]byte(data))\n\t}\n\treturn\n}", "func (c Certificate) String() string {\n\treturn fmt.Sprintf(\"Cert(id=%v,trustId=%v,issuerId=%v,trusteeId=%v,lvl=%v): %v\",\n\t\tformatUUID(c.Id), formatUUID(c.TrustId), formatUUID(c.IssuerId), formatUUID(c.TrusteeId), c.Level, c.ExpiresAt.Sub(c.IssuedAt))\n}", "func toYamlString(resource interface{}) string {\n\tdata, err := yaml.Marshal(resource)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}", "func (c Certificate) String() string {\n\treturn fmt.Sprintf(\"ID: %d\\nUserId: %d\\nCreated: %s\\nLink: %s\\n Link: %t\\n\",\n\t\tc.ID, c.UserID, c.Created.Format(\"02-01-2006 15:04:05\"), c.Link, c.IsDeleted)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ReadTrustAnchor reads a root trust anchor from: and returns the data or an error.
func ReadTrustAnchor(q io.Reader) ([]*TrustAnchor, error) { d := xml.NewDecoder(q) t := new(XMLTrustAnchor) if e := d.Decode(t); e != nil { return nil, e } ta := make([]*TrustAnchor, 0) var err error for _, digest := range t.KeyDigest { t1 := new(TrustAnchor) t1.Id = t.Id t1.Source = t.Source t1.AnchorId = digest.Id if t1.ValidFrom, err = time.Parse("2006-01-02T15:04:05-07:00", digest.ValidFrom); err != nil { return nil, err } if digest.ValidUntil != "" { if t1.ValidUntil, err = time.Parse("2006-01-02T15:04:05-07:00", digest.ValidUntil); err != nil { return nil, err } } d := new(RR_DS) d.Hdr = RR_Header{Name: t.Zone, Class: ClassINET, Rrtype: TypeDS} d.KeyTag = digest.KeyTag d.Algorithm = digest.Algorithm d.DigestType = digest.DigestType d.Digest = digest.Digest t1.Anchor = d // Some checks here too? ta = append(ta, t1) } return ta, nil }
[ "func getTrustAnchor() (*trustAnchor, error) {\n\tresp, err := http.Get(trustAnchorURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad http response: %d\", resp.StatusCode)\n\t}\n\tbyteValue, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar anchor trustAnchor\n\tif err := xml.Unmarshal(byteValue, &anchor); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &anchor, nil\n}", "func (o LookupCustomKeyStoreResultOutput) TrustAnchorCertificate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCustomKeyStoreResult) string { return v.TrustAnchorCertificate }).(pulumi.StringOutput)\n}", "func GetTrustAnchorsAndCertChain(ctx context.Context, kubeClient kubernetes.Interface, namespace string) (string, string, string) {\n\tsecret, err := kubeClient.CoreV1().\n\t\tSecrets(namespace).\n\t\tGet(ctx, securityConsts.TrustBundleK8sSecretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", \"\", \"\"\n\t}\n\n\trootCert := secret.Data[credentials.RootCertFilename]\n\tcertChain := secret.Data[credentials.IssuerCertFilename]\n\tcertKey := secret.Data[credentials.IssuerKeyFilename]\n\treturn string(rootCert), string(certChain), string(certKey)\n}", "func ReadRootCA(RootCACertFile string, RootCAKeyFile string) (rootCA []byte, rootKey []byte, err error) {\n\n // Check if files exist\n rootCAExists, err := FileExists(RootCACertFile)\n if err != nil {\n return nil, nil, err\n }\n\n rootKeyExists, err := FileExists(RootCAKeyFile)\n if err != nil {\n return nil, nil, err\n }\n\n // We need both key and cert to exist\n if (rootCAExists && rootKeyExists) {\n\n // If files exist, read rootCA first\n rootCA, err = ioutil.ReadFile(RootCACertFile)\n if err != nil {\n return nil, nil, errors.New(fmt.Sprintf(\"Error reading %s file\", RootCACertFile))\n }\n\n // Now check if rootCA is a valid DER certificate\n if _, err = x509.ParseCertificate(rootCA); err != nil {\n return nil, nil, err\n }\n\n // Read rootKey\n rootKey, err = ioutil.ReadFile(RootCAKeyFile)\n if err != nil {\n return nil, nil, errors.New(fmt.Sprintf(\"Error reading %s file\", RootCAKeyFile))\n }\n\n // Check if rootKey is a valid key - we already have tlsdump.ParsePrivateKey that does this\n if _, _, err = ParsePrivateKey(rootKey); err != nil {\n return nil, nil, err\n }\n\n return rootCA, rootKey, nil\n\n } else {\n // Custom error text\n var customError = \"\"\n\n if !rootCAExists {\n customError += fmt.Sprintf(\"%s does not exist\", RootCACertFile)\n }\n\n if !rootKeyExists {\n customError += fmt.Sprintf(\"\\n%s does not exist\", RootCAKeyFile)\n }\n\n return nil, nil, errors.New(customError)\n }\n\n // We should not get there (because both if and else have returns) but just in case\n return nil, nil, err\n\n}", "func (c *Client) ReadRootCASecret() (result []byte) {\n\tlogger := c.log.WithName(\"ReadRootCASecret\")\n\tcertProps, err := c.GetTLSCertProps(c.clientConfig)\n\tif err != nil {\n\t\tlogger.Error(err, \"failed to get TLS Cert Properties\")\n\t\treturn result\n\t}\n\tsname := generateRootCASecretName(certProps)\n\tstlsca, err := c.GetResource(\"\", Secrets, certProps.Namespace, sname)\n\tif err != nil {\n\t\treturn result\n\t}\n\ttlsca, err := convertToSecret(stlsca)\n\tif err != nil {\n\t\tlogger.Error(err, \"failed to convert secret\", \"name\", sname, \"namespace\", certProps.Namespace)\n\t\treturn result\n\t}\n\n\tresult = tlsca.Data[rootCAKey]\n\tif len(result) == 0 {\n\t\tlogger.Info(\"root CA certificate not found in secret\", \"name\", tlsca.Name, \"namespace\", certProps.Namespace)\n\t\treturn result\n\t}\n\tlogger.V(4).Info(\"using CA bundle defined in secret to validate the webhook's server certificate\", \"name\", tlsca.Name, \"namespace\", certProps.Namespace)\n\treturn result\n}", "func TrustAnchorString(t []*TrustAnchor) string {\n\txta := new(XMLTrustAnchor)\n\txta.KeyDigest = make([]*XMLKeyDigest, 0)\n\tfor _, ta := range t {\n\t\txta.Id = ta.Id // Sets the everytime, but that is OK.\n\t\txta.Source = ta.Source\n\t\txta.Zone = ta.Anchor.Hdr.Name\n\t\txkd := new(XMLKeyDigest)\n\t\txkd.Id = ta.AnchorId\n\t\txkd.ValidFrom = ta.ValidFrom.Format(\"2006-01-02T15:04:05-07:00\")\n\t\tif !ta.ValidUntil.IsZero() {\n\t\t\txkd.ValidUntil = ta.ValidUntil.Format(\"2006-01-02T15:04:05-07:00\")\n\t\t}\n\t\txkd.KeyTag = ta.Anchor.KeyTag\n\t\txkd.Algorithm = ta.Anchor.Algorithm\n\t\txkd.DigestType = ta.Anchor.DigestType\n\t\txkd.Digest = ta.Anchor.Digest\n\t\txta.KeyDigest = append(xta.KeyDigest, xkd)\n\t}\n\tb, _ := xml.MarshalIndent(xta, \"\", \"\\t\")\n\treturn string(b)\n}", "func trustAnchorToDS(anchor *trustAnchor) []*dns.DS {\n\tvar res []*dns.DS\n\tfor _, key := range anchor.KeyDigests {\n\t\tds := &dns.DS{\n\t\t\tHdr: dns.RR_Header{\n\t\t\t\tName: \".\",\n\t\t\t\tRrtype: dns.TypeDS,\n\t\t\t\tClass: dns.ClassINET,\n\t\t\t},\n\t\t\tKeyTag: key.KeyTag,\n\t\t\tAlgorithm: key.Algorithm,\n\t\t\tDigestType: key.DigestType,\n\t\t\tDigest: strings.ToLower(key.Digest),\n\t\t}\n\t\tres = append(res, ds)\n\t}\n\treturn res\n}", "func readCert(t *testing.T) []byte {\n\tcert, err := ioutil.ReadFile(\"testdata/root.pem\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading cert: %s\", err.Error())\n\t}\n\treturn cert\n}", "func (s *session) LoadTrust(cancel <-chan struct{}, id uuid.UUID) (Trust, bool, error) {\n\ttoken, err := s.token(cancel)\n\tif err != nil {\n\t\treturn Trust{}, false, errors.WithStack(err)\n\t}\n\n\ttrust, ok, err := s.net.TrustById(cancel, token, id)\n\treturn trust, ok, errors.WithStack(err)\n}", "func ReadCheckpoint(root string) ([]byte, error) {\n\ts := filepath.Join(root, layout.CheckpointPath)\n\treturn get(s)\n}", "func readCACert(caCertPath string) ([]byte, error) {\n\tcaCert, err := os.ReadFile(caCertPath)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to read CA cert, cert. path: %v, error: %v\", caCertPath, err)\n\t\treturn nil, fmt.Errorf(\"failed to read CA cert, cert. path: %v, error: %v\", caCertPath, err)\n\t}\n\n\tb, _ := pem.Decode(caCert)\n\tif b == nil {\n\t\treturn nil, fmt.Errorf(\"could not decode pem\")\n\t}\n\tif b.Type != \"CERTIFICATE\" {\n\t\treturn nil, fmt.Errorf(\"ca certificate contains wrong type: %v\", b.Type)\n\t}\n\tif _, err := x509.ParseCertificate(b.Bytes); err != nil {\n\t\treturn nil, fmt.Errorf(\"ca certificate parsing returns an error: %v\", err)\n\t}\n\n\treturn caCert, nil\n}", "func (acap *ACAP) ReadCACertificate(ctx context.Context, in *pb.Empty) (*pb.Cert, error) {\n\tacapLogger.Debug(\"grpc ACAP:ReadCACertificate\")\n\n\treturn &pb.Cert{Cert: acap.aca.raw}, nil\n}", "func GetTrustConfig(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *TrustConfigState, opts ...pulumi.ResourceOption) (*TrustConfig, error) {\n\tvar resource TrustConfig\n\terr := ctx.ReadResource(\"google-native:certificatemanager/v1:TrustConfig\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (e ENS) handleEthLinkSOA(name string, domain string) ([]dns.RR, error) {\n\tresults := make([]dns.RR, 0)\n\tif name == e.EthLinkRoot {\n\t\t// Create a synthetic SOA record\n\t\tnow := time.Now()\n\t\tser := ((now.Hour()*3600 + now.Minute()) * 100) / 86400\n\t\tdateStr := fmt.Sprintf(\"%04d%02d%02d%02d\", now.Year(), now.Month(), now.Day(), ser)\n\t\tresult, err := dns.NewRR(fmt.Sprintf(\"%s 10800 IN SOA ns3.ethdns.xyz. hostmaster.%s %s 3600 600 1209600 300\", name, name, dateStr))\n\t\tif err != nil {\n\t\t\treturn results, err\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\treturn results, nil\n}", "func (this *datastoreRepository) GetTrust(owner Owner, object Object) (*Trust, error) {\n\ttrust := new(Trust)\n\tif err := datastore.Get(this.Context, this.createTrustKey(owner, object), trust); err == datastore.ErrNoSuchEntity {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn trust, nil\n}", "func FetchTrustBundle(ctx context.Context, kubeAPI k8s.KubernetesAPI, controlPlaneNamespace string) (string, error) {\n\tconfigMap, err := kubeAPI.CoreV1().ConfigMaps(controlPlaneNamespace).Get(ctx, \"linkerd-identity-trust-roots\", metav1.GetOptions{})\n\n\treturn configMap.Data[\"ca-bundle.crt\"], err\n}", "func ReadCertificateAuthority(publicKeyFile, privateKeyFile string) (*KeyPair, error) {\n\troot := new(KeyPair)\n\n\trootKey, errRead := ioutil.ReadFile(privateKeyFile)\n\tif errRead != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read private key: %w\", errRead)\n\t}\n\n\tprivPemBlock, _ := pem.Decode(rootKey)\n\n\t// Note that we use PKCS8 to parse the private key here.\n\trootPrivKey, errParse := x509.ParsePKCS8PrivateKey(privPemBlock.Bytes)\n\tif errParse != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse private key: %w\", errParse)\n\t}\n\n\troot.PrivateKey = rootPrivKey.(*rsa.PrivateKey)\n\n\trootCert, errRead := ioutil.ReadFile(publicKeyFile)\n\tif errRead != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read public key: %w\", errRead)\n\t}\n\n\tpublicPemBlock, _ := pem.Decode(rootCert)\n\n\trootPubCrt, errParse := x509.ParseCertificate(publicPemBlock.Bytes)\n\tif errParse != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse public key: %w\", errParse)\n\t}\n\n\troot.PublicKey = rootPubCrt\n\n\treturn root, nil\n}", "func ReadSymlink(path string) (string, error) {\n\tvar realPath string\n\tvar err error\n\tif realPath, err = filepath.Abs(path); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get absolute path for %s: %s\", path, err)\n\t}\n\tif realPath, err = filepath.EvalSymlinks(realPath); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to canonicalise path for %s: %s\", path, err)\n\t}\n\treturn realPath, nil\n}", "func GetTrustDomainFromURISAN(uriSan string) (string, error) {\n\tparsed, err := ParseIdentity(uriSan)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse URI SAN %s. Error: %v\", uriSan, err)\n\t}\n\treturn parsed.TrustDomain, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewStreamToSubStream instantiates a new StreamToSubStream process
func NewStreamToSubStream(wf *scipipe.Workflow, name string) *StreamToSubStream { stss := &StreamToSubStream{ name: name, In: scipipe.NewInPort("in"), OutSubStream: scipipe.NewOutPort("out_substream"), } wf.AddProc(stss) return stss }
[ "func (s *Stream) CreateSubStream(headers http.Header, fin bool) (*Stream, error) {\n\treturn s.conn.CreateStream(headers, s, fin)\n}", "func NewStreamToSubStream(name string) *StreamToSubStream {\n\treturn &StreamToSubStream{\n\t\tname: name,\n\t\tIn: scipipe.NewFilePort(),\n\t\tOutSubStream: scipipe.NewFilePort(),\n\t}\n}", "func newStream(path string, fn streamFunc) *stream {\n\treturn &stream{\n\t\tpath: path,\n\t\tinfo: streamFuncs.add(fn),\n\t}\n}", "func (p *StreamToSubStream) Run() {\n\tdefer p.OutSubStream.Close()\n\n\tscipipe.Debug.Println(\"Creating new information packet for the substream...\")\n\tsubStreamIP := scipipe.NewIP(\"\")\n\tscipipe.Debug.Printf(\"Setting in-port of process %s to IP substream field\\n\", p.Name())\n\tsubStreamIP.SubStream = p.In\n\n\tscipipe.Debug.Printf(\"Sending sub-stream IP in process %s...\\n\", p.Name())\n\tp.OutSubStream.Send(subStreamIP)\n\tscipipe.Debug.Printf(\"Done sending sub-stream IP in process %s.\\n\", p.Name())\n}", "func newStream(session *Session, id uint32, state streamState) *Stream {\n\ts := &Stream{\n\t\tid: id,\n\t\tsession: session,\n\t\tstate: state,\n\t\tcontrolHdr: header(make([]byte, headerSize)),\n\t\tcontrolErr: make(chan error, 1),\n\t\tsendHdr: header(make([]byte, headerSize)),\n\t\tsendErr: make(chan error, 1),\n\t\trecvWindow: initialStreamWindow,\n\t\tsendWindow: initialStreamWindow,\n\t\trecvNotifyCh: make(chan struct{}, 1),\n\t\tsendNotifyCh: make(chan struct{}, 1),\n\t\testablishCh: make(chan struct{}, 1),\n\t}\n\ts.readDeadline.Store(time.Time{})\n\ts.writeDeadline.Store(time.Time{})\n\treturn s\n}", "func (s *subgraphStream) processNewStream(ctx context.Context, unmarshalledBlocks chan *unmarshalledBlock) error {\n\ts.logger.Info(\"retrieving cursor\")\n\tcursor, err := s.in.loadCursor()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to load cursor of subgraph %q: %w\", s.subgraph.PackageName, err)\n\t}\n\n\t// Launch streaming thing\n\n\tforkSteps := []pbbstream.ForkStep{pbbstream.ForkStep_STEP_IRREVERSIBLE}\n\tif s.withReversible {\n\t\tforkSteps = []pbbstream.ForkStep{\n\t\t\tpbbstream.ForkStep_STEP_NEW,\n\t\t\tpbbstream.ForkStep_STEP_UNDO,\n\t\t}\n\t}\n\n\ts.logger.Info(\"requesting blocks\", zap.String(\"cursor\", cursor), zap.Int64(\"start_block_num\", s.startBlock), zap.Uint64(\"stop_block_num\", s.stopBlock))\n\tstream, err := s.streamFactory.StreamBlocks(ctx, &pbbstream.BlocksRequestV2{\n\t\tStartBlockNum: s.startBlock,\n\t\tStartCursor: cursor,\n\t\tStopBlockNum: s.stopBlock,\n\t\tForkSteps: forkSteps,\n\t\tIncludeFilterExpr: s.subgraph.IncludeFilter,\n\t\tDetails: pbbstream.BlockDetails_BLOCK_DETAILS_FULL,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create blocks stream of subgraph %q: %w\", s.subgraph.PackageName, err)\n\t}\n\n\ts.logger.Info(\"streaming blocks\", zap.Uint64(\"stop_block_num\", s.stopBlock))\n\n\tdefer s.metrics.BlockRate.Clean()\n\n\tfor {\n\t\tif s.IsTerminating() {\n\t\t\ts.logger.Info(\"stopping streaming loop\")\n\t\t\treturn nil\n\t\t}\n\n\t\tresponse, err := stream.Recv()\n\t\tif (response == nil) && (err == nil) {\n\t\t\terr = io.EOF // FIXME in bstream lib, stepd hack\n\t\t}\n\n\t\tif err == io.EOF {\n\t\t\tif s.stopBlock != 0 {\n\t\t\t\tif s.lastBlockRef.Num() == s.stopBlock {\n\t\t\t\t\ts.logger.Info(\"reached our stop block\", zap.Stringer(\"last_block_ref\", s.lastBlockRef))\n\t\t\t\t\treturn firehose.ErrStopBlockReached\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"stream ended with EOF but last block seen %q does not match expected stop block %q\", s.lastBlockRef.Num(), s.stopBlock)\n\t\t\t}\n\n\t\t\tvar cursor string\n\t\t\tif response != nil {\n\t\t\t\tcursor = response.Cursor\n\t\t\t}\n\t\t\ts.logger.Error(\"received EOF when not expected, reconnecting\",\n\t\t\t\tzap.String(\"cursor\", cursor),\n\t\t\t\tzap.Stringer(\"last_block\", s.lastBlockRef),\n\t\t\t\tzap.Uint64(\"stop_block\", s.stopBlock),\n\t\t\t)\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\ts.logger.Error(\"stream encountered a remote error, retrying\",\n\t\t\t\tzap.Stringer(\"last_block\", s.lastBlockRef),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\treturn nil\n\t\t}\n\n\t\tblock := response.Block.(*pbcodec.Block)\n\t\ts.lastBlockRef = block.AsRef()\n\n\t\tunmarshalledBlocks <- &unmarshalledBlock{\n\t\t\tblock: block,\n\t\t\tcursor: response.Cursor,\n\t\t\tstep: response.Step,\n\t\t}\n\t}\n}", "func newStream(client *http.Client, req *http.Request) *Stream {\n\ts := &Stream{\n\t\tclient: client,\n\t\tMessages: make(chan *StreamData),\n\t\tdone: make(chan struct{}),\n\t\tgroup: &sync.WaitGroup{},\n\t}\n\ts.group.Add(1)\n\tgo s.retry(req, newExponentialBackOff(), newAggressiveExponentialBackOff())\n\treturn s\n}", "func newStreamProccessor(outs map[string]output.Output, kind, taskName string, properties map[string]interface{}, meta map[string]string) *streamProccessor {\n\tpr, pw := io.Pipe()\n\tscanner := bufio.NewScanner(pr)\n\tscanner.Split(sizeSpliter(maxLineSize, bufio.ScanLines))\n\tlocalProps := map[string]interface{}{\"stream\": kind}\n\tfor k, v := range properties {\n\t\tlocalProps[k] = v\n\t}\n\n\treturn &streamProccessor{\n\t\tscanner: scanner,\n\t\treader: pr,\n\t\tWriteCloser: pw,\n\t\toutputs: outs,\n\t\tkind: kind,\n\t\tproperties: localProps,\n\t\tmeta: meta,\n\t\tprocessor: semaas.NewSemaasProcessor(),\n\t\tfinish: make(chan struct{}),\n\t}\n}", "func newServerStream(\n\tctx context.Context,\n\tcancelCtx func(),\n\tchannel *ServerChannel,\n\tstream *webrtcpb.Stream,\n\tonDone func(id uint64),\n\tlogger golog.Logger,\n) *ServerStream {\n\tbs := newBaseStream(ctx, cancelCtx, stream, onDone, logger)\n\ts := &ServerStream{\n\t\tbaseStream: bs,\n\t\tch: channel,\n\t}\n\treturn s\n}", "func NewStream(\n\tURI string,\n\tstoringDirectory string,\n\tkeepFiles bool,\n\taudio bool,\n\tloggingOpts ProcessLoggingOpts,\n\twaitTimeOut time.Duration,\n) (*Stream, string) {\n\tid := uuid.New().String()\n\tpath := fmt.Sprintf(\"%s/%s\", storingDirectory, id)\n\terr := os.MkdirAll(path, os.ModePerm)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\treturn nil, \"\"\n\t}\n\tprocess := NewProcess(keepFiles, audio)\n\tcmd := process.Spawn(path, URI)\n\n\t// Create nil pointer in case logging is not enabled\n\tcmdLogger := (*lumberjack.Logger)(nil)\n\t// Create logger otherwise\n\tif loggingOpts.Enabled {\n\t\tcmdLogger = &lumberjack.Logger{\n\t\t\tFilename: fmt.Sprintf(\"%s/%s.log\", loggingOpts.Directory, id),\n\t\t\tMaxSize: loggingOpts.MaxSize,\n\t\t\tMaxBackups: loggingOpts.MaxBackups,\n\t\t\tMaxAge: loggingOpts.MaxAge,\n\t\t\tCompress: loggingOpts.Compress,\n\t\t}\n\t\tcmd.Stderr = cmdLogger\n\t\tcmd.Stdout = cmdLogger\n\t}\n\tstream := Stream{\n\t\tID: id,\n\t\tCMD: cmd,\n\t\tProcess: process,\n\t\tMux: &sync.Mutex{},\n\t\tPath: fmt.Sprintf(\"/%s/index.m3u8\", filepath.Join(\"stream\", id)),\n\t\tStorePath: path,\n\t\tStreak: hotstreak.New(hotstreak.Config{\n\t\t\tLimit: 10,\n\t\t\tHotWait: time.Minute * 2,\n\t\t\tActiveWait: time.Minute * 4,\n\t\t}).Activate(),\n\t\tOriginalURI: URI,\n\t\tKeepFiles: keepFiles,\n\t\tLoggingOpts: &loggingOpts,\n\t\tLogger: cmdLogger,\n\t\tRunning: false,\n\t\tWaitTimeOut: waitTimeOut,\n\t}\n\tlogrus.Debugf(\"%s store path created | Stream\", stream.StorePath)\n\treturn &stream, id\n}", "func newStream() *stream {\n\treturn &stream{}\n}", "func NewSub(w *model.Watcher, d *dao.Dao, c *conf.Config) (n *Sub, err error) {\n\tn = &Sub{\n\t\tc: c,\n\t\tw: w,\n\t\troutine: _defRoutine,\n\t\tbackoff: netutil.DefaultBackoffConfig,\n\t\tasyncRty: make(chan *rtyMsg, 100),\n\t\tdao: d,\n\t\tticker: time.NewTicker(time.Minute),\n\t}\n\tn.ctx, n.cancel = context.WithCancel(context.Background())\n\tif clu, ok := c.Clusters[w.Cluster]; ok {\n\t\tn.cluster = clu\n\t} else {\n\t\terr = errClusterNotSupport\n\t\treturn\n\t}\n\tif len(w.Filters) != 0 {\n\t\tn.parseFilter()\n\t}\n\terr = n.parseCallback()\n\tif err != nil {\n\t\terr = errCallbackParse\n\t\treturn\n\t}\n\t// init clients\n\tn.clients = NewClients(c, w)\n\terr = n.dial()\n\tif err != nil {\n\t\treturn\n\t}\n\tif w.Concurrent != 0 {\n\t\tn.routine = w.Concurrent\n\t}\n\tgo n.asyncRtyproc()\n\tfor i := 0; i < n.routine; i++ {\n\t\tgo n.serve()\n\t}\n\tcountProm.Incr(_opCurrentConsumer, w.Group, w.Topic)\n\treturn\n}", "func (t testConn) NewStream(ctx context.Context) (network.Stream, error) { return nil, nil }", "func (client *Client) NewStream(vbucket uint16, vuuid uint64,\n\topaque uint32) *Stream {\n\n\tstream := &Stream{\n\t\tClient: client,\n\t\tVuuid: vuuid,\n\t\tOpaque: opaque,\n\t\tautoRestart: false,\n\t\thealthy: false,\n\t\tqueue: make([]*mcd.MCRequest, 0),\n\t}\n\treturn stream\n}", "func newWrappedStream(s grpc.ServerStream) grpc.ServerStream {\n\treturn &wrappedStream{s}\n}", "func CreateChildStream(reading bool) (ChildStream, error) {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn NewChildSocketStream()\n\t} else {\n\t\treturn NewChildPipeStream(reading)\n\t}\n}", "func NewStreamCommand(command string, args []string) Interface {\n\treturn &StreamCommand{\n\t\tcmd: exec.Command(command, args...),\n\t}\n}", "func NewStream(reverse bool, manaul bool) *Streams {\n\n\t//our internal buffer\n\tlist := immute.CreateList(make([]interface{}, 0))\n\n\t//drain event handler\n\tdrains := NewEvent(\"drain\")\n\n\tsm := &Streams{\n\t\tNewRoller(),\n\t\tlist,\n\t\tdrains,\n\t\tmanaul,\n\t\treverse,\n\t\ttrue,\n\t}\n\n\tsm.ReceiveDone(func(data interface{}) {\n\t\tsm.finished = true\n\t\tsm.Stream()\n\t})\n\n\treturn sm\n}", "func newFileStream(ctx context.Context, wg *sync.WaitGroup, waker waker.Waker, pathname string, fi os.FileInfo, lines chan<- *logline.LogLine, streamFromStart bool) (LogStream, error) {\n\tfs := &fileStream{ctx: ctx, pathname: pathname, lastReadTime: time.Now(), lines: lines, stopChan: make(chan struct{})}\n\tif err := fs.stream(ctx, wg, waker, fi, streamFromStart); err != nil {\n\t\treturn nil, err\n\t}\n\treturn fs, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name returns the name of the StreamToSubStream process
func (p *StreamToSubStream) Name() string { return p.name }
[ "func (o *Echo) GetStreamName() string {\n\treturn \"\"\n}", "func (o *ExportStat) GetStreamName() string {\n\treturn \"\"\n}", "func (wc *WebContext) GetStreamName() string {\n\treturn mux.Vars(wc.Request)[\"stream\"]\n}", "func (o *Kanban) GetStreamName() string {\n\treturn \"\"\n}", "func (o StreamProcessorOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StreamProcessor) pulumi.StringPtrOutput { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (s *StreamInfo) Name() string {\n\treturn s.name\n}", "func (o StreamInputIotHubOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StreamInputIotHub) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (format *HttpStreamFormat) Name() string {\n return \"http-stream\"\n}", "func ReleaseStreamFor(name string) string {\n\tif name == LatestReleaseName {\n\t\treturn StableImageStream\n\t}\n\n\treturn fmt.Sprintf(\"%s-%s\", StableImageStream, name)\n}", "func (o TopicRuleKinesisOutput) StreamName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleKinesis) string { return v.StreamName }).(pulumi.StringOutput)\n}", "func ReleaseNameFrom(stream string) string {\n\tif stream == StableImageStream {\n\t\treturn LatestReleaseName\n\t}\n\n\treturn strings.TrimPrefix(stream, fmt.Sprintf(\"%s-\", StableImageStream))\n}", "func (provider *LegacyProvider) GetStreamName() string {\n\treturn provider.streamName\n}", "func (a *ExternalAgentProcess) Name() string {\n\treturn path.Base(a.cmd.Path)\n}", "func (o TopicRuleErrorActionKinesisOutput) StreamName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionKinesis) string { return v.StreamName }).(pulumi.StringOutput)\n}", "func (o *GetStreamingStatusParams) Name() string {\n\treturn \"GetStreamingStatus\"\n}", "func ChildProcessName(ctx context.Context) string {\n\tif v := ctx.Value(oversightValue(\"name\")); v != nil {\n\t\treturn v.(string)\n\t}\n\treturn \"\"\n}", "func (b *Binary) Name() string {\n\tif b.pr != 0 {\n\t\treturn fmt.Sprintf(\"minikube (PR %d)\", b.pr)\n\t}\n\treturn filepath.Base(b.path)\n}", "func (f *PidFile) Name() string {\n\treturn f.file.Name()\n}", "func (t *TransformCmd) Name() string {\n\treturn t.fs.Name()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
InPorts returns all the inports for the process
func (p *StreamToSubStream) InPorts() map[string]*scipipe.InPort { return map[string]*scipipe.InPort{ p.In.Name(): p.In, } }
[ "func getOpenPorts(n int) []string {\n\tports := []string{}\n\tfor i := 0; i < n; i++ {\n\t\tts := httptest.NewServer(http.NewServeMux())\n\t\tdefer ts.Close()\n\t\tu, err := url.Parse(ts.URL)\n\t\trtx.Must(err, \"Could not parse url to local server:\", ts.URL)\n\t\tports = append(ports, \":\"+u.Port())\n\t}\n\treturn ports\n}", "func exposedPorts(node *parser.Node) [][]string {\n\tvar allPorts [][]string\n\tvar ports []string\n\tfroms := FindAll(node, command.From)\n\texposes := FindAll(node, command.Expose)\n\tfor i, j := len(froms)-1, len(exposes)-1; i >= 0; i-- {\n\t\tfor ; j >= 0 && exposes[j] > froms[i]; j-- {\n\t\t\tports = append(nextValues(node.Children[exposes[j]]), ports...)\n\t\t}\n\t\tallPorts = append([][]string{ports}, allPorts...)\n\t\tports = nil\n\t}\n\treturn allPorts\n}", "func PortIn(vs ...string) predicate.Agent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldPort), v...))\n\t})\n}", "func getExposedPortsFromISI(image *imagev1.ImageStreamImage) ([]corev1.ContainerPort, error) {\n\t// file DockerImageMetadata\n\terr := imageWithMetadata(&image.Image)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ports []corev1.ContainerPort\n\n\tvar exposedPorts = image.Image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage).ContainerConfig.ExposedPorts\n\n\tif image.Image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage).Config != nil {\n\t\tif exposedPorts == nil {\n\t\t\texposedPorts = make(map[string]struct{})\n\t\t}\n\n\t\t// add ports from Config\n\t\tfor exposedPort := range image.Image.DockerImageMetadata.Object.(*dockerapiv10.DockerImage).Config.ExposedPorts {\n\t\t\tvar emptyStruct struct{}\n\t\t\texposedPorts[exposedPort] = emptyStruct\n\t\t}\n\t}\n\n\tfor exposedPort := range exposedPorts {\n\t\tsplits := strings.Split(exposedPort, \"/\")\n\t\tif len(splits) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid port %s\", exposedPort)\n\t\t}\n\n\t\tportNumberI64, err := strconv.ParseInt(splits[0], 10, 32)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid port number %s\", splits[0])\n\t\t}\n\t\tportNumber := int32(portNumberI64)\n\n\t\tvar portProto corev1.Protocol\n\t\tswitch strings.ToUpper(splits[1]) {\n\t\tcase \"TCP\":\n\t\t\tportProto = corev1.ProtocolTCP\n\t\tcase \"UDP\":\n\t\t\tportProto = corev1.ProtocolUDP\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid port protocol %s\", splits[1])\n\t\t}\n\n\t\tport := corev1.ContainerPort{\n\t\t\tName: fmt.Sprintf(\"%d-%s\", portNumber, strings.ToLower(string(portProto))),\n\t\t\tContainerPort: portNumber,\n\t\t\tProtocol: portProto,\n\t\t}\n\n\t\tports = append(ports, port)\n\t}\n\n\treturn ports, nil\n}", "func (j *ScheduledJob) ExposedPorts() (ExposedPortsIndex, error) {\n\tvar exposedPorts []ExposedPort\n\tfor name, sidecar := range j.Sidecars {\n\t\tout, err := sidecar.exposedPorts(name)\n\t\tif err != nil {\n\t\t\treturn ExposedPortsIndex{}, err\n\t\t}\n\t\texposedPorts = append(exposedPorts, out...)\n\t}\n\tportsForContainer, containerForPort := prepareParsedExposedPortsMap(sortExposedPorts(exposedPorts))\n\treturn ExposedPortsIndex{\n\t\tPortsForContainer: portsForContainer,\n\t\tContainerForPort: containerForPort,\n\t}, nil\n}", "func (in *instance) getContainerPorts(tainr *types.Container) []corev1.ContainerPort {\n\tres := []corev1.ContainerPort{}\n\tfor _, pp := range tainr.GetContainerTCPPorts() {\n\t\tn := fmt.Sprintf(\"kd-tcp-%d\", pp)\n\t\tres = append(res, corev1.ContainerPort{ContainerPort: int32(pp), Name: n, Protocol: corev1.ProtocolTCP})\n\t}\n\treturn res\n}", "func getContainerPorts(ports []echo.Port) model.PortList {\n\tcontainerPorts := make(model.PortList, 0, len(ports))\n\tvar healthPort *model.Port\n\tvar readyPort *model.Port\n\tfor _, p := range ports {\n\t\t// Add the port to the set of application ports.\n\t\tcport := &model.Port{\n\t\t\tName: p.Name,\n\t\t\tProtocol: p.Protocol,\n\t\t\tPort: p.InstancePort,\n\t\t}\n\t\tcontainerPorts = append(containerPorts, cport)\n\n\t\tswitch p.Protocol {\n\t\tcase model.ProtocolGRPC:\n\t\t\tcontinue\n\t\tcase model.ProtocolHTTP:\n\t\t\tif p.InstancePort == httpReadinessPort {\n\t\t\t\treadyPort = cport\n\t\t\t}\n\t\tdefault:\n\t\t\tif p.InstancePort == tcpHealthPort {\n\t\t\t\thealthPort = cport\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we haven't added the readiness/health ports, do so now.\n\tif readyPort == nil {\n\t\tcontainerPorts = append(containerPorts, &model.Port{\n\t\t\tName: \"http-readiness-port\",\n\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\tPort: httpReadinessPort,\n\t\t})\n\t}\n\tif healthPort == nil {\n\t\tcontainerPorts = append(containerPorts, &model.Port{\n\t\t\tName: \"tcp-health-port\",\n\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\tPort: tcpHealthPort,\n\t\t})\n\t}\n\treturn containerPorts\n}", "func ListPorts(exporter *BaseOpenStackExporter, ch chan<- prometheus.Metric) error {\n\tvar allPorts []PortBinding\n\n\tallPagesPorts, err := ports.List(exporter.Client, ports.ListOpts{}).AllPages()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ports.ExtractPortsInto(allPagesPorts, &allPorts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tportsWithNoIP := float64(0)\n\tlbaasPortsInactive := float64(0)\n\n\tfor _, port := range allPorts {\n\t\tif port.Status == \"ACTIVE\" && len(port.FixedIPs) == 0 {\n\t\t\tportsWithNoIP++\n\t\t}\n\n\t\tif port.DeviceOwner == \"neutron:LOADBALANCERV2\" && port.Status != \"ACTIVE\" {\n\t\t\tlbaasPortsInactive++\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"port\"].Metric,\n\t\t\tprometheus.GaugeValue, 1, port.ID, port.NetworkID, port.MACAddress, port.DeviceOwner, port.Status, port.VIFType, strconv.FormatBool(port.AdminStateUp))\n\t}\n\n\t// NOTE(mnaser): We should deprecate this and users can replace it by\n\t// count(openstack_neutron_port)\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports\"].Metric,\n\t\tprometheus.GaugeValue, float64(len(allPorts)))\n\n\t// NOTE(mnaser): We should deprecate this and users can replace it by:\n\t// count(openstack_neutron_port{device_owner=\"neutron:LOADBALANCERV2\",status!=\"ACTIVE\"})\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports_lb_not_active\"].Metric,\n\t\tprometheus.GaugeValue, lbaasPortsInactive)\n\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports_no_ips\"].Metric,\n\t\tprometheus.GaugeValue, portsWithNoIP)\n\n\treturn nil\n}", "func getContainerPorts(role *model.Role) ([]v1.ContainerPort, error) {\n\tresult := make([]v1.ContainerPort, 0, len(role.Run.ExposedPorts))\n\n\tfor _, port := range role.Run.ExposedPorts {\n\t\tvar protocol v1.Protocol\n\n\t\tswitch strings.ToLower(port.Protocol) {\n\t\tcase \"tcp\":\n\t\t\tprotocol = v1.ProtocolTCP\n\t\tcase \"udp\":\n\t\t\tprotocol = v1.ProtocolUDP\n\t\t}\n\n\t\t// Convert port range specifications to port numbers\n\t\tminInternalPort, maxInternalPort, err := parsePortRange(port.Internal, port.Name, \"internal\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// The external port is optional here; we only need it if it's public\n\t\tvar minExternalPort, maxExternalPort int32\n\t\tif port.External != \"\" {\n\t\t\tminExternalPort, maxExternalPort, err = parsePortRange(port.External, port.Name, \"external\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif port.External != \"\" && maxInternalPort-minInternalPort != maxExternalPort-minExternalPort {\n\t\t\treturn nil, fmt.Errorf(\"Port %s has mismatched internal and external port ranges %s and %s\",\n\t\t\t\tport.Name, port.Internal, port.External)\n\t\t}\n\n\t\tportInfos, err := getPortInfo(port.Name, minInternalPort, maxInternalPort)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, portInfo := range portInfos {\n\t\t\tresult = append(result, v1.ContainerPort{\n\t\t\t\tName: portInfo.name,\n\t\t\t\tContainerPort: portInfo.port,\n\t\t\t\tProtocol: protocol,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (client ProcessesClient) ListAcceptingPorts(ctx context.Context, resourceGroupName string, workspaceName string, machineName string, processName string, startTime *date.Time, endTime *date.Time) (result PortCollectionPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProcessesClient.ListAcceptingPorts\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.pc.Response.Response != nil {\n\t\t\t\tsc = result.pc.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 64, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `[a-zA-Z0-9_-]+`, Chain: nil}}},\n\t\t{TargetValue: workspaceName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"workspaceName\", Name: validation.MaxLength, Rule: 63, Chain: nil},\n\t\t\t\t{Target: \"workspaceName\", Name: validation.MinLength, Rule: 3, Chain: nil},\n\t\t\t\t{Target: \"workspaceName\", Name: validation.Pattern, Rule: `[a-zA-Z0-9_][a-zA-Z0-9_-]+[a-zA-Z0-9_]`, Chain: nil}}},\n\t\t{TargetValue: machineName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"machineName\", Name: validation.MaxLength, Rule: 64, Chain: nil},\n\t\t\t\t{Target: \"machineName\", Name: validation.MinLength, Rule: 3, Chain: nil}}},\n\t\t{TargetValue: processName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"processName\", Name: validation.MaxLength, Rule: 128, Chain: nil},\n\t\t\t\t{Target: \"processName\", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"servicemap.ProcessesClient\", \"ListAcceptingPorts\", err.Error())\n\t}\n\n\tresult.fn = client.listAcceptingPortsNextResults\n\treq, err := client.ListAcceptingPortsPreparer(ctx, resourceGroupName, workspaceName, machineName, processName, startTime, endTime)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListAcceptingPortsSender(req)\n\tif err != nil {\n\t\tresult.pc.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.pc, err = client.ListAcceptingPortsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func GetSandboxPorts() (map[nat.Port]struct{}, map[nat.Port][]nat.PortBinding, error) {\n\treturn nat.ParsePortSpecs([]string{\n\t\t\"0.0.0.0:30081:30081\", // Flyteconsole Port\n\t\t\"0.0.0.0:30082:30082\", // Flyteadmin Port\n\t\t\"0.0.0.0:30084:30084\", // Minio API Port\n\t\t\"0.0.0.0:30086:30086\", // K8s Dashboard Port\n\t\t\"0.0.0.0:30087:30087\", // Minio Console Port\n\t})\n}", "func (c *initMysql) getPorts() []corev1.ContainerPort {\n\treturn nil\n}", "func availablePorts(cnt int) ([]string, error) {\n\trtn := []string{}\n\n\tfor i := 0; i < cnt; i++ {\n\t\tport, err := getPort()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trtn = append(rtn, strconv.Itoa(port))\n\t}\n\treturn rtn, nil\n}", "func (c *auditLog) getPorts() []corev1.ContainerPort {\n\treturn nil\n}", "func (r *Container) ExposedPorts(ctx context.Context) ([]Port, error) {\n\tq := r.q.Select(\"exposedPorts\")\n\n\tq = q.Select(\"description port protocol\")\n\n\ttype exposedPorts struct {\n\t\tDescription string\n\t\tPort int\n\t\tProtocol NetworkProtocol\n\t}\n\n\tconvert := func(fields []exposedPorts) []Port {\n\t\tout := []Port{}\n\n\t\tfor i := range fields {\n\t\t\tout = append(out, Port{description: &fields[i].Description, port: &fields[i].Port, protocol: &fields[i].Protocol})\n\t\t}\n\n\t\treturn out\n\t}\n\tvar response []exposedPorts\n\n\tq = q.Bind(&response)\n\n\terr := q.Execute(ctx, r.c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn convert(response), nil\n}", "func getPodPorts(containers []v1.Container) []ocicni.PortMapping {\n\tvar infraPorts []ocicni.PortMapping\n\tfor _, container := range containers {\n\t\tfor _, p := range container.Ports {\n\t\t\tportBinding := ocicni.PortMapping{\n\t\t\t\tHostPort: p.HostPort,\n\t\t\t\tContainerPort: p.ContainerPort,\n\t\t\t\tProtocol: strings.ToLower(string(p.Protocol)),\n\t\t\t}\n\t\t\tif p.HostIP != \"\" {\n\t\t\t\tlogrus.Debug(\"HostIP on port bindings is not supported\")\n\t\t\t}\n\t\t\tinfraPorts = append(infraPorts, portBinding)\n\t\t}\n\t}\n\treturn infraPorts\n}", "func (in *instance) GetImageExposedPorts(img string) (map[string]struct{}, error) {\n\tcfg, err := image.InspectConfig(\"docker://\" + img)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg.Config.ExposedPorts, nil\n}", "func getPortsFromReader(file io.Reader) []int {\n\tvar ports []int\n\tres, err := parser.Parse(file)\n\tif err != nil {\n\t\treturn ports\n\t}\n\n\tfor _, child := range res.AST.Children {\n\t\t// check for the potential port number in a Dockerfile/Containerfile\n\t\tif strings.ToLower(child.Value) == \"expose\" {\n\t\t\tfor n := child.Next; n != nil; n = n.Next {\n\t\t\t\tif port, err := strconv.Atoi(n.Value); err == nil {\n\t\t\t\t\tports = append(ports, port)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn ports\n}", "func GetPorts(filename string) ([]int, error) {\n\tdata, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = NormalizeNewlines(data)\n\tlines := strings.Split(string(data), \"\\n\")\n\tports := []int{}\n\n\tfor _, line := range lines {\n\t\tmatch := findExposePortsRegEx.FindStringSubmatch(line)\n\t\tif match == nil || len(match) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tportStrings := strings.Split(match[1], \" \")\n\n\tOUTER:\n\t\tfor _, port := range portStrings {\n\t\t\tif port == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tintPort, err := strconv.Atoi(strings.Split(port, \"/\")[0])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Check if port already exists\n\t\t\tfor _, existingPort := range ports {\n\t\t\t\tif existingPort == intPort {\n\t\t\t\t\tcontinue OUTER\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tports = append(ports, intPort)\n\t\t}\n\t}\n\n\treturn ports, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
OutPorts returns all the outports for the process
func (p *StreamToSubStream) OutPorts() map[string]*scipipe.OutPort { return map[string]*scipipe.OutPort{ p.OutSubStream.Name(): p.OutSubStream, } }
[ "func exposedPorts(node *parser.Node) [][]string {\n\tvar allPorts [][]string\n\tvar ports []string\n\tfroms := FindAll(node, command.From)\n\texposes := FindAll(node, command.Expose)\n\tfor i, j := len(froms)-1, len(exposes)-1; i >= 0; i-- {\n\t\tfor ; j >= 0 && exposes[j] > froms[i]; j-- {\n\t\t\tports = append(nextValues(node.Children[exposes[j]]), ports...)\n\t\t}\n\t\tallPorts = append([][]string{ports}, allPorts...)\n\t\tports = nil\n\t}\n\treturn allPorts\n}", "func (d *Driver) Outs() (outs []drivers.Out, err error) {\n\tvar num int\n\tfor i := 0; i < portmidi.CountDevices(); i++ {\n\t\tinfo := portmidi.Info(portmidi.DeviceID(i))\n\t\t//\t\tfmt.Printf(\"%q devideID %v\\n\", info.Name, portmidi.DeviceID(i))\n\t\tif info != nil && info.IsOutputAvailable {\n\t\t\t//\t\tfmt.Printf(\"registering out port %q, number [%v], devideID %v\\n\", info.Name, num, portmidi.DeviceID(i))\n\t\t\touts = append(outs, newOut(d, portmidi.DeviceID(i), num, info.Name))\n\t\t\tnum++\n\t\t}\n\t}\n\treturn\n}", "func getOpenPorts(n int) []string {\n\tports := []string{}\n\tfor i := 0; i < n; i++ {\n\t\tts := httptest.NewServer(http.NewServeMux())\n\t\tdefer ts.Close()\n\t\tu, err := url.Parse(ts.URL)\n\t\trtx.Must(err, \"Could not parse url to local server:\", ts.URL)\n\t\tports = append(ports, \":\"+u.Port())\n\t}\n\treturn ports\n}", "func (j *ScheduledJob) ExposedPorts() (ExposedPortsIndex, error) {\n\tvar exposedPorts []ExposedPort\n\tfor name, sidecar := range j.Sidecars {\n\t\tout, err := sidecar.exposedPorts(name)\n\t\tif err != nil {\n\t\t\treturn ExposedPortsIndex{}, err\n\t\t}\n\t\texposedPorts = append(exposedPorts, out...)\n\t}\n\tportsForContainer, containerForPort := prepareParsedExposedPortsMap(sortExposedPorts(exposedPorts))\n\treturn ExposedPortsIndex{\n\t\tPortsForContainer: portsForContainer,\n\t\tContainerForPort: containerForPort,\n\t}, nil\n}", "func ToPorts(pp []v1.ServicePort) string {\n\tports := make([]string, len(pp))\n\tfor i, p := range pp {\n\t\tif len(p.Name) > 0 {\n\t\t\tports[i] = p.Name + \":\"\n\t\t}\n\t\tports[i] += strconv.Itoa(int(p.Port)) +\n\t\t\t\"►\" +\n\t\t\tstrconv.Itoa(int(p.NodePort))\n\t\tif p.Protocol != \"TCP\" {\n\t\t\tports[i] += \"╱\" + string(p.Protocol)\n\t\t}\n\t}\n\n\treturn strings.Join(ports, \" \")\n}", "func ListPorts(exporter *BaseOpenStackExporter, ch chan<- prometheus.Metric) error {\n\tvar allPorts []PortBinding\n\n\tallPagesPorts, err := ports.List(exporter.Client, ports.ListOpts{}).AllPages()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ports.ExtractPortsInto(allPagesPorts, &allPorts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tportsWithNoIP := float64(0)\n\tlbaasPortsInactive := float64(0)\n\n\tfor _, port := range allPorts {\n\t\tif port.Status == \"ACTIVE\" && len(port.FixedIPs) == 0 {\n\t\t\tportsWithNoIP++\n\t\t}\n\n\t\tif port.DeviceOwner == \"neutron:LOADBALANCERV2\" && port.Status != \"ACTIVE\" {\n\t\t\tlbaasPortsInactive++\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"port\"].Metric,\n\t\t\tprometheus.GaugeValue, 1, port.ID, port.NetworkID, port.MACAddress, port.DeviceOwner, port.Status, port.VIFType, strconv.FormatBool(port.AdminStateUp))\n\t}\n\n\t// NOTE(mnaser): We should deprecate this and users can replace it by\n\t// count(openstack_neutron_port)\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports\"].Metric,\n\t\tprometheus.GaugeValue, float64(len(allPorts)))\n\n\t// NOTE(mnaser): We should deprecate this and users can replace it by:\n\t// count(openstack_neutron_port{device_owner=\"neutron:LOADBALANCERV2\",status!=\"ACTIVE\"})\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports_lb_not_active\"].Metric,\n\t\tprometheus.GaugeValue, lbaasPortsInactive)\n\n\tch <- prometheus.MustNewConstMetric(exporter.Metrics[\"ports_no_ips\"].Metric,\n\t\tprometheus.GaugeValue, portsWithNoIP)\n\n\treturn nil\n}", "func getContainerPorts(ports []echo.Port) model.PortList {\n\tcontainerPorts := make(model.PortList, 0, len(ports))\n\tvar healthPort *model.Port\n\tvar readyPort *model.Port\n\tfor _, p := range ports {\n\t\t// Add the port to the set of application ports.\n\t\tcport := &model.Port{\n\t\t\tName: p.Name,\n\t\t\tProtocol: p.Protocol,\n\t\t\tPort: p.InstancePort,\n\t\t}\n\t\tcontainerPorts = append(containerPorts, cport)\n\n\t\tswitch p.Protocol {\n\t\tcase model.ProtocolGRPC:\n\t\t\tcontinue\n\t\tcase model.ProtocolHTTP:\n\t\t\tif p.InstancePort == httpReadinessPort {\n\t\t\t\treadyPort = cport\n\t\t\t}\n\t\tdefault:\n\t\t\tif p.InstancePort == tcpHealthPort {\n\t\t\t\thealthPort = cport\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we haven't added the readiness/health ports, do so now.\n\tif readyPort == nil {\n\t\tcontainerPorts = append(containerPorts, &model.Port{\n\t\t\tName: \"http-readiness-port\",\n\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\tPort: httpReadinessPort,\n\t\t})\n\t}\n\tif healthPort == nil {\n\t\tcontainerPorts = append(containerPorts, &model.Port{\n\t\t\tName: \"tcp-health-port\",\n\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\tPort: tcpHealthPort,\n\t\t})\n\t}\n\treturn containerPorts\n}", "func (test *Test) GetPorts(projectName string, ip string) ([]models.Port, error) {\n\treturn tests.NormalPorts, nil\n}", "func nodePorts(svcPorts []utils.ServicePort) []int64 {\n\tports := []int64{}\n\tfor _, p := range uniq(svcPorts) {\n\t\tif !p.NEGEnabled {\n\t\t\tports = append(ports, p.NodePort)\n\t\t}\n\t}\n\treturn ports\n}", "func ListSubports(port, workDir string) ([]string, error) {\n\tlistCmd := exec.Command(\"mpbb\", \"--work-dir\", workDir, \"list-subports\", \"--archive-site=\", \"--archive-site-private=\", port)\n\tstdout, err := listCmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = listCmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tsubports := make([]string, 0, 1)\n\tstdoutScanner := bufio.NewScanner(stdout)\n\tfor stdoutScanner.Scan() {\n\t\tline := stdoutScanner.Text()\n\t\tsubports = append(subports, line)\n\t}\n\tif err = listCmd.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn subports, nil\n}", "func (r *Container) ExposedPorts(ctx context.Context) ([]Port, error) {\n\tq := r.q.Select(\"exposedPorts\")\n\n\tq = q.Select(\"description port protocol\")\n\n\ttype exposedPorts struct {\n\t\tDescription string\n\t\tPort int\n\t\tProtocol NetworkProtocol\n\t}\n\n\tconvert := func(fields []exposedPorts) []Port {\n\t\tout := []Port{}\n\n\t\tfor i := range fields {\n\t\t\tout = append(out, Port{description: &fields[i].Description, port: &fields[i].Port, protocol: &fields[i].Protocol})\n\t\t}\n\n\t\treturn out\n\t}\n\tvar response []exposedPorts\n\n\tq = q.Bind(&response)\n\n\terr := q.Execute(ctx, r.c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn convert(response), nil\n}", "func (w Work) Ports() map[string]connector.Connector {\n\treturn w.Ports_\n}", "func (c *auditLog) getPorts() []corev1.ContainerPort {\n\treturn nil\n}", "func (c *initMysql) getPorts() []corev1.ContainerPort {\n\treturn nil\n}", "func PortsForTask(taskInfo *mesos.TaskInfo) map[docker.Port]struct{} {\n\tports := make(map[docker.Port]struct{}, len(taskInfo.Container.Docker.PortMappings))\n\n\tfor _, port := range taskInfo.Container.Docker.PortMappings {\n\t\tif port.ContainerPort == nil {\n\t\t\tcontinue\n\t\t}\n\t\tportStr := docker.Port(strconv.Itoa(int(*port.ContainerPort)) + \"/tcp\") // TODO UDP support?\n\t\tports[portStr] = struct{}{}\n\t}\n\n\tlog.Debugf(\"Ports: %#v\", ports)\n\n\treturn ports\n}", "func availablePorts(cnt int) ([]string, error) {\n\trtn := []string{}\n\n\tfor i := 0; i < cnt; i++ {\n\t\tport, err := getPort()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trtn = append(rtn, strconv.Itoa(port))\n\t}\n\treturn rtn, nil\n}", "func (s LifecyclerRPC) Ports(version string, flagValues map[string]interface{}) ([]string, error) {\n\tvar resp []string\n\terr := s.client.Call(\"Plugin.Ports\", HostOpts{Version: version, FlagValues: flagValues}, &resp)\n\treturn resp, err\n}", "func (client ProcessesClient) ListAcceptingPorts(ctx context.Context, resourceGroupName string, workspaceName string, machineName string, processName string, startTime *date.Time, endTime *date.Time) (result PortCollectionPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProcessesClient.ListAcceptingPorts\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.pc.Response.Response != nil {\n\t\t\t\tsc = result.pc.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 64, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `[a-zA-Z0-9_-]+`, Chain: nil}}},\n\t\t{TargetValue: workspaceName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"workspaceName\", Name: validation.MaxLength, Rule: 63, Chain: nil},\n\t\t\t\t{Target: \"workspaceName\", Name: validation.MinLength, Rule: 3, Chain: nil},\n\t\t\t\t{Target: \"workspaceName\", Name: validation.Pattern, Rule: `[a-zA-Z0-9_][a-zA-Z0-9_-]+[a-zA-Z0-9_]`, Chain: nil}}},\n\t\t{TargetValue: machineName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"machineName\", Name: validation.MaxLength, Rule: 64, Chain: nil},\n\t\t\t\t{Target: \"machineName\", Name: validation.MinLength, Rule: 3, Chain: nil}}},\n\t\t{TargetValue: processName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"processName\", Name: validation.MaxLength, Rule: 128, Chain: nil},\n\t\t\t\t{Target: \"processName\", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"servicemap.ProcessesClient\", \"ListAcceptingPorts\", err.Error())\n\t}\n\n\tresult.fn = client.listAcceptingPortsNextResults\n\treq, err := client.ListAcceptingPortsPreparer(ctx, resourceGroupName, workspaceName, machineName, processName, startTime, endTime)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListAcceptingPortsSender(req)\n\tif err != nil {\n\t\tresult.pc.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.pc, err = client.ListAcceptingPortsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"servicemap.ProcessesClient\", \"ListAcceptingPorts\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func getContainerPorts(role *model.Role) ([]v1.ContainerPort, error) {\n\tresult := make([]v1.ContainerPort, 0, len(role.Run.ExposedPorts))\n\n\tfor _, port := range role.Run.ExposedPorts {\n\t\tvar protocol v1.Protocol\n\n\t\tswitch strings.ToLower(port.Protocol) {\n\t\tcase \"tcp\":\n\t\t\tprotocol = v1.ProtocolTCP\n\t\tcase \"udp\":\n\t\t\tprotocol = v1.ProtocolUDP\n\t\t}\n\n\t\t// Convert port range specifications to port numbers\n\t\tminInternalPort, maxInternalPort, err := parsePortRange(port.Internal, port.Name, \"internal\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// The external port is optional here; we only need it if it's public\n\t\tvar minExternalPort, maxExternalPort int32\n\t\tif port.External != \"\" {\n\t\t\tminExternalPort, maxExternalPort, err = parsePortRange(port.External, port.Name, \"external\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif port.External != \"\" && maxInternalPort-minInternalPort != maxExternalPort-minExternalPort {\n\t\t\treturn nil, fmt.Errorf(\"Port %s has mismatched internal and external port ranges %s and %s\",\n\t\t\t\tport.Name, port.Internal, port.External)\n\t\t}\n\n\t\tportInfos, err := getPortInfo(port.Name, minInternalPort, maxInternalPort)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, portInfo := range portInfos {\n\t\t\tresult = append(result, v1.ContainerPort{\n\t\t\t\tName: portInfo.name,\n\t\t\t\tContainerPort: portInfo.port,\n\t\t\t\tProtocol: protocol,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn result, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run runs the StreamToSubStream
func (p *StreamToSubStream) Run() { defer p.OutSubStream.Close() scipipe.Debug.Println("Creating new information packet for the substream...") subStreamIP := scipipe.NewIP("") scipipe.Debug.Printf("Setting in-port of process %s to IP substream field\n", p.Name()) subStreamIP.SubStream = p.In scipipe.Debug.Printf("Sending sub-stream IP in process %s...\n", p.Name()) p.OutSubStream.Send(subStreamIP) scipipe.Debug.Printf("Done sending sub-stream IP in process %s.\n", p.Name()) }
[ "func (transmuxer *Transmuxer) Run() {\n\tif transmuxer.closed {\n\t\treturn\n\t}\n\n\tif transmuxer.running {\n\t\treturn\n\t}\n\n\ttransmuxer.running = true\n\n\tfor {\n\t\tvar sample float64\n\n\t\tfor _, streamer := range transmuxer.Streamers {\n\t\t\tnewSample, err := streamer.ReadSample()\n\t\t\tif err != nil {\n\t\t\t\tstreamer.setError(err)\n\t\t\t\tstreamer.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsample += newSample * streamer.Volume\n\t\t}\n\n\t\tsample = sample * transmuxer.MasterVolume\n\n\t\tif transmuxer.FinalStream != nil {\n\t\t\terr := transmuxer.FinalStream.WriteSample(sample)\n\t\t\tif err != nil {\n\t\t\t\ttransmuxer.setError(err)\n\t\t\t\ttransmuxer.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif transmuxer.buffer != nil {\n\t\t\ttransmuxer.buffer = append(transmuxer.buffer, sample)\n\t\t}\n\t}\n}", "func (p *Pipeline) Run() {\n\tin := make(chan Item)\n\tdefer close(in)\n\n\tvar wg sync.WaitGroup\n\twg.Add(p.numWorkers + 2)\n\n\tgo func() {\n\t\tdec := json.NewDecoder(p.source)\n\t\tfor {\n\t\t\tvar v Item\n\n\t\t\tif err := dec.Decode(&v); err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tp.debugf(\"Failed to decode object %s\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// push decoded JSON to the channel\n\t\t\tin <- v\n\t\t}\n\t}()\n\n\tout := p.process(p.ctx, in, &wg)\n\n\t// spawn n OUT streamers\n\tfor i := 0; i < p.numWorkers; i++ {\n\t\tgo p.stream(out, &wg)\n\t}\n\n\twg.Wait()\n}", "func (c *Copier) Run() {\n\tc.closed = make(chan struct{})\n\tgo c.logfile.ReadLogs(ReadConfig{Follow: true, Since: c.since, Tail: 0}, c.reader)\n\tgo c.copySrc()\n}", "func (pf ProcFn) Run(ctx context.Context, stream <-chan Msg) error { return pf(ctx, stream) }", "func (r *incomingStream) Run(\n\tctx context.Context,\n\tstopper *stop.Stopper,\n\t// The gRPC stream with incoming messages.\n\tstream ctpb.SideTransport_PushUpdatesServer,\n) error {\n\t// We have to do the stream processing on a separate goroutine because Recv()\n\t// is blocking, with no way to interrupt it other than returning from the RPC\n\t// handler (i.e. this Run function).\n\t// The main goroutine remains in charge of listening for stopper quiescence.\n\tstreamDone := make(chan struct{})\n\tif err := stopper.RunAsyncTask(ctx, \"closedts side-transport server conn\", func(ctx context.Context) {\n\t\t// On exit, signal the other goroutine to terminate.\n\t\tdefer close(streamDone)\n\t\tfor {\n\t\t\tmsg, err := stream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tif fn := r.testingKnobs.onRecvErr; fn != nil {\n\t\t\t\t\tfn(r.nodeID, err)\n\t\t\t\t}\n\t\t\t\tr.server.onRecvErr(ctx, r.nodeID, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif r.nodeID == 0 {\n\t\t\t\tr.nodeID = msg.NodeID\n\n\t\t\t\tif err := r.server.onFirstMsg(ctx, r, r.nodeID); err != nil {\n\t\t\t\t\tlog.Warningf(ctx, \"%s\", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t} else if ch := r.testingKnobs.onFirstMsg; ch != nil {\n\t\t\t\t\tch <- struct{}{}\n\t\t\t\t}\n\t\t\t\tif !msg.Snapshot {\n\t\t\t\t\tlog.Fatal(ctx, \"expected the first message to be a snapshot\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tr.processUpdate(ctx, msg)\n\t\t\tif ch := r.testingKnobs.onMsg; ch != nil {\n\t\t\t\tselect {\n\t\t\t\tcase ch <- msg:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t// Block until the client terminates (or there's another stream error) or\n\t// the stopper signals us to bail.\n\tselect {\n\tcase <-streamDone:\n\tcase <-stopper.ShouldQuiesce():\n\t}\n\t// Returning causes a blocked stream.Recv() (if there still is one) to return.\n\treturn nil\n}", "func RunStream(plugin plugin.YomoStreamPlugin, endpoint string) {\n\tlog.SetPrefix(fmt.Sprintf(\"[%s:%v]\", plugin.Name(), os.Getpid()))\n\tlog.Printf(\"plugin service start... [%s]\", endpoint)\n\n\t// binding plugin\n\tpluginStream := framework.NewStreamPlugin(plugin)\n\n\t// decoding\n\tdeStream1 := txtkv.NewStreamDecoder(plugin.Observed())\n\n\t//过滤\n\tdeStream2 := txtkv.NewFilterDecoder(plugin.Observed())\n\n\t// encoding\n\tenStream := txtkv.NewStreamEncoder(plugin.Observed())\n\n\tdeStream := io.MultiWriter(deStream1.Writer, deStream2.Writer)\n\n\t// activation service\n\tframework.NewServer(endpoint, deStream, enStream.Reader)\n\n\tgo func() { io.CopyN(pluginStream.Writer, deStream1.Reader, 1024) }() // nolint\n\tgo func() { io.CopyN(enStream.Writer, pluginStream.Reader, 1024) }() // nolint\n\tgo func() { io.CopyN(enStream.Writer, deStream2.Reader, 1024) }() // nolint\n}", "func (s *SyncManager) runStream(stream chan (ScheduledAction)) {\n\tn := time.Now()\n\tgo func() {\n\t\tfmt.Printf(\"Starting a new stream at %s\\n\", n)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase action := <-stream:\n\t\t\t\terr := action.Do()\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.errorHandler(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func (p *producer) runStream(ctx context.Context, interval time.Duration) (resetBackoff bool, err error) {\n\tstreamCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tstream, err := p.client.StreamCoreMetrics(streamCtx, &v3orcaservicepb.OrcaLoadReportRequest{\n\t\tReportInterval: durationpb.New(interval),\n\t})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor {\n\t\treport, err := stream.Recv()\n\t\tif err != nil {\n\t\t\treturn resetBackoff, err\n\t\t}\n\t\tresetBackoff = true\n\t\tp.mu.Lock()\n\t\tfor l := range p.listeners {\n\t\t\tl.OnLoadReport(report)\n\t\t}\n\t\tp.mu.Unlock()\n\t}\n}", "func (s *Streamer) Run() {\n\tpublishTimer := time.NewTicker(time.Duration(s.frameTimeMs) * time.Millisecond)\n\tfor {\n\t\t<-publishTimer.C\n\t\ts.SendFrame()\n\t}\n}", "func (s *S3Sink) Run(stopCh <-chan bool) {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-s.eventCh.Out():\n\t\t\tvar evt EventData\n\t\t\tvar ok bool\n\t\t\tif evt, ok = e.(EventData); !ok {\n\t\t\t\tglog.Warningf(\"Invalid type sent through event channel: %T\", e)\n\t\t\t\tcontinue loop\n\t\t\t}\n\n\t\t\t// Start with just this event...\n\t\t\tarr := []EventData{evt}\n\n\t\t\t// Consume all buffered events into an array, in case more have been written\n\t\t\t// since we last forwarded them\n\t\t\tnumEvents := s.eventCh.Len()\n\t\t\tfor i := 0; i < numEvents; i++ {\n\t\t\t\te := <-s.eventCh.Out()\n\t\t\t\tif evt, ok = e.(EventData); ok {\n\t\t\t\t\tarr = append(arr, evt)\n\t\t\t\t} else {\n\t\t\t\t\tglog.Warningf(\"Invalid type sent through event channel: %T\", e)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ts.drainEvents(arr)\n\t\tcase <-stopCh:\n\t\t\tbreak loop\n\t\t}\n\t}\n}", "func (a *ADSC) Run() error {\n\tvar err error\n\n\tctx := a.ctx\n\tif a.Config.XDSHeaders != nil {\n\t\tfor k, v := range a.Config.XDSHeaders {\n\t\t\tctx = metadata.AppendToOutgoingContext(ctx, k, v)\n\t\t}\n\t}\n\n\ta.conn, err = grpc.DialContext(ctx, a.url, a.GrpcOpts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"dial context: %v\", err)\n\t}\n\n\txds := discovery.NewAggregatedDiscoveryServiceClient(a.conn)\n\n\tedsstr, err := xds.StreamAggregatedResources(ctx, grpc.MaxCallRecvMsgSize(math.MaxInt32))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TD only returns an error after sending the first request.\n\ta.stream = edsstr\n\tgo a.handleRecv()\n\treturn nil\n}", "func (p *Concatenator) Run() {\n\tdefer p.CloseAllOutPorts()\n\n\toutFt := scipipe.NewFileIP(p.OutPath)\n\toutFh := outFt.OpenWriteTemp()\n\tfor ft := range p.In().Chan {\n\n\t\tfr := NewFileReader(p.Workflow(), p.Name()+\"_filereader_\"+getRandString(7))\n\t\tpop := scipipe.NewParamOutPort(\"temp_filepath_feeder\")\n\t\tpop.SetProcess(p)\n\t\tfr.InFilePath().Connect(pop)\n\t\tgo func() {\n\t\t\tdefer pop.Close()\n\t\t\tpop.Send(ft.Path())\n\t\t}()\n\n\t\tpip := scipipe.NewParamInPort(p.Name() + \"temp_line_reader\")\n\t\tpip.SetProcess(p)\n\t\tpip.Connect(fr.OutLine())\n\n\t\tgo fr.Run()\n\t\tfor line := range pip.Chan {\n\t\t\tscipipe.Debug.Println(\"Processing \", line, \"...\")\n\t\t\toutFh.Write([]byte(line))\n\t\t}\n\t}\n\toutFh.Close()\n\toutFt.Atomize()\n\tp.Out().Send(outFt)\n}", "func (obj *StorageST) StreamChannelRun(streamID string, channelID string) {\n\tobj.mutex.Lock()\n\tdefer obj.mutex.Unlock()\n\tif streamTmp, ok := obj.Streams[streamID]; ok {\n\t\tif channelTmp, ok := streamTmp.Channels[channelID]; ok {\n\t\t\tif !channelTmp.runLock {\n\t\t\t\tchannelTmp.runLock = true\n\t\t\t\tstreamTmp.Channels[channelID] = channelTmp\n\t\t\t\tobj.Streams[streamID] = streamTmp\n\t\t\t\tgo StreamServerRunStreamDo(streamID, channelID)\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *mutationStreamReader) run() {\n\n\t//panic handler\n\tdefer r.panicHandler()\n\n\tfor {\n\t\tselect {\n\n\t\tcase msg, ok := <-r.streamMutch:\n\n\t\t\tif ok {\n\t\t\t\tswitch msg.(type) {\n\t\t\t\tcase []*protobuf.VbKeyVersions:\n\t\t\t\t\tvbKeyVer := msg.([]*protobuf.VbKeyVersions)\n\t\t\t\t\tr.handleVbKeyVersions(vbKeyVer)\n\n\t\t\t\tdefault:\n\t\t\t\t\tr.handleStreamInfoMsg(msg)\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t//stream library has closed this channel indicating\n\t\t\t\t//unexpected stream closure send the message to supervisor\n\t\t\t\tlogging.Fatalf(\"MutationStreamReader::run Unexpected Mutation \"+\n\t\t\t\t\t\"Channel Close for Stream %v\", r.streamId)\n\t\t\t\tmsgErr := &MsgError{\n\t\t\t\t\terr: Error{code: ERROR_STREAM_READER_STREAM_SHUTDOWN,\n\t\t\t\t\t\tseverity: FATAL,\n\t\t\t\t\t\tcategory: STREAM_READER}}\n\t\t\t\tr.supvRespch <- msgErr\n\t\t\t}\n\n\t\tcase <-r.killch:\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func SubscriberRun(s *websocket.StructSpeaker) {\n\ts.Start()\n\tdefer s.Stop()\n\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\t<-ch\n}", "func (s *S3Consumer) Run(\n\tctx context.Context,\n\tmessageChan chan message,\n) error {\n\tobjectChan := make(chan s3ObjTask, s.NumWorkers)\n\terrChan := make(chan error, s.NumWorkers+1)\n\n\tfor i := 0; i < s.NumWorkers; i++ {\n\t\tgo func() {\n\t\t\terrChan <- s.runSubTasks(ctx, messageChan, objectChan)\n\t\t}()\n\t}\n\n\tgo func() {\n\t\terrChan <- s.processPrefixes(ctx, objectChan)\n\t\tclose(objectChan)\n\t}()\n\n\tfor i := 0; i < s.NumWorkers+1; i++ {\n\t\tif err := <-errChan; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *StreamCommand) Run(stdout io.Writer, stderr io.Writer, stdin io.Reader) error {\n\tif stdout == nil {\n\t\ts.cmd.Stdout = defaultStdout\n\t} else {\n\t\ts.cmd.Stdout = stdout\n\t}\n\n\tif stderr == nil {\n\t\ts.cmd.Stderr = defaultStderr\n\t} else {\n\t\ts.cmd.Stderr = stderr\n\t}\n\n\tif stdin != nil {\n\t\ts.cmd.Stdin = stdin\n\t}\n\n\treturn s.cmd.Run()\n}", "func (t *Task) Run() error {\n\tif t.Handler == nil {\n\t\treturn fmt.Errorf(\"command not found: %s\", t.Name)\n\t}\n\n\tt.Start = time.Now()\n\tt.Status = t.Handler(t)\n\tt.Stop = time.Now()\n\n\tif err := t.OutputStream.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.ErrorStream.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (codec *BinaryCodec) Run() {\n\tlog.Print(\"Inside binaryCodec run\")\n\n\t// buffer.Grow(4096)\n\t//\n\t// f, err := os.OpenFile(\"test.log\", os.O_WRONLY|os.O_CREATE, 0777)\n\t// if err != nil {\n\t// \t//t.Fatalf(\"error opening file: %v\", err)\n\t// }\n\t// defer f.Close()\n\t//\n\t// log.SetOutput(f)\n\n\tfor {\n\t\tselect {\n\t\tcase d := <-codec.Write:\n\t\t\t//log.Print(\"Start write data to codec\")\n\t\t\t//log.Printf(\"Decoding binary data: %d\", len(d))\n\n\t\t\tif codec.IsClosing {\n\t\t\t\tlog.Print(\"Closing the binary codec\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//log.Print(\"End binarycodec run write\")\n\t\t\tselect {\n\t\t\tcase codec.bufferIncoming <- d: // Buffer the data to decode\n\t\t\tdefault:\n\t\t\t\tlog.Print(\"Error writing data to buffer\")\n\t\t\t}\n\t\t\t//log.Print(\"Stop write data to codec\")\n\t\tcase d := <-codec.bufferIncoming:\n\t\t\t//log.Print(\"Start write data to buffer\")\n\t\t\t//mutex.Lock()\n\n\t\t\t// Add the data to the buffer\n\t\t\t_, err := buffer.Write(d)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t}\n\n\t\t\t//log.Printf(\"AddBuffer size: %d\", buffer.Len())\n\t\t\t//log.Printf(\"AddBuffer size: %d\", len(d))\n\n\t\t\t// Decode the data\n\t\t\tdecodeIncomingData(codec)\n\n\t\t\t//mutex.Unlock()\n\t\t\t//log.Print(\"Stop write data to buffer\")\n\t\tdefault:\n\t\t\t//log.Print(\"Error in codec\")\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reconcileStorage will ensure that the storage options for the ArgoCDExport are present.
func (r *ReconcileArgoCDExport) reconcileStorage(cr *argoprojv1a1.ArgoCDExport) error { if cr.Spec.Storage == nil { cr.Spec.Storage = &argoprojv1a1.ArgoCDExportStorageSpec{ Backend: common.ArgoCDExportStorageBackendLocal, } return r.Client.Update(context.TODO(), cr) } // Local storage if err := r.reconcileLocalStorage(cr); err != nil { return err } return nil }
[ "func (p *PBM) ResyncStorage(l *log.Event) error {\n\tstg, err := p.GetStorage(l)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to get backup store\")\n\t}\n\n\t_, err = stg.FileStat(StorInitFile)\n\tif errors.Is(err, storage.ErrNotExist) {\n\t\terr = stg.Save(StorInitFile, bytes.NewBufferString(version.DefaultInfo.Version), 0)\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"init storage\")\n\t}\n\n\tbcps, err := stg.List(\"\", MetadataFileSuffix)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get a backups list from the storage\")\n\t}\n\n\terr = p.moveCollection(BcpCollection, BcpOldCollection)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"copy current backups meta from %s to %s\", BcpCollection, BcpOldCollection)\n\t}\n\terr = p.moveCollection(PITRChunksCollection, PITRChunksOldCollection)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"copy current pitr meta from %s to %s\", PITRChunksCollection, PITRChunksOldCollection)\n\t}\n\n\tif len(bcps) == 0 {\n\t\treturn nil\n\t}\n\n\tvar ins []interface{}\n\tfor _, b := range bcps {\n\t\td, err := stg.SourceReader(b.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"read meta for %v\", b.Name)\n\t\t}\n\n\t\tv := BackupMeta{}\n\t\terr = json.NewDecoder(d).Decode(&v)\n\t\td.Close()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unmarshal backup meta\")\n\t\t}\n\t\terr = checkBackupFiles(&v, stg)\n\t\tif err != nil {\n\t\t\tl.Warning(\"skip snapshot %s: %v\", v.Name, err)\n\t\t\tcontinue\n\t\t}\n\t\tins = append(ins, v)\n\t}\n\t_, err = p.Conn.Database(DB).Collection(BcpCollection).InsertMany(p.ctx, ins)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"insert retrieved backups meta\")\n\t}\n\n\tpitrf, err := stg.List(PITRfsPrefix, \"\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get list of pitr chunks\")\n\t}\n\tif len(pitrf) == 0 {\n\t\treturn nil\n\t}\n\n\tvar pitr []interface{}\n\tfor _, f := range pitrf {\n\t\t_, err := stg.FileStat(PITRfsPrefix + \"/\" + f.Name)\n\t\tif err != nil {\n\t\t\tl.Warning(\"skip pitr chunk %s/%s because of %v\", PITRfsPrefix, f.Name, err)\n\t\t\tcontinue\n\t\t}\n\t\tchnk := PITRmetaFromFName(f.Name)\n\t\tif chnk != nil {\n\t\t\tpitr = append(pitr, chnk)\n\t\t}\n\t}\n\n\tif len(pitr) == 0 {\n\t\treturn nil\n\t}\n\n\t_, err = p.Conn.Database(DB).Collection(PITRChunksCollection).InsertMany(p.ctx, pitr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"insert retrieved pitr meta\")\n\t}\n\n\treturn nil\n}", "func (r *ReconcileStorageOSUpgrade) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\tlog := log.WithValues(\"Request.Namespace\", request.Namespace, \"Request.Name\", request.Name)\n\t// log.Info(\"Reconciling Upgrade\")\n\n\treconcilePeriod := 10 * time.Second\n\treconcileResult := reconcile.Result{RequeueAfter: reconcilePeriod}\n\n\t// Return this for a immediate retry of the reconciliation loop with the\n\t// same request object.\n\timmediateRetryResult := reconcile.Result{Requeue: true}\n\n\t// Fetch the StorageOSUpgrade instance\n\tinstance := &storageosv1.StorageOSUpgrade{}\n\terr := r.client.Get(context.TODO(), request.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Upgrade instance not found. Reset the current cluster.\n\t\t\t// In this order: resume cluster, reset cluster, reset upgrade.\n\t\t\tif err := r.resumeCluster(request); err != nil {\n\t\t\t\treturn immediateRetryResult, err\n\t\t\t}\n\t\t\tr.resetImagePuller(request)\n\t\t\tr.resetCurrentCluster(request)\n\t\t\tr.ResetCurrentUpgrade(request)\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue.\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn immediateRetryResult, err\n\t}\n\n\tr.SetCurrentUpgradeIfNone(instance)\n\n\t// Check if it's the only upgrade before continuing.\n\tif !r.IsCurrentUpgrade(instance) {\n\t\terr := fmt.Errorf(\"can't create more than one storageos upgrade\")\n\t\tr.recorder.Event(instance, corev1.EventTypeWarning, \"FailedCreation\", err.Error())\n\t\t// Don't requeue. This is a failed upgrade.\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Pull image.\n\tif r.imagePuller == nil {\n\t\t// Get the current cluster. Use this to define node selector for image\n\t\t// puller job, based on the cluster's node selector.\n\t\tcurrentCluster, err := r.findCurrentCluster()\n\t\tif err != nil {\n\t\t\tlog.Info(\"Failed to find current cluster\", \"error\", err)\n\t\t\tinstance.Status.Completed = false\n\t\t\tif updateErr := r.client.Status().Update(context.Background(), instance); updateErr != nil {\n\t\t\t\terr = fmt.Errorf(\"%v,%v\", updateErr, err)\n\t\t\t}\n\t\t\t// Re-queue if it fails to get the current cluster.\n\t\t\treturn immediateRetryResult, err\n\t\t}\n\t\t// Create image puller.\n\t\tr.imagePuller = newImagePullJob(instance, currentCluster)\n\t\tif err := controllerutil.SetControllerReference(instance, r.imagePuller, r.scheme); err != nil {\n\t\t\treturn immediateRetryResult, err\n\t\t}\n\t\tif err := r.client.Create(context.Background(), r.imagePuller); err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn immediateRetryResult, fmt.Errorf(\"failed to create image puller job: %v\", err)\n\t\t}\n\n\t\tr.recorder.Event(instance, corev1.EventTypeNormal, \"PullImage\", \"Pulling the new container image\")\n\n\t\t// Re-queue, let the puller create and continue.\n\t\treturn reconcileResult, nil\n\t}\n\n\t// Update the image puller instance and check if it has completed.\n\tnsdName := types.NamespacedName{\n\t\tName: r.imagePuller.Name,\n\t\tNamespace: r.imagePuller.Namespace,\n\t}\n\terr = r.client.Get(context.TODO(), nsdName, r.imagePuller)\n\tif err != nil {\n\t\tlog.Info(\"Failed to fetch image puller status\", \"error\", err)\n\t}\n\t// Re-queue if the image pull didn't complete.\n\tif !r.imagePuller.Status.Completed {\n\t\terr := fmt.Errorf(\"image pull didn't complete\")\n\t\tinstance.Status.Completed = false\n\t\tif updateErr := r.client.Update(context.Background(), instance); updateErr != nil {\n\t\t\terr = fmt.Errorf(\"%v, %v\", updateErr, err)\n\t\t}\n\t\treturn reconcileResult, err\n\t}\n\n\t// Find and pause the running cluster.\n\tif r.currentCluster == nil {\n\t\tif err := r.findAndSetCurrentCluster(); err != nil {\n\t\t\treturn reconcileResult, err\n\t\t}\n\t\tif err := r.pauseCluster(); err != nil {\n\t\t\treturn reconcileResult, err\n\t\t}\n\t\tr.recorder.Event(instance, corev1.EventTypeNormal, \"PauseClusterCtrl\", \"Pausing the cluster controller and enabling cluster maintenance mode\")\n\t}\n\n\t// Create a ServiceAccount for the upgrader.\n\tsa := newServiceAccountForCR(\"storageos-upgrader-sa\", instance)\n\tif err := controllerutil.SetControllerReference(instance, sa, r.scheme); err != nil {\n\t\treturn reconcileResult, err\n\t}\n\tif err := r.client.Create(context.Background(), sa); err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn reconcileResult, fmt.Errorf(\"failed to create service account: %v\", err)\n\t}\n\n\t// Create a ClusterRole for the upgrader.\n\t// This must cluster scoped because the applications can be in any namespace.\n\trules := []rbacv1.PolicyRule{\n\t\t{\n\t\t\tAPIGroups: []string{\"apps\"},\n\t\t\tResources: []string{\"daemonsets\", \"deployments\", \"statefulsets\"},\n\t\t\tVerbs: []string{\"get\", \"list\", \"update\", \"patch\"},\n\t\t},\n\t\t{\n\t\t\tAPIGroups: []string{\"\"},\n\t\t\tResources: []string{\"pods\"},\n\t\t\tVerbs: []string{\"get\", \"list\"},\n\t\t},\n\t\t{\n\t\t\tAPIGroups: []string{\"\"},\n\t\t\tResources: []string{\"persistentvolumeclaims\"},\n\t\t\tVerbs: []string{\"get\", \"list\"},\n\t\t},\n\t\t{\n\t\t\tAPIGroups: []string{\"storage.k8s.io\"},\n\t\t\tResources: []string{\"storageclasses\"},\n\t\t\tVerbs: []string{\"get\", \"list\"},\n\t\t},\n\t}\n\tcr := newClusterRole(\"storageos-upgrader-role\", rules)\n\tif err := controllerutil.SetControllerReference(instance, cr, r.scheme); err != nil {\n\t\treturn reconcileResult, err\n\t}\n\tif err := r.client.Create(context.Background(), cr); err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn reconcileResult, fmt.Errorf(\"failed to create cluster role: %v\", err)\n\t}\n\n\t// Create ClusterRoleBinding for the ServiceAccount.\n\tsubjects := []rbacv1.Subject{\n\t\t{\n\t\t\tKind: rbacv1.ServiceAccountKind,\n\t\t\tName: \"storageos-upgrader-sa\",\n\t\t\tNamespace: instance.GetNamespace(),\n\t\t},\n\t}\n\troleRef := rbacv1.RoleRef{\n\t\tKind: \"ClusterRole\",\n\t\tName: cr.GetName(),\n\t\tAPIGroup: rbacv1.GroupName,\n\t}\n\tcrb := newClusterRoleBinding(\"storageos-upgrader-clusterrolebinding\", subjects, roleRef)\n\tif err := controllerutil.SetControllerReference(instance, crb, r.scheme); err != nil {\n\t\treturn reconcileResult, err\n\t}\n\tif err := r.client.Create(context.Background(), crb); err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn reconcileResult, fmt.Errorf(\"failed to create cluster role binding: %v\", err)\n\t}\n\n\t// Define a new Job object.\n\tjob := newJobForCR(instance)\n\n\t// Set StorageOSUpgrade instance as the owner and controller.\n\tif err := controllerutil.SetControllerReference(instance, job, r.scheme); err != nil {\n\t\treturn reconcileResult, err\n\t}\n\n\t// Check if this Job already exists.\n\tfound := &batchv1.Job{}\n\terr = r.client.Get(context.TODO(), types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\terr = r.client.Create(context.TODO(), job)\n\t\tif err != nil {\n\t\t\treturn reconcileResult, err\n\t\t}\n\n\t\t// Job created successfully - requeue.\n\t\t// Requeue is needed here to enable repeated check on the upgrade\n\t\t// process.\n\t\tupgradeInitMessage := fmt.Sprintf(\"StorageOS upgrade of cluster %s started\", r.currentCluster.GetName())\n\t\tr.recorder.Event(instance, corev1.EventTypeNormal, \"UpgradeInit\", upgradeInitMessage)\n\t\treturn reconcileResult, nil\n\t} else if err != nil {\n\t\treturn reconcileResult, err\n\t}\n\n\tif r.currentUpgrade.Status.Completed {\n\t\t// Upgrade completed. Do nothing.\n\t\treturn reconcileResult, nil\n\t}\n\n\tif found.Status.Succeeded == 1 {\n\t\tr.currentUpgrade.Status.Completed = true\n\t\tsuccessMessage := fmt.Sprintf(\"StorageOS upgraded to %s. Delete upgrade object to disable cluster maintenance mode\", instance.Spec.NewImage)\n\t\tr.recorder.Event(instance, corev1.EventTypeNormal, \"UpgradeComplete\", successMessage)\n\t}\n\n\treturn reconcileResult, nil\n}", "func (r *ReconcileLogStorage) reconcileManaged(ctx context.Context, network *operatorv1.Installation, reqLogger logr.Logger) (reconcile.Result, error) {\n\tif _, err := GetLogStorage(ctx, r.client); err == nil {\n\t\treturn reconcile.Result{}, fmt.Errorf(\"cluster type is Managed but logstorage still exists\")\n\t} else if !errors.IsNotFound(err) {\n\t\tr.status.SetDegraded(\"Failed to get LogStorage CR\", err.Error())\n\t\treturn reconcile.Result{}, err\n\t}\n\n\thdler := utils.NewComponentHandler(log, r.client, r.scheme, network)\n\tcomponent := render.ElasticsearchManaged(r.localDNS, r.provider)\n\tif err := hdler.CreateOrUpdate(ctx, component, r.status); err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn reconcile.Result{}, nil\n}", "func configureStorage(dep *appsv1.Deployment, nodeSet v1alpha1.NodeSet) error {\n\tif nuxeoContainer, err := GetNuxeoContainer(dep); err != nil {\n\t\treturn err\n\t} else {\n\t\tfor _, storage := range nodeSet.Storage {\n\t\t\tif volume, err := createVolumeForStorage(storage); err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tvolMnt := createVolumeMountForStorage(storage.StorageType, volume.Name)\n\t\t\t\tenvVar := createEnvVarForStorage(storage.StorageType, volMnt.MountPath)\n\t\t\t\tif err := util.OnlyAddVol(dep, volume); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := util.OnlyAddVolMnt(nuxeoContainer, volMnt); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif envVar != (corev1.EnvVar{}) {\n\t\t\t\t\tif err := util.OnlyAddEnvVar(nuxeoContainer, envVar); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func CleanupArtifactStorage(pr *v1alpha1.PipelineRun, c kubernetes.Interface, logger *zap.SugaredLogger) error {\n\tconfigMap, err := c.CoreV1().ConfigMaps(system.GetNamespace()).Get(v1alpha1.BucketConfigName, metav1.GetOptions{})\n\tshouldCreatePVC, err := ConfigMapNeedsPVC(configMap, err, logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif shouldCreatePVC {\n\t\terr = deletePVC(pr, c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MinIOReconciler) Reconcile() (*lcm.CRStatus, error) {\n\tvar minioCR minio.Tenant\n\tif m.HarborCluster.Spec.Storage.Kind != inClusterStorage {\n\t\tvar exSecret corev1.Secret\n\t\terr := m.KubeClient.Get(m.getExternalSecretNamespacedName(), &exSecret)\n\t\tif k8serror.IsNotFound(err) {\n\t\t\treturn m.ProvisionExternalStorage()\n\t\t} else if err != nil {\n\t\t\treturn minioNotReadyStatus(GetExternalSecretError, err.Error()), err\n\t\t}\n\n\t\tm.CurrentExternalSecret = &exSecret\n\t\tm.DesiredExternalSecret, err = m.generateExternalSecret()\n\t\tif err != nil {\n\t\t\treturn minioNotReadyStatus(err.Error(), err.Error()), err\n\t\t}\n\n\t\tif m.checkExternalUpdate() {\n\t\t\treturn m.ExternalUpdate()\n\t\t}\n\n\t\tp := &lcm.Property{\n\t\t\tName: m.HarborCluster.Spec.Storage.Kind + ExternalStorageSecretSuffix,\n\t\t\tValue: m.getExternalSecretName(),\n\t\t}\n\t\tproperties := &lcm.Properties{p}\n\n\t\treturn minioReadyStatus(properties), nil\n\t}\n\n\tm.DesiredMinIOCR = m.generateMinIOCR()\n\n\terr := m.KubeClient.Get(m.getMinIONamespacedName(), &minioCR)\n\tif k8serror.IsNotFound(err) {\n\t\treturn m.Provision()\n\t} else if err != nil {\n\t\treturn minioNotReadyStatus(GetMinIOError, err.Error()), err\n\t}\n\n\tm.CurrentMinIOCR = &minioCR\n\n\t// TODO remove scale event\n\tisScale, err := m.checkMinIOScale()\n\tif err != nil {\n\t\treturn minioNotReadyStatus(ScaleMinIOError, err.Error()), err\n\t}\n\tif isScale {\n\t\treturn m.Scale()\n\t}\n\n\tif m.checkMinIOUpdate() {\n\t\treturn m.Update()\n\t}\n\tisReady, err := m.checkMinIOReady()\n\tif err != nil {\n\t\treturn minioNotReadyStatus(GetMinIOError, err.Error()), err\n\t}\n\n\tif isReady {\n\t\terr := m.minioInit()\n\t\tif err != nil {\n\t\t\treturn minioNotReadyStatus(CreateDefaultBucketError, err.Error()), err\n\t\t}\n\t\treturn m.ProvisionInClusterSecretAsS3(&minioCR)\n\t}\n\n\treturn minioUnknownStatus(), nil\n}", "func (s *Store) CompactStorage(entityKey string, threshold uint64) (err error) {\n\tvar repoSize, newRepoSize uint64\n\trepoSize, err = s.StorageSize(s.CacheDir)\n\tif err == nil && repoSize > 0 && repoSize > threshold {\n\t\tcslog := slog.WithFieldsF(func() logrus.Fields {\n\t\t\treturn logrus.Fields{\"repoSize\": repoSize, \"threshold\": threshold, \"entityKey\": entityKey}\n\t\t})\n\n\t\tcslog.Debug(\"Local repo size exceeds compaction threshold. Compacting.\")\n\t\tif err = s.compactCacheStorage(entityKey, threshold); err != nil {\n\t\t\treturn\n\t\t}\n\t\tnewRepoSize, err = s.StorageSize(s.CacheDir)\n\t\tif nil != err {\n\t\t\treturn\n\t\t}\n\n\t\tcslog.WithFieldsF(func() logrus.Fields {\n\t\t\tsavedPct := (float64(repoSize-newRepoSize) / float64(repoSize)) * 100\n\t\t\treturn logrus.Fields{\"newRepoSize\": newRepoSize, \"savedPercentage\": savedPct}\n\t\t}).Debug(\"Local repo compacted.\")\n\n\t\terr = s.SaveState()\n\t}\n\treturn\n}", "func (r *MetadataRestoreReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {\n\tctx := context.Background()\n\n\tvar mr kubedrv1alpha1.MetadataRestore\n\tif err := r.Get(ctx, req.NamespacedName, &mr); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// we'll ignore not-found errors, since they can't be fixed by an immediate\n\t\t\t// requeue (we'll need to wait for a new notification).\n\t\t\tr.Log.Info(\"MetadataRestore (\" + req.NamespacedName.Name + \") is not found\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\n\t\tr.Log.Error(err, \"unable to fetch MetadataRestore\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Skip if spec hasn't changed. This check prevents reconcile on status\n\t// updates.\n\tif mr.Status.ObservedGeneration == mr.ObjectMeta.Generation {\n\t\tr.Log.Info(\"Skipping reconcile as generation number hasn't changed\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\t// No deletion logic as we don't really have anything to do during\n\t// deletion of a MetadataRestore resource.\n\n\t// Check annotations to see if this resource was already processed\n\t// and restore was successful.\n\trestoreAnnotation := \"restored.annotations.kubedr.catalogicsoftware.com\"\n\n\trestored, exists := mr.ObjectMeta.Annotations[restoreAnnotation]\n\tif exists && (restored == \"true\") {\n\t\t// No need to process the resource as restore was done already.\n\t\tr.Log.Info(\"Restore was already done\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\t// We are deliberately avoiding any attempt to make the name unique.\n\t// The client is in a better position to come up with a unique name.\n\t// If we do switch to generating a unique name, we need to make sure\n\t// that any previous pods are cleaned up.\n\tpodName := mr.Name + \"-mr\"\n\n\t// Since we don't generate a unique name for the pod that initializes the repo,\n\t// we need to explicitly check and delete the pod if it exists.\n\tvar prevPod corev1.Pod\n\tif err := r.Get(ctx, types.NamespacedName{Namespace: req.Namespace, Name: podName}, &prevPod); err == nil {\n\t\tr.Log.Info(\"Found a previous restore pod, will delete it and continue...\")\n\t\tif err := r.Delete(ctx, &prevPod); ignoreNotFound(err) != nil {\n\t\t\tr.Log.Error(err, \"Error in deleting init pod\")\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t}\n\n\tpod, err := r.buildRestorePod(&mr, req.Namespace, podName)\n\tif err != nil {\n\t\tr.Log.Error(err, \"Error in creating restore pod\")\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// This shouldn't really happen but if an invalid MBR is given or\n\t\t\t// if backup location inside the MBR is wrong, there is nothing we can\n\t\t\t// do.\n\t\t\tr.setStatus(&mr, \"Failed\",\n\t\t\t\tfmt.Sprintf(\"Error in creating restore pod, reason (%s)\", err.Error()))\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif err := ctrl.SetControllerReference(&mr, pod, r.Scheme); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tr.Log.Info(\"Starting a new Pod\", \"Pod.Namespace\", pod.Namespace, \"Pod.Name\", pod.Name)\n\terr = r.Create(ctx, pod)\n\tif err != nil {\n\t\tr.Log.Error(err, \"Error in starting restore pod\")\n\t\tr.setStatus(&mr, \"Failed\", err.Error())\n\t\treturn ctrl.Result{}, err\n\t}\n\n\treturn ctrl.Result{}, nil\n}", "func (o *MicrosoftGraphAndroidGeneralDeviceConfiguration) HasStorageRequireRemovableStorageEncryption() bool {\n\tif o != nil && o.StorageRequireRemovableStorageEncryption != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *deletedReconciler) Reconcile(ctx context.Context, in *marketplace.OperatorSource) (out *marketplace.OperatorSource, nextPhase *marketplace.Phase, err error) {\n\tout = in\n\n\t// Delete the operator source manifests.\n\tr.datastore.RemoveOperatorSource(out.UID)\n\n\t// Delete the owned CatalogSourceConfig\n\terr = r.deleteCreatedResources(ctx, in.Name, in.Namespace)\n\tif err != nil {\n\t\t// Something went wrong before we removed the finalizer, let's retry.\n\t\tnextPhase = phase.GetNextWithMessage(in.Status.CurrentPhase.Name, err.Error())\n\t\treturn\n\t}\n\n\t// Remove the opsrc finalizer from the object.\n\tout.RemoveFinalizer()\n\n\t// Update the client. Since there is no phase shift, the transitioner\n\t// will not update it automatically like the normal phases.\n\terr = r.client.Update(context.TODO(), out)\n\tif err != nil {\n\t\t// An error happened on update. If it was transient, we will retry.\n\t\t// If not, and the finalizer was removed, then the delete will clean\n\t\t// the object up anyway. Let's set the next phase for a possible retry.\n\t\tnextPhase = phase.GetNextWithMessage(in.Status.CurrentPhase.Name, err.Error())\n\t\treturn\n\t}\n\n\tr.logger.Info(\"Finalizer removed, now garbage collector will clean it up.\")\n\n\treturn\n}", "func (r *succeededReconciler) Reconcile(ctx context.Context, in *v2.CatalogSourceConfig) (out *v2.CatalogSourceConfig, nextPhase *shared.Phase, err error) {\n\tif in.Status.CurrentPhase.Name != phase.Succeeded {\n\t\terr = phase.ErrWrongReconcilerInvoked\n\t\treturn\n\t}\n\n\t// No change is being made, so return the CatalogSourceConfig object as is.\n\tout = in\n\n\tmsg := \"No action taken, the object has already been reconciled\"\n\n\t// Always log the message.\n\tdefer func() {\n\t\tr.log.Info(msg)\n\t}()\n\n\tsecretIsPresent, err := r.isSecretPresent(in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif watches.CheckChildResources(r.client, in.Name, in.Namespace, in.Spec.TargetNamespace, secretIsPresent) {\n\t\t// A child resource has been deleted. Drop the existing Status field so that reconciliation can start anew.\n\t\tout.ForceUpdate()\n\t\tnextPhase = phase.GetNext(phase.Configuring)\n\t\tmsg = \"Child resource(s) have been deleted, scheduling for configuring\"\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *Container) cleanupStorage() error {\n\tif !c.state.Mounted {\n\t\t// Already unmounted, do nothing\n\t\treturn nil\n\t}\n\n\tfor _, mount := range c.config.Mounts {\n\t\tif err := unix.Unmount(mount, unix.MNT_DETACH); err != nil {\n\t\t\tif err != syscall.EINVAL {\n\t\t\t\tlogrus.Warnf(\"container %s failed to unmount %s : %v\", c.ID(), mount, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Also unmount storage\n\tif err := c.runtime.storageService.UnmountContainerImage(c.ID()); err != nil {\n\t\treturn errors.Wrapf(err, \"error unmounting container %s root filesystem\", c.ID())\n\t}\n\n\tc.state.Mountpoint = \"\"\n\tc.state.Mounted = false\n\n\treturn c.save()\n}", "func (ei *EnvInfo) CompleteStorage(storage *localConfigProvider.LocalStorage) {\n\tif storage.Size == \"\" {\n\t\tstorage.Size = DefaultVolumeSize\n\t}\n\tif storage.Path == \"\" {\n\t\t// acc to the devfile schema, if the mount path is absent; it will be mounted at the dir with the mount name\n\t\tstorage.Path = \"/\" + storage.Name\n\t}\n}", "func (c *Container) CleanupStorage() error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif err := c.syncContainer(); err != nil {\n\t\treturn err\n\t}\n\treturn c.cleanupStorage()\n}", "func storageVersionForCRD(crd *apiextensionsv1.CustomResourceDefinition) (string, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Storage {\n\t\t\treturn v.Name, nil\n\t\t}\n\t}\n\treturn \"\", errors.Errorf(\"could not find storage version for CRD %q\", crd.Name)\n}", "func (a *API) ProposeStorageDeal(ctx context.Context, data cid.Cid, miner address.Address,\n\taskid uint64, duration uint64, allowDuplicates bool) (*storagedeal.Response, error) {\n\n\treturn a.sc.ProposeDeal(ctx, miner, data, askid, duration, allowDuplicates)\n}", "func (a *Agent) setStorages() error {\n\ta.MetadataStorages = &storage.MetadataStorages{}\n\n\ta.MetadataStorages.ResourcedMaster = storage.NewResourcedMasterMetadataStorage(a.GeneralConfig.ResourcedMaster.URL, a.GeneralConfig.ResourcedMaster.AccessToken)\n\n\ta.Db = storage.NewStorage()\n\n\treturn nil\n}", "func (r *reconciler) Reconcile(ctx context.Context, object runtime.Object) error {\n\tlogger := logging.FromContext(ctx)\n\n\tsource, ok := object.(*sourcesv1alpha1.DriveSource)\n\tif !ok {\n\t\tlogger.Errorf(\"could not find Drive source %v\", object)\n\t\treturn nil\n\t}\n\n\t// See if the source has been deleted.\n\taccessor, err := meta.Accessor(source)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to get metadata accessor: %s\", zap.Error(err))\n\t\treturn err\n\t}\n\n\tvar reconcileErr error\n\tif accessor.GetDeletionTimestamp() == nil {\n\t\treconcileErr = r.reconcile(ctx, source)\n\t} else {\n\t\treconcileErr = r.finalize(ctx, source)\n\t}\n\n\treturn reconcileErr\n}", "func (r *ReconcileHiveConfig) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\n\thLog := log.WithField(\"controller\", \"hive\")\n\thLog.Info(\"Reconciling Hive components\")\n\n\t// Fetch the Hive instance\n\tinstance := &hivev1.HiveConfig{}\n\t// NOTE: ignoring the Namespace that seems to get set on request when syncing on namespaced objects,\n\t// when our HiveConfig is ClusterScoped.\n\terr := r.Get(context.TODO(), types.NamespacedName{Name: request.NamespacedName.Name}, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Object not found, return. Created objects are automatically garbage collected.\n\t\t\t// For additional cleanup logic use finalizers.\n\t\t\thLog.Debug(\"HiveConfig not found, deleted?\")\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\thLog.WithError(err).Error(\"error reading HiveConfig\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// We only support one HiveConfig per cluster, and it must be called \"hive\". This prevents installing\n\t// Hive more than once in the cluster.\n\tif instance.Name != hiveConfigName {\n\t\thLog.WithField(\"hiveConfig\", instance.Name).Warn(\"invalid HiveConfig name, only one HiveConfig supported per cluster and must be named 'hive'\")\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\trecorder := events.NewRecorder(r.kubeClient.CoreV1().Events(constants.HiveNamespace), \"hive-operator\", &corev1.ObjectReference{\n\t\tName: request.Name,\n\t\tNamespace: constants.HiveNamespace,\n\t})\n\n\tif r.syncAggregatorCA {\n\t\t// We use the configmap lister and not the regular client which only watches resources in the hive namespace\n\t\taggregatorCAConfigMap, err := r.managedConfigCMLister.ConfigMaps(managedConfigNamespace).Get(aggregatorCAConfigMapName)\n\t\t// If an error other than not found, retry. If not found, it means we don't need to do anything with\n\t\t// admission pods yet.\n\t\tcmLog := hLog.WithField(\"configmap\", fmt.Sprintf(\"%s/%s\", managedConfigNamespace, aggregatorCAConfigMapName))\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\tcmLog.Warningf(\"configmap was not found, will not sync aggregator CA with admission pods\")\n\t\tcase err != nil:\n\t\t\tcmLog.WithError(err).Errorf(\"cannot retrieve configmap\")\n\t\t\treturn reconcile.Result{}, err\n\t\tdefault:\n\t\t\tcaHash := computeHash(aggregatorCAConfigMap.Data)\n\t\t\tcmLog.WithField(\"hash\", caHash).Debugf(\"computed hash for configmap\")\n\t\t\tif instance.Status.AggregatorClientCAHash != caHash {\n\t\t\t\tcmLog.WithField(\"oldHash\", instance.Status.AggregatorClientCAHash).\n\t\t\t\t\tInfo(\"configmap has changed, admission pods will restart on the next sync\")\n\t\t\t\tinstance.Status.AggregatorClientCAHash = caHash\n\t\t\t\tcmLog.Debugf(\"updating status with new aggregator CA configmap hash\")\n\t\t\t\terr = r.Status().Update(context.TODO(), instance)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcmLog.WithError(err).Error(\"cannot update hash in config status\")\n\t\t\t\t}\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\t\t\tcmLog.Debug(\"configmap unchanged, nothing to do\")\n\t\t}\n\t}\n\n\th := resource.NewHelperFromRESTConfig(r.restConfig, hLog)\n\n\tif err := deployManagedDomainsConfigMap(h, instance); err != nil {\n\t\thLog.WithError(err).Error(\"error deploying managed domains configmap\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\terr = r.deployHive(hLog, h, instance, recorder)\n\tif err != nil {\n\t\thLog.WithError(err).Error(\"error deploying Hive\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\terr = r.deployHiveAdmission(hLog, h, instance, recorder)\n\tif err != nil {\n\t\thLog.WithError(err).Error(\"error deploying HiveAdmission\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tif err := r.teardownLegacyExternalDNS(hLog); err != nil {\n\t\thLog.WithError(err).Error(\"error tearing down legacy ExternalDNS\")\n\t\treturn reconcile.Result{}, err\n\t}\n\n\treturn reconcile.Result{}, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HasOwned returns true if the tags contains a tag that marks the resource as owned by the cluster from the perspective of this management tooling.
func (in Labels) HasOwned(cluster string) bool { value, ok := in[ClusterTagKey(cluster)] return ok && ResourceLifecycle(value) == ResourceLifecycleOwned }
[ "func IsOwned(object metav1.Object) (owned bool, err error) {\n\trefs, err := getRefs(object)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn len(refs) > 0, nil\n}", "func (k keeper) HasOwner(ctx sdk.Context, name string) bool {\n\treturn !k.GetWhois(ctx, name).Owner.Empty()\n}", "func (n *Network) AdPeopleOwned() bool {\n\tfor _, ssid := range adpeople_owned {\n\t\tif n.Ssid == ssid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (k Keeper) HasOwner(ctx sdk.Context, name string) bool {\n\treturn !k.GetWhois(ctx, name).Owner.Empty()\n}", "func IsTopologyOwned(o metav1.Object) bool {\n\t_, ok := o.GetLabels()[clusterv1.ClusterTopologyOwnedLabel]\n\treturn ok\n}", "func (k Keeper) HasOwner(ctx sdk.Context, name string) bool {\n\twhois := k.GetWhois(ctx, name)\n\treturn !whois.Owner.Empty()\n}", "func ServiceOwned(ctx context.Context, conn *dbus.Conn, svc string) bool {\n\tobj := conn.Object(busName, busPath)\n\treturn obj.CallWithContext(ctx, busInterface+\".GetNameOwner\", 0, svc).Err == nil\n}", "func (o *User) HasOwnedObjects() bool {\n\tif o != nil && o.OwnedObjects != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *V0037Node) HasOwner() bool {\n\tif o != nil && o.Owner != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) HasResourcePoolOwner() bool {\n\tif o != nil && o.ResourcePoolOwner != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Inventory) HasResourceOwnerId() bool {\n\tif o != nil && o.ResourceOwnerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Tag) Own(name string) bool {\n\tif c.Name == name {\n\t\treturn true\n\t}\n\talias := c.Value(OptAlias)\n\tif util.ListIndex(alias, name) > -1 {\n\t\treturn true\n\t}\n\treturn false\n}", "func IsContainershipManaged(obj interface{}) bool {\n\tmeta, err := meta.Accessor(obj)\n\n\tif err != nil {\n\t\tlog.Error(\"isContainershipManaged Error: \", err)\n\t\treturn false\n\t}\n\n\tl := meta.GetLabels()\n\tif cs, ok := l[\"containership.io/managed\"]; ok && cs == \"true\" {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (sp *serviceOwnedEdgeLBObjectMetadata) IsOwnedBy(service *corev1.Service) bool {\n\treturn sp.ClusterName == cluster.Name && sp.Namespace == service.Namespace && sp.Name == service.Name\n}", "func (o AccessLevelBasicConditionDevicePolicyOutput) RequireCorpOwned() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v AccessLevelBasicConditionDevicePolicy) *bool { return v.RequireCorpOwned }).(pulumi.BoolPtrOutput)\n}", "func (m *ingressOwnedEdgeLBObjectMetadata) IsOwnedBy(ingress *extsv1beta1.Ingress) bool {\n\treturn m.ClusterName == cluster.Name && m.Namespace == ingress.Namespace && m.Name == ingress.Name\n}", "func (resource Resource) HasTag(tag string) bool {\n\tfor _, t := range resource.Tags {\n\t\tif t == tag {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *Operation) IsOwner(gid GoogleID) bool {\n\treturn o.ID.IsOwner(gid)\n}", "func (o *User) HasOwnedDevices() bool {\n\tif o != nil && o.OwnedDevices != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ToComputeFilter returns the string representation of the labels as a filter to be used in google compute sdk calls.
func (in Labels) ToComputeFilter() string { var builder strings.Builder for k, v := range in { builder.WriteString(fmt.Sprintf("(labels.%s = %q) ", k, v)) } return builder.String() }
[ "func (q *Query) ToFilter() string {\n\treturn fmt.Sprintf(`\nresource.type=k8s_container\nAND (\n\tlogName=projects/%s/logs/stderr\n\tOR logName=projects/%s/logs/stdout\n)\nAND resource.labels.cluster_name=%q\nAND resource.labels.namespace_name=%q\nAND labels.%q=%q\n`,\n\t\tq.Project,\n\t\tq.Project,\n\t\tq.Cluster,\n\t\tq.Namespace,\n\t\tStackdriverBuildIDLabel,\n\t\tq.BuildID,\n\t)\n}", "func (sink *influxdbSink) labelsToPredicate(labels map[string]string) string {\n\tif len(labels) == 0 {\n\t\treturn \"\"\n\t}\n\n\tparts := make([]string, 0, len(labels))\n\tfor k, v := range labels {\n\t\tparts = append(parts, fmt.Sprintf(\"%q = '%s'\", k, v))\n\t}\n\n\treturn strings.Join(parts, \" AND \")\n}", "func (qb QueryBuilder) composeFilter() string {\n\tfilterBuilder := qb.getFilterBuilder().\n\t\tWithMetricType(qb.metricName).\n\t\tWithProject(qb.translator.config.Project).\n\t\tWithCluster(qb.translator.config.Cluster)\n\n\tresourceNames := qb.getResourceNames()\n\tif qb.translator.useNewResourceModel {\n\t\t// new resource model specific filters\n\t\tfilterBuilder = filterBuilder.WithLocation(qb.translator.config.Location)\n\t\tif !qb.nodes.isNodeValuesEmpty() {\n\t\t\t// node metrics\n\t\t\treturn filterBuilder.WithNodes(resourceNames).Build()\n\t\t}\n\t\t// pod metrics\n\t\treturn filterBuilder.\n\t\t\tWithNamespace(qb.namespace).\n\t\t\tWithPods(resourceNames).\n\t\t\tBuild()\n\n\t}\n\t// legacy resource model specific filters\n\treturn filterBuilder.\n\t\tWithContainer().\n\t\tWithPods(resourceNames).\n\t\tBuild()\n}", "func generateListFilterFromLabels(labels map[string]string) string {\n\tvar filter string\n\tfor k, v := range labels {\n\t\tfilter = fmt.Sprintf(\"%s(labels.%s eq %s)\", filter, k, v)\n\t}\n\n\treturn filter\n}", "func FilterLabels() map[string]string {\n\treturn map[string]string{\n\t\t\"eventing.knative.dev/brokerRole\": \"filter\",\n\t}\n}", "func (tf TrueFilter) ToFilterDescription() FilterDescription {\n\treturn FilterDescription{\n\t\tType: \"TrueFilter\",\n\t\tSQLExpression: ptrString(\"1=1\"),\n\t}\n}", "func (f *IPLabelFilter) String() string {\n\teq := \"=\" // LabelFilterEqual -> \"==\", we don't want in string representation of ip label filter.\n\tif f.ty == LabelFilterNotEqual {\n\t\teq = LabelFilterNotEqual.String()\n\t}\n\n\treturn fmt.Sprintf(\"%s%sip(%q)\", f.label, eq, f.pattern) // label filter\n}", "func (r *resultImpl) Filter(filter func(label *Label) *Label) (LabelResult, error) {\n\tvar result []Label\n\tfor _, value := range r.labels {\n\t\tfilterResult := filter(&value)\n\t\tif filterResult != nil {\n\t\t\tresult = append(result, *filterResult)\n\t\t}\n\t}\n\treturn &resultImpl{\n\t\tlabels: result,\n\t}, nil\n}", "func ToC(filter []bpf.Instruction, opts COpts) (string, error) {\n\tif !funcNameRegex.MatchString(opts.FunctionName) {\n\t\treturn \"\", errors.Errorf(\"invalid FunctionName %q\", opts.FunctionName)\n\t}\n\n\tblocks, err := compile(filter)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfun := cFunction{\n\t\tName: opts.FunctionName,\n\t\tBlocks: make([]cBlock, len(blocks)),\n\t}\n\n\t// Compile blocks to C\n\tfor i, block := range blocks {\n\t\tfun.Blocks[i], err = blockToC(block)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Fill in the template\n\ttmpl, err := template.New(\"cbfp_func\").Parse(funcTemplate)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"unable to parse func template\")\n\t}\n\n\tc := strings.Builder{}\n\n\tif err := tmpl.Execute(&c, fun); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"unable to execute func template\")\n\t}\n\n\treturn c.String(), nil\n}", "func (f Foo) FilterLabels(fn func(string) bool) []string {\n\treturn f.FilterLabelsN(fn, -1)\n}", "func (filter AnalyticMetricFilter) ToString() string {\n\tvar str []string\n\tfor key, val := range filter {\n\t\tstr = append(str, fmt.Sprintf(\"%v=%v\", key, val))\n\t}\n\treturn strings.Join(str, \",\")\n}", "func AddLabelFilter(filter filters.Args, name string, value string) {\n\tlabel := fmt.Sprintf(\"%s%s=%s\", DOCKERLABELNAMESPACE, name, value)\n\tfilter.Add(\"label\", label)\n}", "func (c *Config) LabelsFilter() []string {\n\treturn c.labelsFilter\n}", "func TransformLabelsToSelector(labels map[string]string) string {\n\tlabelList := make([]string, 0)\n\tfor key, value := range labels {\n\t\tlabelList = append(labelList, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\treturn strings.Join(labelList, \",\")\n}", "func (sf SQLFilter) ToFilterDescription() FilterDescription {\n\treturn FilterDescription{\n\t\tType: \"SqlFilter\",\n\t\tSQLExpression: &sf.Expression,\n\t}\n}", "func (c *Controller) DockerFilters() map[string][]string {\n labelFilter := \"mapreduced.ctl=\\\"\" + c.LabelValue + \"\\\"\"\n\n return map[string][]string{\"label\": []string{labelFilter}}\n}", "func FilterLabels(labels map[string]string) map[string]string {\n\n\tstatefulSetLabels := make(map[string]string)\n\tfor key, value := range labels {\n\t\tif key != bdv1.LabelDeploymentVersion {\n\t\t\tstatefulSetLabels[key] = value\n\t\t}\n\t}\n\treturn statefulSetLabels\n}", "func BuildRemoveLabelFilter(predicate func(key string) bool) (yaml.Filter, error) {\n\tfieldPaths, err := xform.ParseFieldPaths(\n\t\t[]string{\n\t\t\t\"metadata.labels\",\n\t\t\t\"spec.selector\",\n\t\t\t\"spec.selector.matchLabels\",\n\t\t\t\"spec.template.metadata.labels\",\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &xform.FieldClearer{\n\t\tFieldPaths: fieldPaths,\n\t\tPredicate: predicate,\n\t}, nil\n}", "func FilterLabels(labels map[string]string) map[string]string {\n\tstatefulSetLabels := make(map[string]string)\n\tfor key, value := range labels {\n\t\tif key != bdv1.LabelDeploymentVersion {\n\t\t\tstatefulSetLabels[key] = value\n\t\t}\n\t}\n\treturn statefulSetLabels\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ClusterTagKey generates the key for resources associated with a cluster.
func ClusterTagKey(name string) string { return fmt.Sprintf("%s%s", NameGCPProviderOwned, name) }
[ "func GetClusterKey(clusterId string) string {\n\treturn ClusterKeyPrefix + clusterId\n}", "func ToClusterKey(vc *v1alpha1.Virtualcluster) string {\n\tif len(vc.GetNamespace()) > 0 {\n\t\treturn vc.GetNamespace() + \"-\" + vc.GetName()\n\t}\n\treturn vc.GetName()\n}", "func ResourceKey(group, version, kind string) string {\n\tif group == \"\" {\n\t\tgroup = \"core\"\n\t}\n\treturn \"k8s_\" + ToSnake(group) + \"_\" + version + \"_\" + ToSnake(kind)\n}", "func ConnEkgKey(cid types.ConnId) []byte {\n return createKey(CONN,EKG,cid.Serialize())\n}", "func ConfigMapKey(pandaCluster *vectorizedv1alpha1.Cluster) types.NamespacedName {\n\treturn types.NamespacedName{Name: resourceNameTrim(pandaCluster.Name, baseSuffix), Namespace: pandaCluster.Namespace}\n}", "func tagKey(dir string, context *build.Context, tags []string) string {\n\tctags := map[string]bool{\n\t\tcontext.GOOS: true,\n\t\tcontext.GOARCH: true,\n\t}\n\tif context.CgoEnabled {\n\t\tctags[\"cgo\"] = true\n\t}\n\tfor _, tag := range context.BuildTags {\n\t\tctags[tag] = true\n\t}\n\t// TODO: ReleaseTags (need to load default)\n\tkey := dir\n\n\t// explicit on GOOS and GOARCH as global cache will use \"all\" cached packages for\n\t// an indirect imported package. See https://github.com/golang/go/issues/21181\n\t// for more detail.\n\ttags = append(tags, context.GOOS, context.GOARCH)\n\tsort.Strings(tags)\n\n\tfor _, tag := range tags {\n\t\tif ctags[tag] {\n\t\t\tkey += \",\" + tag\n\t\t\tctags[tag] = false\n\t\t}\n\t}\n\treturn key\n}", "func ETCDKey(id string, ktype KeyType) (string, error) {\n\tsuffix, ok := etcdKeySuffixes[ktype]\n\tif !ok {\n\t\treturn \"\", errors.Wrapf(ErrInvalidKey, \"%v is not a supported key type\", ktype)\n\t}\n\treturn id + suffix, nil\n}", "func ResourceKey(c Codec, resourceName, pk string) string {\n\treturn path.Join(c.Key(), resourceName, pk)\n}", "func CacheKey(metadata *metav1.ObjectMeta) string {\n\treturn fmt.Sprintf(\"%v_%v\", metadata.UID, metadata.ResourceVersion)\n}", "func getKey(cluster *clusteroperator.Cluster, t *testing.T) string {\n\tif key, err := controller.KeyFunc(cluster); err != nil {\n\t\tt.Errorf(\"Unexpected error getting key for Cluster %v: %v\", cluster.Name, err)\n\t\treturn \"\"\n\t} else {\n\t\treturn key\n\t}\n}", "func (o ClusterOutput) ClusterResourceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ClusterResourceId }).(pulumi.StringOutput)\n}", "func Key(name string, namespace string) string {\n\treturn ksrkey.Key(PodKeyword, name, namespace)\n}", "func (rc *TagCache) Key(name, value string, ismeta bool) string {\n\treturn name + value + fmt.Sprintf(\"%v\", ismeta)\n}", "func KeyFor(obj runtime.Object, nsn types.NamespacedName) string {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\treturn strings.Join([]string{gvk.Group, gvk.Version, gvk.Kind, nsn.Namespace, nsn.Name}, KeyDelimiter)\n}", "func (a *Attribute) TagKey() TagKey {\n\tif a.tagKey != \"\" {\n\t\treturn a.tagKey\n\t}\n\ta.tagKey = tagToKey(a.Tag)\n\treturn a.tagKey\n}", "func ContextForCluster(kindClusterName string) string {\n\treturn kubeconfig.KINDClusterKey(kindClusterName)\n}", "func GetKeyNodeName(cluster, node string) string {\n\t// WARNING - STABLE API: Changing the structure of the key may break\n\t// backwards compatibility\n\treturn path.Join(cluster, node)\n}", "func (t Task) Key() string {\n\treturn fmt.Sprintf(\"%s:%s\", t.Name, t.ID)\n}", "func (o ClusterNodePoolNodeConfigReservationAffinityOutput) Key() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterNodePoolNodeConfigReservationAffinity) *string { return v.Key }).(pulumi.StringPtrOutput)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build builds tags including the cluster tag and returns them in map form.
func Build(params BuildParams) Labels { tags := make(Labels) for k, v := range params.Additional { tags[strings.ToLower(k)] = strings.ToLower(v) } tags[ClusterTagKey(params.ClusterName)] = string(params.Lifecycle) if params.Role != nil { tags[NameGCPClusterAPIRole] = strings.ToLower(*params.Role) } return tags }
[ "func BuildTags(t *testing.T, ti map[string]interface{}) map[string]string {\n\tt.Helper()\n\tx := map[string]string{}\n\tfor k := range ti {\n\t\tx[k] = k + \"-tag-val\"\n\t}\n\treturn x\n}", "func buildTags() string {\n\treturn *tags\n}", "func (r *Cluster) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func (t *SentryTaggedStruct) BuildTags(v interface{}) (tags map[string]string, err error) {\n\titems := make(map[string]string)\n\tfor prop, name := range t.Tags {\n\t\tif _, value, e := t.GetProperty(v, prop); e == nil {\n\t\t\titems[name] = value\n\t\t} else {\n\t\t\terr = e\n\t\t\treturn\n\t\t}\n\t}\n\n\ttags = items\n\treturn\n}", "func (t *SentryTaggedScalar) BuildTags(v interface{}) (items map[string]string, err error) {\n\titems = make(map[string]string)\n\tif value, e := t.Get(v); e == nil {\n\t\titems[t.Name] = value\n\t} else {\n\t\terr = e\n\t}\n\treturn\n}", "func createTags(tagMap *map[string]string) []*cloudformation.Tag {\n\ttags := make([]*cloudformation.Tag, 0)\n\tfor key, value := range *tagMap {\n\t\ttags = append(tags, &cloudformation.Tag{Key: &key, Value: &value})\n\t}\n\treturn tags\n}", "func (tb *tagSetBuilder) Build() *TagSet {\n\tts := tb.ts\n\ttb.ts = nil\n\treturn ts\n}", "func (o KubernetesClusterOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *KubernetesCluster) pulumi.StringArrayOutput { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (o ClusterNodeConfigOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ClusterNodeConfig) []string { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func (metadata *GCPMetadata) TagMap() map[string]string {\n\ttagMap := map[string]string{}\n\tif metadata.ContainerID != nil {\n\t\ttagMap[metadata.ContainerID.TagName] = metadata.ContainerID.Value\n\t}\n\tif metadata.Region != nil {\n\t\ttagMap[metadata.Region.TagName] = metadata.Region.Value\n\t}\n\tif metadata.ProjectID != nil {\n\t\ttagMap[metadata.ProjectID.TagName] = metadata.ProjectID.Value\n\t}\n\treturn tagMap\n}", "func (b *ClusterBuilder) Build() (object *Cluster, err error) {\n\tobject = new(Cluster)\n\tobject.id = b.id\n\tobject.href = b.href\n\tobject.bitmap_ = b.bitmap_\n\tif b.api != nil {\n\t\tobject.api, err = b.api.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.aws != nil {\n\t\tobject.aws, err = b.aws.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.awsInfrastructureAccessRoleGrants != nil {\n\t\tobject.awsInfrastructureAccessRoleGrants, err = b.awsInfrastructureAccessRoleGrants.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.ccs != nil {\n\t\tobject.ccs, err = b.ccs.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.dns != nil {\n\t\tobject.dns, err = b.dns.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.gcp != nil {\n\t\tobject.gcp, err = b.gcp.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.addons != nil {\n\t\tobject.addons, err = b.addons.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.billingModel = b.billingModel\n\tif b.cloudProvider != nil {\n\t\tobject.cloudProvider, err = b.cloudProvider.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.console != nil {\n\t\tobject.console, err = b.console.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.creationTimestamp = b.creationTimestamp\n\tobject.disableUserWorkloadMonitoring = b.disableUserWorkloadMonitoring\n\tobject.displayName = b.displayName\n\tobject.etcdEncryption = b.etcdEncryption\n\tobject.expirationTimestamp = b.expirationTimestamp\n\tobject.externalID = b.externalID\n\tif b.externalConfiguration != nil {\n\t\tobject.externalConfiguration, err = b.externalConfiguration.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.flavour != nil {\n\t\tobject.flavour, err = b.flavour.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.groups != nil {\n\t\tobject.groups, err = b.groups.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.healthState = b.healthState\n\tif b.identityProviders != nil {\n\t\tobject.identityProviders, err = b.identityProviders.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.ingresses != nil {\n\t\tobject.ingresses, err = b.ingresses.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.loadBalancerQuota = b.loadBalancerQuota\n\tif b.machinePools != nil {\n\t\tobject.machinePools, err = b.machinePools.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.managed = b.managed\n\tobject.multiAZ = b.multiAZ\n\tobject.name = b.name\n\tif b.network != nil {\n\t\tobject.network, err = b.network.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.nodeDrainGracePeriod != nil {\n\t\tobject.nodeDrainGracePeriod, err = b.nodeDrainGracePeriod.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.nodes != nil {\n\t\tobject.nodes, err = b.nodes.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.openshiftVersion = b.openshiftVersion\n\tif b.product != nil {\n\t\tobject.product, err = b.product.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.properties != nil {\n\t\tobject.properties = make(map[string]string)\n\t\tfor k, v := range b.properties {\n\t\t\tobject.properties[k] = v\n\t\t}\n\t}\n\tif b.provisionShard != nil {\n\t\tobject.provisionShard, err = b.provisionShard.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.region != nil {\n\t\tobject.region, err = b.region.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.state = b.state\n\tif b.status != nil {\n\t\tobject.status, err = b.status.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.storageQuota != nil {\n\t\tobject.storageQuota, err = b.storageQuota.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.subscription != nil {\n\t\tobject.subscription, err = b.subscription.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif b.version != nil {\n\t\tobject.version, err = b.version.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (nt *NetworkStru) Build() error {\n\tnt.StopThreads() // any existing..\n\tnt.LayClassMap = make(map[string][]string)\n\temsg := \"\"\n\tfor li, ly := range nt.Layers {\n\t\tly.SetIndex(li)\n\t\tif ly.IsOff() {\n\t\t\tcontinue\n\t\t}\n\t\terr := ly.Build()\n\t\tif err != nil {\n\t\t\temsg += err.Error() + \"\\n\"\n\t\t}\n\t\tcls := strings.Split(ly.Class(), \" \")\n\t\tfor _, cl := range cls {\n\t\t\tll := nt.LayClassMap[cl]\n\t\t\tll = append(ll, ly.Name())\n\t\t\tnt.LayClassMap[cl] = ll\n\t\t}\n\t}\n\tnt.Layout()\n\tnt.BuildThreads()\n\tnt.StartThreads()\n\tif emsg != \"\" {\n\t\treturn errors.New(emsg)\n\t}\n\treturn nil\n}", "func createAtlasTags(namespace core.Namespace, tags map[string]string) map[string]string {\n\t// Convert namespace to variable map\n\tvars := map[string]string{\n\t\t\"namespace\": strings.Join(namespace.Strings(), \".\"),\n\t}\n\tstaticNamespace := []string{}\n\tn := len(namespace)\n\tfor i := 0; i < n; i++ {\n\t\t// Add in positional variables\n\t\tvars[fmt.Sprintf(\"%d\", i)] = namespace[i].Value\n\t\tvars[fmt.Sprintf(\"%d\", i - n)] = namespace[i].Value\n\n\t\t// For dynamic elements, add in variable with name. Otherwise append\n\t\t// to static set.\n\t\tif namespace[i].IsDynamic() {\n\t\t\tvars[namespace[i].Name] = namespace[i].Value\n\t\t} else {\n\t\t\tstaticNamespace = append(staticNamespace, namespace[i].Value)\n\t\t}\n\t}\n\tvars[\"namespace_static\"] = strings.Join(staticNamespace, \".\")\n\n\t// By default use the parts of the namespace to form the name. If an explicit\n\t// 'name' key is used in the tags, then it will overwrite this value.\n\tatlasTags := map[string]string{\n\t\t\"name\": vars[\"namespace\"],\n\t}\n\n\t// Copy tags that are not explicitly ignored into the Atlas tag map.\n\tfor k, v := range tags {\n\t\tif _, ignored := ignoredTags[k]; !ignored {\n\t\t\tatlasTags[k] = substitute(v, vars)\n\t\t}\n\t}\n\n\treturn atlasTags\n}", "func (o TriggerBuildOutput) Tags() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuild) []string { return v.Tags }).(pulumi.StringArrayOutput)\n}", "func BuildFromECRTags(tags []ecr.Tag) []Tag {\n\tif len(tags) < 1 {\n\t\treturn nil\n\t}\n\tres := make([]Tag, len(tags))\n\tfor i, t := range tags {\n\t\tres[i] = Tag{aws.StringValue(t.Key), aws.StringValue(t.Value)}\n\t}\n\n\treturn res\n}", "func (o BucketOutput) Tags() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.MapOutput { return v.Tags }).(pulumi.MapOutput)\n}", "func (b *ServiceClusterBuilder) Build() (object *ServiceCluster, err error) {\n\tobject = new(ServiceCluster)\n\tobject.id = b.id\n\tobject.href = b.href\n\tobject.bitmap_ = b.bitmap_\n\tif b.dns != nil {\n\t\tobject.dns, err = b.dns.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.cloudProvider = b.cloudProvider\n\tif b.clusterManagementReference != nil {\n\t\tobject.clusterManagementReference, err = b.clusterManagementReference.Build()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tobject.name = b.name\n\tobject.region = b.region\n\tobject.status = b.status\n\treturn\n}", "func PackTags(in map[string]string) string {\n\ttags := []string{}\n\n\tfor k, v := range in {\n\t\ttags = append(tags, fmt.Sprintf(\"%s:%s\", k, v))\n\t}\n\n\tsort.Strings(tags)\n\n\treturn strings.Join(tags, \",\")\n}", "func (b *ByNameCategorizerBuilder) Build() Categorizer {\n\tbyNameMap := make(map[string]fin.Cat)\n\tfor k, v := range b.trainingData {\n\t\tif v.cat != fin.Expense {\n\t\t\tbyNameMap[k] = v.cat\n\t\t}\n\t}\n\treturn byNameCategorizer(byNameMap)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GinLogrus is a logger middleware, which use the logrus replace gin default logger
func GinLogrus() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() // some evil middlewares modify this values path := c.Request.URL.Path c.Next() end := time.Since(start) status := c.Writer.Status() entry := logrus.WithFields(logrus.Fields{ "path": path, "method": c.Request.Method, "clientIP": c.ClientIP(), "userAgent": c.Request.UserAgent(), "requestID": c.MustGet(RequestIDKey), "status": status, "size": c.Writer.Size(), "latency": fmt.Sprintf("%fms", float64(end.Seconds())*1000.0), }) if len(c.Errors) > 0 { // Append error field if this is an erroneous request. entry.Error(c.Errors.String()) } else { if status > 499 { entry.Error() } else { entry.Info() } } } }
[ "func GinLogger(logger ...*logrus.Entry) gin.HandlerFunc {\n\tlog := getGinLogger(logger...)\n\n\treturn func(c *gin.Context) {\n\t\tpath := c.Request.URL.Path\n\t\tstart := time.Now()\n\t\tc.Next()\n\t\tstop := time.Since(start)\n\t\tlatency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))\n\t\tstatusCode := c.Writer.Status()\n\t\tclientIP := c.ClientIP()\n\t\tclientUserAgent := c.Request.UserAgent()\n\t\treferer := c.Request.Referer()\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\thostname = \"unknown\"\n\t\t}\n\t\tdataLength := c.Writer.Size()\n\t\tif dataLength < 0 {\n\t\t\tdataLength = 0\n\t\t}\n\n\t\tentry := log.WithFields(logrus.Fields{\n\t\t\t\"hostname\": hostname,\n\t\t\t\"statusCode\": statusCode,\n\t\t\t\"latency\": latency, // time to process\n\t\t\t\"clientIP\": clientIP,\n\t\t\t\"method\": c.Request.Method,\n\t\t\t\"path\": path,\n\t\t\t\"referer\": referer,\n\t\t\t\"dataLength\": dataLength,\n\t\t\t\"userAgent\": clientUserAgent,\n\t\t})\n\n\t\tif len(c.Errors) > 0 {\n\t\t\tentry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"%d \\\"%s %s\\\" (%dms)\", statusCode, c.Request.Method, path, latency)\n\t\t\tif statusCode > 499 {\n\t\t\t\tentry.Error(msg)\n\t\t\t} else if statusCode > 399 {\n\t\t\t\tentry.Warn(msg)\n\t\t\t} else {\n\t\t\t\tentry.Trace(msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func Logrus() echo.MiddlewareFunc {\n\treturn LogrusDefaultConfig(DefaultLoggerConfig)\n}", "func GinLogger(log *logrus.Logger) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\t// other handler can change c.Path so:\n\t\tpath := c.Request.URL.Path\n\t\tmethod := c.Request.Method\n\t\tstart := time.Now()\n\t\tc.Next()\n\t\tstop := time.Since(start)\n\t\tlatency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))\n\t\tstatusCode := c.Writer.Status()\n\t\tclientIP := c.ClientIP()\n\t\tclientUserAgent := c.Request.UserAgent()\n\t\treferer := c.Request.Referer()\n\t\trequestS := c.Request.ContentLength\n\t\tresponseS := c.Writer.Size()\n\t\tif requestS < 0 {\n\t\t\trequestS = 0\n\t\t}\n\t\trequest := &HTTPRequest{\n\t\t\tRequestMethod: method,\n\t\t\tRequestURL: path,\n\t\t\tRemoteIP: clientIP,\n\t\t\tReferer: referer,\n\t\t\tUserAgent: clientUserAgent,\n\t\t\tResponseSize: strconv.Itoa(responseS),\n\t\t\tLatency: strconv.Itoa(latency),\n\t\t\tStatus: strconv.Itoa(statusCode),\n\t\t\tRequestSize: strconv.FormatInt(requestS, 10),\n\t\t}\n\n\t\tfields := logrus.Fields{\"httpRequest\": request}\n\n\t\ttraceHeader := c.GetHeader(\"X-Request-ID\")\n\t\tif traceHeader != \"\" {\n\t\t\tfields[\"trace\"] = traceHeader\n\t\t}\n\n\t\tentry := log.WithFields(fields)\n\n\t\tif len(c.Errors) > 0 {\n\t\t\tentry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"[%s - %s] %d\", c.Request.Method, path, statusCode)\n\t\t\tif statusCode > 399 {\n\t\t\t\tentry.Error(msg)\n\t\t\t} else {\n\t\t\t\tentry.Info(msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func ginlogger() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tlogger.LogMessageSource(logger.LogLevelDebug, logsrc, \"%v %v\\n\", c.Request.Method, c.Request.RequestURI)\n\t\tc.Next()\n\t}\n}", "func Logrus() echo.MiddlewareFunc {\n\treturn LogrusWithConfig(DefaultLogrusConfig)\n}", "func WrapLogrus(in logrusLogger) Logger {\n\treturn logrusWrapper{in}\n}", "func (r *RouterGroup) UseLogger() {\n\tr.gin.Use(gin.Logger())\n}", "func init() {\n\tlog = logrus.WithField(\"prefix\", \"example_app\")\n}", "func (e *Engine) UseLogger() {\n\te.gin.Use(gin.Logger())\n}", "func Logger(ctx *gin.Context) {\n\tif isAsset(ctx) {\n\t\treturn\n\t}\n\n\tstart := time.Now().UTC()\n\n\t//s := SessionFromCtx(ctx)\n\tf := logrus.Fields{}\n\n\t// this will be unique per request\n\tid, err := session.GenerateRandomString(10)\n\tif err == nil {\n\t\tf[\"req_id\"] = id\n\t\tctx.Writer.Header().Set(\"x-req-id\", id)\n\t}\n\n\tf[\"req_url\"] = ctx.Request.URL.String()\n\tf[\"req_referer\"] = ctx.Request.Referer()\n\tf[\"req_ip\"] = ctx.Request.RemoteAddr\n\tf[\"req_method\"] = ctx.Request.Method\n\tf[\"req_useragent\"] = ctx.Request.UserAgent()\n\tf[\"req_handler\"] = path.Base(ctx.HandlerName())\n\n\tl := logrus.WithFields(f)\n\n\tctx.Set(log.LoggerCtxKey, l)\n\n\tctx.Next()\n\n\tl = LoggerFromCtx(ctx)\n\tl.WithFields(logrus.Fields{\n\t\t\"response_code\": ctx.Writer.Status(),\n\t\t\"response_size\": ctx.Writer.Size(),\n\t\t\"req_duration_ms\": time.Since(start).Nanoseconds() / int64(time.Millisecond),\n\t}).Info(\"http_request\")\n\n\tif config.Conf.Env == \"dev\" {\n\t\tfmt.Println(\"\")\n\t}\n}", "func getLogrusLogger(loggerConfig *config.LoggerConfig) (glogger.Logger, error) {\n\tlogger := logrus.New()\n\t//standard configuration\n\tlogger.SetFormatter(&logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t})\n\tlogger.SetReportCaller(true)\n\n\t//customize it as per configurations\n\terr := customizeLogrusLogger(logger, loggerConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"customizeLogrusLogger\")\n\t}\n\treturn logger, nil\n}", "func LogrusWithConfig(config LogrusConfig) echo.MiddlewareFunc {\n\t// Defaults\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultLogrusConfig.Skipper\n\t}\n\n\tif config.Logger == nil {\n\t\tconfig.Logger = DefaultLogrusConfig.Logger\n\t}\n\n\tif len(config.FieldMap) == 0 {\n\t\tconfig.FieldMap = DefaultLogrusConfig.FieldMap\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) (err error) {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\tres := c.Response()\n\t\t\tstart := time.Now()\n\n\t\t\tif err = next(c); err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tstop := time.Now()\n\t\t\tentry := config.Logger\n\n\t\t\tfor k, v := range config.FieldMap {\n\t\t\t\tif v == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tswitch v {\n\t\t\t\tcase \"@id\":\n\t\t\t\t\tid := req.Header.Get(echo.HeaderXRequestID)\n\n\t\t\t\t\tif id == \"\" {\n\t\t\t\t\t\tid = res.Header().Get(echo.HeaderXRequestID)\n\t\t\t\t\t}\n\n\t\t\t\t\tentry = entry.WithField(k, id)\n\t\t\t\tcase \"@remote_ip\":\n\t\t\t\t\tentry = entry.WithField(k, c.RealIP())\n\t\t\t\tcase \"@uri\":\n\t\t\t\t\tentry = entry.WithField(k, req.RequestURI)\n\t\t\t\tcase \"@host\":\n\t\t\t\t\tentry = entry.WithField(k, req.Host)\n\t\t\t\tcase \"@method\":\n\t\t\t\t\tentry = entry.WithField(k, req.Method)\n\t\t\t\tcase \"@path\":\n\t\t\t\t\tp := req.URL.Path\n\n\t\t\t\t\tif p == \"\" {\n\t\t\t\t\t\tp = \"/\"\n\t\t\t\t\t}\n\n\t\t\t\t\tentry = entry.WithField(k, p)\n\t\t\t\tcase \"@referer\":\n\t\t\t\t\tentry = entry.WithField(k, req.Referer())\n\t\t\t\tcase \"@user_agent\":\n\t\t\t\t\tentry = entry.WithField(k, req.UserAgent())\n\t\t\t\tcase \"@status\":\n\t\t\t\t\tentry = entry.WithField(k, res.Status)\n\t\t\t\tcase \"@latency\":\n\t\t\t\t\tl := stop.Sub(start)\n\t\t\t\t\tentry = entry.WithField(k, strconv.FormatInt(int64(l), 10))\n\t\t\t\tcase \"@latency_human\":\n\t\t\t\t\tentry = entry.WithField(k, stop.Sub(start).String())\n\t\t\t\tcase \"@bytes_in\":\n\t\t\t\t\tcl := req.Header.Get(echo.HeaderContentLength)\n\n\t\t\t\t\tif cl == \"\" {\n\t\t\t\t\t\tcl = \"0\"\n\t\t\t\t\t}\n\n\t\t\t\t\tentry = entry.WithField(k, cl)\n\t\t\t\tcase \"@bytes_out\":\n\t\t\t\t\tentry = entry.WithField(k, strconv.FormatInt(res.Size, 10))\n\t\t\t\tdefault:\n\t\t\t\t\tswitch {\n\t\t\t\t\tcase strings.HasPrefix(v, \"@header:\"):\n\t\t\t\t\t\tentry = entry.WithField(k, c.Request().Header.Get(v[8:]))\n\t\t\t\t\tcase strings.HasPrefix(v, \"@query:\"):\n\t\t\t\t\t\tentry = entry.WithField(k, c.QueryParam(v[7:]))\n\t\t\t\t\tcase strings.HasPrefix(v, \"@form:\"):\n\t\t\t\t\t\tentry = entry.WithField(k, c.FormValue(v[6:]))\n\t\t\t\t\tcase strings.HasPrefix(v, \"@cookie:\"):\n\t\t\t\t\t\tcookie, err := c.Cookie(v[8:])\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tentry = entry.WithField(k, cookie.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentry.Print(\"Handle request\")\n\n\t\t\treturn\n\t\t}\n\t}\n}", "func RequestLogger(timeFormat string, utc bool) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstart := time.Now()\n\t\t// some evil middlewares modify this values\n\t\tpath := c.Request.URL.Path\n\t\tc.Next()\n\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\t\tif utc {\n\t\t\tend = end.UTC()\n\t\t}\n\n\t\tuuid, _ := c.Get(ContextKey)\n\n\t\tentry := Logger(c).WithFields(logrus.Fields{\n\t\t\t\"status\": c.Writer.Status(),\n\t\t\t\"method\": c.Request.Method,\n\t\t\t\"path\": path,\n\t\t\t\"ip\": c.ClientIP(),\n\t\t\t\"latency\": latency,\n\t\t\t\"user-agent\": c.Request.UserAgent(),\n\t\t\t\"time\": end.Format(timeFormat),\n\t\t\t\"uuid\": uuid,\n\t\t})\n\n\t\tif len(c.Errors) > 0 {\n\t\t\t// Append error field if this is an erroneous request.\n\t\t\tentry.Error(c.Errors.String())\n\t\t} else {\n\t\t\tentry.Info()\n\t\t}\n\t}\n}", "func InitLogrus() {\n\tlog.Logger()\n}", "func WithGinLog(f string) option {\n\treturn func(s *httpServer) {\n\t\tif f != \"\" {\n\t\t\ts.ginLog = f\n\t\t}\n\t}\n}", "func GorillaLogger(w io.Writer) middleware.MiddleWare {\r\n\treturn func(next http.Handler) http.Handler {\r\n\t\treturn handlers.LoggingHandler(w, next)\r\n\t}\r\n}", "func Logger() gin.HandlerFunc {\n\treturn LoggerWithWriter(gin.DefaultWriter)\n}", "func customizeLogrusLogger(logger *logrus.Logger, loggerConfig *config.LoggerConfig) error {\n\tlogger.SetReportCaller(loggerConfig.EnableCaller)\n\tlogLevel := &logger.Level\n\terr := logLevel.UnmarshalText([]byte(loggerConfig.Level))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"logLevel.UnmarshalText\")\n\t}\n\tlogger.SetLevel(*logLevel)\n\treturn nil\n}", "func L() *zap.SugaredLogger {\n\tonce.Do(func() {\n\t\tlogLevel := config.Get().LogLevel\n\t\tlogLevelInt, err := strconv.Atoi(logLevel)\n\t\tif err != nil {\n\t\t\tlogLevelInt = int(zap.InfoLevel)\n\t\t}\n\n\t\tif logLevelInt > 5 || logLevelInt < -1 {\n\t\t\tlogLevelInt = int(zap.InfoLevel)\n\t\t}\n\n\t\tstdout := zapcore.AddSync(os.Stdout)\n\n\t\tatom := zap.NewAtomicLevel()\n\t\tatom.SetLevel(zapcore.Level(logLevelInt))\n\n\t\tencoderCfg := zap.NewProductionEncoderConfig()\n\t\tencoderCfg.TimeKey = \"timestamp\"\n\t\tencoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder\n\n\t\tcore := zapcore.NewCore(\n\t\t\tzapcore.NewJSONEncoder(encoderCfg),\n\t\t\tstdout,\n\t\t\tatom,\n\t\t)\n\n\t\tdefaultLogger = zap.New(core).Sugar()\n\t})\n\n\treturn defaultLogger\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save saving current page to filesystem
func (p *Page) save(d *Dir) error { p.Sidebar = d.sidebar p.Items = d.pages file, err := os.Create(p.Path) if (err != nil) { return err } fmt.Printf("Create new page: %s\n \tby link:%s\n", p.Title, p.Path) return p.render(file) }
[ "func (p *Page) save() error {\n\t// Create data/ directory in case it does not exist\n\tos.Mkdir(\"data\", 0777)\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(pageDataRoot+filename, p.Body, 0600)\n}", "func (p *Page) save() error {\n filename := p.Title + \".txt\"\n return ioutil.WriteFile(filename, p.Body, 0600)\n}", "func Pagesave(webpage *Webpage, name string, dir string) error {\n\tif e, _ := exists(dir); !e {\n\t\treturn fmt.Errorf(\"dir %s does not exist\", dir)\n\t}\n\tfpath := path.Join(dir, name)\n\tf, err := os.Create(fpath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tline := []byte(webpage.Url + \"\\n\")\n\t_, err = f.Write(line)\n\tif err != nil {\n\t\treturn err\n\t}\n\tline = []byte(strconv.Itoa(webpage.Depth) + \"\\n\")\n\t_, err = f.Write(line)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.Write([]byte(webpage.Text))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Mirror) save(link *url.URL, page *html.Node) {\n\tpath := m.buildLocalPath(link)\n\tdir := filepath.Dir(path)\n\tif err := os.MkdirAll(dir, 0777); err != nil {\n\t\tlog.Fatalf(\"creating dir %q: %v\", dir, err)\n\t}\n\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\tlog.Fatalf(\"creating file %q: %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\terr = html.Render(file, page)\n\tif err != nil {\n\t\tlog.Fatalf(\"copying to %q: %v\", path, err)\n\t}\n}", "func saveWebPage(cr *Crawler, url, extension string, content []byte) {\n\tname := strings.Replace(strings.Replace(url, \":\", \"*\", -1), \"/\", \"!\", -1)\n\tfilename := cr.destinationPath + \"/\" + name + \".\" + extension\n\texisting := cr.destinationPath + \"/\" + name\n\tif extension == \"done\" {\n\t\texisting += \".saved\"\n\t} else {\n\t\tif extension == \"saved\" {\n\t\t\texisting += \".ready\"\n\t\t}\n\t\tfile, err := os.Create(existing)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfile.Write(content)\n\t\tfile.Close()\n\t}\n\tif err := os.Rename(existing, filename); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (p *WikiPage) saveWiki() error {\n\tfilename := p.Title + \".txt\"\n\treturn ioutil.WriteFile(filename, p.Body, 0600)\n}", "func (s store) Save() {\n\ts.writeToDisk()\n}", "func (s *FilesystemStore) save(session *SessionImp) error {\n\tencoded, err := securecookie.EncodeMulti(session.name, session.Values,\n\t\ts.Codecs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfilename := filepath.Join(s.path, \"session_\"+session.ID)\n\tfileMutex.Lock()\n\tdefer fileMutex.Unlock()\n\treturn ioutil.WriteFile(filename, []byte(encoded), 0600)\n}", "func (b *Bookmarks) Save() error {\n\treturn b.WriteToFile(b.Filename)\n}", "func SaveFile(name string, content string) {\n\tmyself, error := user.Current()\n\n\tif error != nil {\n\t\tfmt.Println(error)\n\t}\n\n\tfullPath := myself.HomeDir + \"/Documents/Server/\" + name\n\tfmt.Println(\"FILE SAVED AT => \" + fullPath)\n\tioutil.WriteFile(fullPath, []byte(content), 0644)\n}", "func (s *state) Save(path string) error {\n\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\ts.mu.Lock()\n\terr = gob.NewEncoder(f).Encode(s.sessions)\n\ts.mu.Unlock()\n\treturn err\n}", "func (s *FilesystemStore) Save(c *kelly.Context, session *SessionImp) error {\n\t// Delete if max-age is <= 0\n\tif session.Options.MaxAge <= 0 {\n\t\tif err := s.erase(session); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttp.SetCookie(c, NewCookie(session.name, \"\", session.Options))\n\t\treturn nil\n\t}\n\n\tif session.ID == \"\" {\n\t\t// Because the ID is used in the filename, encode it to\n\t\t// use alphanumeric characters only.\n\t\tsession.ID = strings.TrimRight(\n\t\t\tbase32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), \"=\")\n\t}\n\tif err := s.save(session); err != nil {\n\t\treturn err\n\t}\n\tencoded, err := securecookie.EncodeMulti(session.name, session.ID,\n\t\ts.Codecs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.SetCookie(c, NewCookie(session.name, encoded, session.Options))\n\treturn nil\n}", "func (h *Homework) save() (err error) {\n\tbuf, err := json.MarshalIndent(h, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(h.path, buf, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func savePageMemory_(index int) {\n\tsite := fmt.Sprintf(\"http://c.api.globo.com/news/%s.json\", ufs[index])\n\tfile, err := http.Get(site)\n\t//connection error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t//get all data from website\n\tdataByte, err := ioutil.ReadAll(file.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t//split the data\n\tdataSplit := split(dataByte)\n\tsession := connectionDB()\n\tdefer session.Close()\n\tc := session.DB(\"apidb\").C(\"news\")\n\tvar ufPage UfPage\n\tufPage.Uf = ufs[index]\n\tufPage.Pageuf = make([]Page, len(dataSplit))\n\tfor i := 0; i < len(dataSplit); i++ {\n\t\tufPage.Pageuf[i] = unMarshal([]byte(dataSplit[i]))\n\t}\n\t_, err = c.Upsert(bson.M{\"uf\": ufs[index]}, &ufPage)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (bh browserHistory) Save() error {\n\tbytes, err := json.Marshal(bh.Records)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjs.Global().Get(\"localStorage\").Set(\"history\", string(bytes))\n\n\treturn nil\n}", "func (d *DiskStorage) Save() error {\n\n\tvar file, err = os.OpenFile(d.path, os.O_RDWR, 0644)\n\tif d.isError(err) {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, errWrite := file.WriteString(d.String())\n\treturn errWrite\n}", "func (p *Entry) Save() (err error) {\n\tfm, err := frontmatter.Marshal(&p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar perm os.FileMode = 0666\n\tif err = ioutil.WriteFile(p.Path, append(fm, p.Body...), perm); err != nil {\n\t\tfmt.Println(\"Dump:\")\n\t\tfmt.Println(string(fm))\n\t\tfmt.Println(string(p.Body))\n\t}\n\treturn err\n}", "func Save(path string, v interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.OpenFile(path, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn formatter.Encode(file, v)\n}", "func (wlt *Wallet) Save(dir string) error {\n\tr := NewReadableWallet(*wlt)\n\treturn r.Save(filepath.Join(dir, wlt.GetFilename()))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
public static native int floatToRawIntBits(float value);
func floatToRawIntBits(frame *rtda.Frame) { floatVal := frame.LocalVars().GetFloat(0) frame.OperandStack().PushInt(int32(math.Float32bits(floatVal))) }
[ "func JDK_java_lang_Float_floatToRawIntBits(value Float) Int {\n\tbits := math.Float32bits(float32(value))\n\treturn Int(int32(bits))\n}", "func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) }", "func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) }", "func floatBits(f float64) uint64 {\n\t// Take f parameter and determine bit pattern.\n\t// Translate bit pattern into a value of type uint64\n\ti := *(*uint64)(unsafe.Pointer(&f))\n\t//fmt.Printf(\"strconv.FormatUint: %v\\n\", strconv.FormatUint(i, 2))\n\t// Return new value\n\treturn i\n}", "func intFromFloat(f float64) int {\n\treturn int(math.Float64bits(f))\n}", "func Float64frombits(b uint64) float64 { return *(*float64)(unsafe.Pointer(&b)) }", "func Floatbits(tk obj.Token, args []oop.VarDef) oop.Val {\n\tval := args[0].Val\n\tif val.Type != oop.Int && val.Type != oop.Float {\n\t\tval.Data = 0.0\n\t}\n\tf := val.Data.(float64)\n\treturn oop.Val{Data: float64(*(*uint64)(unsafe.Pointer(&f))), Type: oop.Int}\n}", "func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) }", "func (f Float) Bits() (a, b uint64) {\n\treturn math.Float64bits(f.high), math.Float64bits(f.low)\n}", "func Floatfrombits(tk obj.Token, args []oop.VarDef) oop.Val {\n\tval := args[0].Val\n\tif val.Type != oop.Int {\n\t\tval.Data = 0.0\n\t}\n\tb := uint64(val.Data.(float64))\n\treturn oop.Val{Data: *(*float64)(unsafe.Pointer(&b)), Type: oop.Float}\n}", "func IeeeFloatToInt(b [10]byte) int {\n\tvar i uint32\n\t// Negative number\n\tif (b[0] & 0x80) == 1 {\n\t\treturn 0\n\t}\n\n\t// Less than 1\n\tif b[0] <= 0x3F {\n\t\treturn 1\n\t}\n\n\t// Too big\n\tif b[0] > 0x40 {\n\t\treturn 67108864\n\t}\n\n\t// Still too big\n\tif b[0] == 0x40 && b[1] > 0x1C {\n\t\treturn 800000000\n\t}\n\n\ti = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1)\n\ti >>= (29 - uint32(b[1]))\n\n\treturn int(i)\n}", "func Float64From32Bits(f float64) float64 {\n\tif f < 0 {\n\t\treturn 0\n\t}\n\treturn f\n}", "func floatFromInt(i int) float64 {\n\treturn math.Float64frombits(uint64(i))\n}", "func IntToFloat(val int) float64 {\r\n\r\n\treturn float64(val)\r\n\r\n}", "func floatToFix(x float32) int32 {\n\treturn int32(x * 64.0)\n}", "func IntToIeeeFloat(i int) [10]byte {\n\tb := [10]byte{}\n\tnum := float64(i)\n\n\tvar sign int\n\tvar expon int\n\tvar fMant, fsMant float64\n\tvar hiMant, loMant uint\n\n\tif num < 0 {\n\t\tsign = 0x8000\n\t} else {\n\t\tsign = 0\n\t}\n\n\tif num == 0 {\n\t\texpon = 0\n\t\thiMant = 0\n\t\tloMant = 0\n\t} else {\n\t\tfMant, expon = math.Frexp(num)\n\t\tif (expon > 16384) || !(fMant < 1) { /* Infinity or NaN */\n\t\t\texpon = sign | 0x7FFF\n\t\t\thiMant = 0\n\t\t\tloMant = 0 /* infinity */\n\t\t} else { /* Finite */\n\t\t\texpon += 16382\n\t\t\tif expon < 0 { /* denormalized */\n\t\t\t\tfMant = math.Ldexp(fMant, expon)\n\t\t\t\texpon = 0\n\t\t\t}\n\t\t\texpon |= sign\n\t\t\tfMant = math.Ldexp(fMant, 32)\n\t\t\tfsMant = math.Floor(fMant)\n\t\t\thiMant = uint(fsMant)\n\t\t\tfMant = math.Ldexp(fMant-fsMant, 32)\n\t\t\tfsMant = math.Floor(fMant)\n\t\t\tloMant = uint(fsMant)\n\t\t}\n\t}\n\n\tb[0] = byte(expon >> 8)\n\tb[1] = byte(expon)\n\tb[2] = byte(hiMant >> 24)\n\tb[3] = byte(hiMant >> 16)\n\tb[4] = byte(hiMant >> 8)\n\tb[5] = byte(hiMant)\n\tb[6] = byte(loMant >> 24)\n\tb[7] = byte(loMant >> 16)\n\tb[8] = byte(loMant >> 8)\n\tb[9] = byte(loMant)\n\n\treturn b\n}", "func Float32(b []byte) float32 {\n\tv := float32(0)\n\tcopy((*(*[size32bitsInBytes]byte)(unsafe.Pointer(&v)))[:], b)\n\treturn v\n}", "func PtrFloat(v float32) *float32 { return &v }", "func (f Float) Bits() (a, b uint64) {\n\treturn f.a, f.b\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send marshals and sends the DescribeUserHierarchyStructure API request.
func (r DescribeUserHierarchyStructureRequest) Send(ctx context.Context) (*DescribeUserHierarchyStructureResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &DescribeUserHierarchyStructureResponse{ DescribeUserHierarchyStructureOutput: r.Request.Data.(*DescribeUserHierarchyStructureOutput), response: &aws.Response{Request: r.Request}, } return resp, nil }
[ "func (s *DescribeUserHierarchyStructureOutput) SetHierarchyStructure(v *HierarchyStructure) *DescribeUserHierarchyStructureOutput {\n\ts.HierarchyStructure = v\n\treturn s\n}", "func (s *UpdateUserHierarchyStructureInput) SetHierarchyStructure(v *HierarchyStructureUpdate) *UpdateUserHierarchyStructureInput {\n\ts.HierarchyStructure = v\n\treturn s\n}", "func GetUserHomeStructureHandler(w http.ResponseWriter, r *http.Request) error {\n\t// get username from jwt\n\tok, username := tools.GetUserNameFromToken(r.Header.Get(\"Authorization\"), AuthRedisClient)\n\tif !ok {\n\t\tw.WriteHeader(401)\n\t\treturn nil\n\t}\n\n\t// Get project information\n\tsession := MysqlEngine.NewSession()\n\tu := model.User{Username: username}\n\tok, err := u.GetWithUsername(session)\n\tif !ok {\n\t\tw.WriteHeader(400)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get file structure\n\tstructure, err := model.GetFileStructure(username)\n\tif err != nil {\n\t\treturn err\n\t}\n\tret, err := json.Marshal(structure)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.Write(ret)\n\treturn nil\n}", "func (r DescribeUserRequest) Send(ctx context.Context) (*DescribeUserOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*DescribeUserOutput), nil\n}", "func (status UpstreamStatus) MarshalHierarchical() string {\n\thierarchy := hierr.Push(\n\t\t\"upstream\",\n\t\t\"total: \"+strconv.Itoa(status.Total),\n\t\tfmt.Sprintf(\n\t\t\t\"success: %d (%.2f%%)\",\n\t\t\tstatus.Success, status.SuccessPercent,\n\t\t),\n\t\tfmt.Sprintf(\n\t\t\t\"error: %d (%.2f%%)\",\n\t\t\tstatus.Error, status.ErrorPercent,\n\t\t),\n\t)\n\n\tif len(status.Slaves) > 0 {\n\t\tslaves := errors.New(\"slaves\")\n\t\tfor _, slave := range status.Slaves {\n\t\t\tslaves = hierr.Push(slaves, slave.MarshalHierarchical())\n\t\t}\n\n\t\thierarchy = hierr.Push(hierarchy, slaves)\n\t}\n\n\treturn hierr.String(hierarchy)\n}", "func (c *Connect) DescribeUserHierarchyStructureWithContext(ctx aws.Context, input *DescribeUserHierarchyStructureInput, opts ...request.Option) (*DescribeUserHierarchyStructureOutput, error) {\n\treq, out := c.DescribeUserHierarchyStructureRequest(input)\n\treq.SetContext(ctx)\n\treq.ApplyOptions(opts...)\n\treturn out, req.Send()\n}", "func (r DescribeUserRequest) Send(ctx context.Context) (*DescribeUserResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DescribeUserResponse{\n\t\tDescribeUserOutput: r.Request.Data.(*DescribeUserOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (*MessageHubBlockUserRequest) Descriptor() ([]byte, []int) {\n\treturn file_messagehub_proto_rawDescGZIP(), []int{10}\n}", "func (u *DbUser) UserStructureLevel(meetingID int) string {\n\tif u.Level == \"\" {\n\t\treturn u.DefaultLevel\n\t}\n\treturn u.Level\n}", "func (*Out_CreateUserLevel) Descriptor() ([]byte, []int) {\n\treturn file_modules_user_user_level_user_level_proto_rawDescGZIP(), []int{11}\n}", "func (*CreateOrganizationRequest_User) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_auth_proto_rawDescGZIP(), []int{6, 1}\n}", "func (a *Client) GetUniverseStructures(params *GetUniverseStructuresParams) (*GetUniverseStructuresOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseStructuresParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_structures\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/structures/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseStructuresReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseStructuresOK), nil\n\n}", "func (a *Client) GetUniverseStructures(params *GetUniverseStructuresParams) (*GetUniverseStructuresOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseStructuresParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_structures\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/structures/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseStructuresReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseStructuresOK), nil\n\n}", "func CreateHierarchyPage(req *http.Request, bp core.Page, h hierarchyClient.Model, dst dataset.DatasetDetails, f filter.Model, selectedValueLabels map[string]string, dims dataset.VersionDimensions, name, curPath, datasetID, apiRouterVersion, lang, serviceMessage string, emergencyBannerContent zebedee.EmergencyBanner) model.Hierarchy {\n\tp := model.Hierarchy{\n\t\tPage: bp,\n\t}\n\tp.BetaBannerEnabled = true\n\tp.FeatureFlags.SixteensVersion = sixteensVersion\n\tp.Language = lang\n\tp.RemoveGalleryBackground = true\n\n\tmapCookiePreferences(req, &p.CookiesPreferencesSet, &p.CookiesPolicy)\n\n\tctx := req.Context()\n\tlog.Info(ctx, \"mapping api response models to hierarchy page\", log.Data{\"filterID\": f.FilterID, \"datasetID\": datasetID, \"label\": h.Label})\n\n\tpageTitle := helpers.TitleCaseStr(name)\n\tfor i := range dims.Items {\n\t\tif dims.Items[i].Name == name {\n\t\t\tp.Metadata.Description = dims.Items[i].Description\n\t\t\tif len(dims.Items[i].Label) > 0 {\n\t\t\t\tpageTitle = dims.Items[i].Label\n\t\t\t}\n\t\t}\n\t}\n\n\tp.DatasetTitle = dst.Title\n\tp.Data.DimensionName = pageTitle\n\tp.DatasetId = datasetID\n\tp.URI = req.URL.Path\n\tp.ServiceMessage = serviceMessage\n\tp.EmergencyBanner = mapEmergencyBanner(emergencyBannerContent)\n\n\tvar title string\n\tif len(h.Breadcrumbs) == 0 {\n\t\ttitle = pageTitle\n\t} else {\n\t\ttitle = h.Label\n\t}\n\n\tvar ok bool\n\tif p.Type, ok = hierarchyBrowseLookup[name]; !ok {\n\t\tp.Type = \"type\"\n\t}\n\n\tp.SearchDisabled = true\n\n\tp.Data.SearchURL = fmt.Sprintf(\"/filters/%s/dimensions/%s/search\", f.FilterID, name)\n\n\tversionURL, err := url.Parse(f.Links.Version.HRef)\n\tif err != nil {\n\t\tlog.Warn(ctx, \"unable to parse version url\", log.FormatErrors([]error{err}))\n\t}\n\tversionPath := strings.TrimPrefix(versionURL.Path, apiRouterVersion)\n\n\tp.IsInFilterBreadcrumb = true\n\n\t_, edition, _, err := helpers.ExtractDatasetInfoFromPath(ctx, versionPath)\n\tif err != nil {\n\t\tlog.Warn(ctx, \"unable to extract edition from url\", log.FormatErrors([]error{err}))\n\t}\n\n\tp.Breadcrumb = append(\n\t\tp.Breadcrumb,\n\t\tcore.TaxonomyNode{\n\t\t\tTitle: dst.Title,\n\t\t\tURI: fmt.Sprintf(\"/datasets/%s/editions\", dst.ID),\n\t\t}, core.TaxonomyNode{\n\t\t\tTitle: edition,\n\t\t\tURI: versionPath,\n\t\t}, core.TaxonomyNode{\n\t\t\tTitle: \"Filter options\",\n\t\t\tURI: fmt.Sprintf(\"/filters/%s/dimensions\", f.FilterID),\n\t\t})\n\n\tif len(h.Breadcrumbs) > 0 {\n\t\tif name == \"geography\" {\n\t\t\tp.Breadcrumb = append(p.Breadcrumb, core.TaxonomyNode{\n\t\t\t\tTitle: \"Geographic Areas\",\n\t\t\t\tURI: fmt.Sprintf(\"/filters/%s/dimensions/%s\", f.FilterID, \"geography\"),\n\t\t\t})\n\n\t\t\tif !topLevelGeographies[h.Links.Code.ID] {\n\t\t\t\tfor i := len(h.Breadcrumbs) - 1; i >= 0; i-- {\n\t\t\t\t\tbreadcrumb := h.Breadcrumbs[i]\n\n\t\t\t\t\tif !topLevelGeographies[breadcrumb.Links.Code.ID] {\n\t\t\t\t\t\tvar uri string\n\t\t\t\t\t\tif breadcrumb.Links.Code.ID != \"\" {\n\t\t\t\t\t\t\turi = fmt.Sprintf(\"/filters/%s/dimensions/%s/%s\", f.FilterID, name, breadcrumb.Links.Code.ID)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\turi = fmt.Sprintf(\"/filters/%s/dimensions/%s\", f.FilterID, name)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tp.Breadcrumb = append(p.Breadcrumb, core.TaxonomyNode{\n\t\t\t\t\t\t\tTitle: breadcrumb.Label,\n\t\t\t\t\t\t\tURI: uri,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor i := len(h.Breadcrumbs) - 1; i >= 0; i-- {\n\t\t\t\tbreadcrumb := h.Breadcrumbs[i]\n\n\t\t\t\tvar uri string\n\t\t\t\tif breadcrumb.Links.Code.ID != \"\" {\n\t\t\t\t\turi = fmt.Sprintf(\"/filters/%s/dimensions/%s/%s\", f.FilterID, name, breadcrumb.Links.Code.ID)\n\t\t\t\t} else {\n\t\t\t\t\turi = fmt.Sprintf(\"/filters/%s/dimensions/%s\", f.FilterID, name)\n\t\t\t\t}\n\n\t\t\t\tp.Breadcrumb = append(p.Breadcrumb, core.TaxonomyNode{\n\t\t\t\t\tTitle: breadcrumb.Label,\n\t\t\t\t\tURI: uri,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tp.Breadcrumb = append(p.Breadcrumb, core.TaxonomyNode{\n\t\tTitle: title,\n\t})\n\n\tp.FilterID = f.FilterID\n\tp.Data.Title = title\n\tp.Metadata.Title = fmt.Sprintf(\"Filter Options - %s\", title)\n\n\tif len(h.Breadcrumbs) > 0 {\n\t\tif len(h.Breadcrumbs) == 1 || topLevelGeographies[h.Breadcrumbs[0].Links.Code.ID] && name == \"geography\" {\n\t\t\tp.Data.Parent = pageTitle\n\t\t\tp.Data.GoBack = model.Link{\n\t\t\t\tURL: fmt.Sprintf(\"/filters/%s/dimensions/%s\", f.FilterID, name),\n\t\t\t}\n\t\t} else {\n\t\t\tp.Data.Parent = h.Breadcrumbs[0].Label\n\t\t\tp.Data.GoBack = model.Link{\n\t\t\t\tURL: fmt.Sprintf(\"/filters/%s/dimensions/%s/%s\", f.FilterID, name, h.Breadcrumbs[0].Links.Code.ID),\n\t\t\t}\n\t\t}\n\t}\n\n\tp.Data.AddAllFilters.Amount = strconv.Itoa(len(h.Children))\n\tp.Data.AddAllFilters.URL = curPath + \"/add-all\"\n\tfor _, child := range h.Children {\n\t\tif child.HasData {\n\t\t\tp.Data.HasData = true\n\t\t\tbreak\n\t\t}\n\t}\n\tp.Data.RemoveAll.URL = curPath + \"/remove-all\"\n\n\tfor option, label := range selectedValueLabels {\n\t\tp.Data.FiltersAdded = append(p.Data.FiltersAdded, model.Filter{\n\t\t\tLabel: label,\n\t\t\tRemoveURL: fmt.Sprintf(\"%s/remove/%s\", curPath, option),\n\t\t\tID: option,\n\t\t})\n\t}\n\n\tif h.HasData && len(h.Breadcrumbs) == 0 {\n\t\t_, selected := selectedValueLabels[h.Links.Code.ID]\n\t\tp.Data.FilterList = append(p.Data.FilterList, model.List{\n\t\t\tLabel: h.Label,\n\t\t\tID: h.Links.Code.ID,\n\t\t\tSubNum: \"0\",\n\t\t\tSubURL: \"\",\n\t\t\tSelected: selected,\n\t\t\tHasData: true,\n\t\t})\n\t}\n\n\tfor _, child := range h.Children {\n\t\t_, selected := selectedValueLabels[child.Links.Code.ID]\n\t\tp.Data.FilterList = append(p.Data.FilterList, model.List{\n\t\t\tLabel: child.Label,\n\t\t\tID: child.Links.Code.ID,\n\t\t\tSubNum: strconv.Itoa(child.NumberofChildren),\n\t\t\tSubURL: fmt.Sprintf(\"redirect:/filters/%s/dimensions/%s/%s\", f.FilterID, name, child.Links.Code.ID),\n\t\t\tSelected: selected,\n\t\t\tHasData: child.HasData,\n\t\t})\n\t}\n\n\tp.Data.SaveAndReturn.URL = curPath + \"/update\"\n\tp.Data.Cancel.URL = fmt.Sprintf(\"/filters/%s/dimensions\", f.FilterID)\n\n\treturn p\n}", "func (r *DeviceConfigurationUserOverviewRequest) Get(ctx context.Context) (resObj *DeviceConfigurationUserOverview, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (s *RPC) userDetailHndl(id uint64, params json.RawMessage) (rr jrpc.Response) {\n\treq := engine.UserDetailRequest{}\n\tif err := json.Unmarshal(params, &req); err != nil {\n\t\treturn jrpc.Response{Error: err.Error()}\n\t}\n\tvalue, err := s.eng.UserDetail(req)\n\treturn jrpc.EncodeResponse(id, value, err)\n}", "func (*In_CreateUserLevel) Descriptor() ([]byte, []int) {\n\treturn file_modules_user_user_level_user_level_proto_rawDescGZIP(), []int{10}\n}", "func (*ListMembersResponse_OrganizationUser) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_organizationmanager_v1_user_service_proto_rawDescGZIP(), []int{1, 0}\n}", "func (status MirrorStatus) MarshalHierarchical() string {\n\thierarchy := hierr.Push(\n\t\tstatus.Name,\n\t\tfmt.Sprintf(\"state: %s\", status.State),\n\t)\n\n\tif status.ModifyDate > 0 {\n\t\thierarchy = hierr.Push(\n\t\t\thierarchy,\n\t\t\tfmt.Sprintf(\"modify date: %v\", status.ModifyDate),\n\t\t)\n\t}\n\n\treturn hierr.String(hierarchy)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SDKResponseMetdata returns the response metadata for the DescribeUserHierarchyStructure request.
func (r *DescribeUserHierarchyStructureResponse) SDKResponseMetdata() *aws.Response { return r.response }
[ "func (r *DescribeUserResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListHumanTaskUisResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeOrganizationConfigurationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeCacheSubnetGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeTemplatePermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateUserResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeAccountAuditConfigurationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListUsersResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeDBClusterParameterGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ModifySelfservicePermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeIdentityUsageResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeClusterParameterGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeFileSystemsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListDirectoriesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *GetRelationalDatabaseMasterUserPasswordResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteUserAttributesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListSecurityProfilesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RegisterUserResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeregisterTransitGatewayMulticastGroupMembersResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Func to remove lines if contains keyword 'TODO'
func removeText(fileName string) { //Skip main.go file if fileName != "main.go" { //Read file bytes from filename param, a success call return err==null, not err==EOF input, err := ioutil.ReadFile(fileName) if err != nil { log.Fatalln(err) } //Convert content to string text := string(input) //Replace keyword 'TODO' by regex re := regexp.MustCompile(".*TODO.*\r?\n") lines := re.ReplaceAllString(text, "") //Write string into a file err = WriteToFile(fileName, lines) if err != nil { log.Fatal(err) } } }
[ "func cleanMsg(msg string) string {\n\tremComments := bytes.Buffer{}\n\tsplit := strings.SplitAfter(msg, \"\\n\")\n\tfor _, line := range split {\n\t\ttrim := strings.TrimSpace(line)\n\t\tif strings.HasPrefix(trim, string(commentChar)+\" \"+snipLine) {\n\t\t\tbreak\n\t\t}\n\t\tif strings.HasPrefix(trim, string(commentChar)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tremComments.WriteString(line)\n\t}\n\treturn strings.TrimSpace(remComments.String())\n}", "func (rign *CFGoReadIgnore) Clean() {\n}", "func removeDoNotEdit(dir string) error {\n\tsrcDir := filepath.Join(dir, \"src\")\n\treturn filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() || filepath.Ext(path) != GoExtension {\n\t\t\treturn nil\n\t\t}\n\n\t\tset := token.NewFileSet()\n\t\tfile, err := parser.ParseFile(set, path, nil, parser.ParseComments)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf, err := os.OpenFile(path, os.O_RDWR, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tfor _, comment := range file.Comments {\n\t\t\tdata := make([]byte, comment.End()-comment.Pos())\n\t\t\tif _, err := f.Seek(int64(comment.Pos()-1), io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := io.ReadFull(f, data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcommentStr := string(data)\n\t\t\tif strings.Contains(commentStr, \"DO NOT EDIT\") {\n\t\t\t\tcommentStr = strings.Replace(commentStr, \"DO NOT EDIT\", \"XXXXXXXXXXX\", -1)\n\t\t\t\tif _, err := f.WriteAt([]byte(commentStr), int64(comment.Pos()-1)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (todo Todo) Remove() error {\n\treturn todo.updateInPlace(func(lineNumber int, line string) (string, bool) {\n\t\tif lineNumber == todo.Line {\n\t\t\treturn \"\", true\n\t\t}\n\n\t\treturn line, false\n\t})\n}", "func cleanupForInclude(md string) string {\n\tlines := strings.Split(md, \"\\n\")\n\n\t// add title for component docs\n\tfirstL := lines[0]\n\ttitle := strings.TrimPrefix(firstL, \"## \")\n\tlines[0] = \"---\"\n\tnewlines := []string{\"---\", \"title: \" + title}\n\tnewlines = append(newlines, lines...)\n\n\tcleanMd := \"\"\n\tfor i, line := range newlines {\n\t\tif line == \"### SEE ALSO\" {\n\t\t\tbreak\n\t\t}\n\n\t\tcleanMd += line\n\t\tif i < len(newlines)-1 {\n\t\t\tcleanMd += \"\\n\"\n\t\t}\n\t}\n\n\tcleanMd += \"###### Auto generated by [spf13/cobra script in Karmada](https://github.com/karmada-io/karmada/tree/master/hack/tools/gencomponentdocs)\"\n\treturn cleanMd\n}", "func TestGoDocSkipLinesPass(t *testing.T) {\n\taccept(t, \"godoc_test.go\", \"TestGoDocSkipLinesPass\")\n}", "func removeIgnorableTexts(s string) string {\n\tlines := strings.Split(strings.TrimRight(s, \"\\n\"), \"\\n\")\n\tvar start int\n\tfor ; start < len(lines); start++ {\n\t\tline := strings.TrimSpace(lines[start])\n\t\tvar matches bool\n\t\tfor _, re := range ignorableTexts {\n\t\t\tif re.MatchString(line) {\n\t\t\t\tmatches = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matches {\n\t\t\tbreak\n\t\t}\n\t}\n\tend := len(lines)\n\tif start > end {\n\t\treturn \"\\n\"\n\t}\n\treturn strings.Join(lines[start:end], \"\\n\") + \"\\n\"\n}", "func shouldKeep(e bf.Expr) bool {\n\tc := e.Comment()\n\treturn len(c.Suffix) > 0 && strings.HasPrefix(c.Suffix[0].Token, keep)\n}", "func RemoveLine(p, startsWith string) {\n\tf, err := os.Open(p)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tvar outText string\n\tfound := false\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tif strings.HasPrefix(scanner.Text(), startsWith) {\n\t\t\tfound = true\n\t\t} else {\n\t\t\toutText += scanner.Text() + string('\\n')\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn\n\t}\n\n\tif found {\n\t\tWriteData(p, []byte(outText))\n\t}\n}", "func want(f *ast.File) []string {\n\tfor _, c := range f.Comments {\n\t\ttext := strings.TrimSpace(c.Text())\n\t\tif t := strings.TrimPrefix(text, \"WANT:\\n\"); t != text {\n\t\t\treturn strings.Split(t, \"\\n\")\n\t\t}\n\t}\n\treturn nil\n}", "func (a *Annotation) remove(c context.Context, r io.Reader) (bool, error) {\n\tchange := &annotationRemove{}\n\n\terr := json.NewDecoder(r).Decode(change)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tmodified := false\n\n\tif change.Time {\n\t\ta.SnoozeTime = 0\n\t\tmodified = true\n\t}\n\n\tif change.Bugs != nil {\n\t\tset := stringset.NewFromSlice(a.Bugs...)\n\t\tfor _, bug := range change.Bugs {\n\t\t\tset.Del(bug)\n\t\t}\n\t\ta.Bugs = set.ToSlice()\n\t\tmodified = true\n\t}\n\n\t// Client passes in a list of comment indices to delete.\n\tfor _, i := range change.Comments {\n\t\tif i < 0 || i >= len(a.Comments) {\n\t\t\treturn false, errors.New(\"Invalid comment index\")\n\t\t}\n\t\ta.Comments = append(a.Comments[:i], a.Comments[i+1:]...)\n\t\tmodified = true\n\t}\n\n\tif change.GroupID {\n\t\ta.GroupID = \"\"\n\t\tmodified = true\n\t}\n\n\tif modified {\n\t\ta.ModificationTime = clock.Now(c)\n\t}\n\n\treturn false, nil\n}", "func ShouldKeep(e bzl.Expr) bool {\n\tfor _, c := range append(e.Comment().Before, e.Comment().Suffix...) {\n\t\ttext := strings.TrimSpace(strings.TrimPrefix(c.Token, \"#\"))\n\t\tif text == \"keep\" || strings.HasPrefix(text, \"keep: \") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func functionWithWrappedLineComment() {\n\treturn nil\n}", "func TODO(project, label string, fullTime bool) bool {\n\treturn lists[\"todo\"].Print(project, label, fullTime)\n}", "func (m mark) deleteLine() {\n\tb := m.buf\n\tif len(b.text) == 1 {\n\t\tb.text[0] = newLine()\n\t\treturn\n\t}\n\tb.text = append(b.text[:m.line], b.text[m.line+1:]...)\n}", "func removeLines(fn string, start, n int) (err error) {\n\tlogs.INFO.Println(\"Clear file -> \", fn)\n\tif n < 0 {\n\t\tn = store.getLines()\n\t}\n\tif n == 0 {\n\t\tlogs.INFO.Println(\"Nothing to clear\")\n\t\tseek = 0\n\t\treturn nil\n\t}\n\tlogs.INFO.Println(\"Total lines -> \", n)\n\tif start < 1 {\n\t\tlogs.WARNING.Println(\"Invalid request. line numbers start at 1.\")\n\t}\n\tvar f *os.File\n\tif f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {\n\t\tlogs.CRITICAL.Println(\"Failed to open the file -> \", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif cErr := f.Close(); err == nil {\n\t\t\terr = cErr\n\t\t}\n\t}()\n\tvar b []byte\n\tif b, err = ioutil.ReadAll(f); err != nil {\n\t\tlogs.CRITICAL.Println(\"Failed to reading the file -> \", err)\n\t\treturn\n\t}\n\tcut, ok := skip(b, start-1)\n\tif !ok {\n\t\tlogs.CRITICAL.Printf(\"less than %d lines -> \", start)\n\t\treturn\n\t}\n\tif n == 0 {\n\t\treturn nil\n\t}\n\ttail, ok := skip(cut, n)\n\tif !ok {\n\t\tlogs.CRITICAL.Printf(\"less than %d lines after line %d \", n, start)\n\t\treturn\n\t}\n\tt := int64(len(b) - len(cut))\n\tif err = f.Truncate(t); err != nil {\n\t\treturn\n\t}\n\t// Writing in the archive the bytes already with cut removed\n\tif len(tail) > 0 {\n\t\t_, err = f.WriteAt(tail, t)\n\t}\n\treturn\n}", "func stripCommentedOutLines(lines []string) []string {\n\tvar outputLines []string\n\tfor _, line := range lines {\n\t\tif commentedOutLineRegexp.MatchString(line) {\n\t\t\toutputLines = append(outputLines, \"\")\n\t\t} else {\n\t\t\toutputLines = append(outputLines, line)\n\t\t}\n\t}\n\treturn outputLines\n}", "func (r region) delete() mark {\n\tvar fr, to = orderMarks(r.start, r.end)\n\tb := fr.buf\n\tb.text[fr.line] = append(b.text[fr.line][:fr.pos], b.text[to.line][to.pos:]...)\n\tif to.line > fr.line {\n\t\tto.line -= b.deleteLines(mark{fr.line + 1, 0, b}, to)\n\t\tif fr.atEmptyLine() && fr.maxLine() > 0 {\n\t\t\tfr.deleteLine()\n\t\t}\n\t}\n\tfr.fixPos()\n\treturn fr\n}", "func MultipleLinesCommentNoPunctuationAnywhere() string {\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewWorkload constructs and returns a workload representation from an application reference.
func NewWorkload(cluster *kubernetes.Cluster, app models.AppRef) *Workload { return &Workload{cluster: cluster, app: app} }
[ "func NewWorkload(ctx *pulumi.Context,\n\tname string, args *WorkloadArgs, opts ...pulumi.ResourceOption) (*Workload, error) {\n\tif args == nil {\n\t\targs = &WorkloadArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Workload\n\terr := ctx.RegisterResource(\"example::Workload\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewWorkloadDefinition(ctx *pulumi.Context,\n\tname string, args *WorkloadDefinitionArgs, opts ...pulumi.ResourceOption) (*WorkloadDefinition, error) {\n\tif args == nil {\n\t\targs = &WorkloadDefinitionArgs{}\n\t}\n\targs.ApiVersion = pulumi.StringPtr(\"core.oam.dev/v1alpha2\")\n\targs.Kind = pulumi.StringPtr(\"WorkloadDefinition\")\n\tvar resource WorkloadDefinition\n\terr := ctx.RegisterResource(\"kubernetes:core.oam.dev/v1alpha2:WorkloadDefinition\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func CreateWorkload(pce PCE, workload Workload) (Workload, APIResponse, error) {\n\tvar newWL Workload\n\tvar api APIResponse\n\tvar err error\n\n\t// Build the API URL\n\tapiURL, err := url.Parse(\"https://\" + pceSanitization(pce.FQDN) + \":\" + strconv.Itoa(pce.Port) + \"/api/v2/orgs/\" + strconv.Itoa(pce.Org) + \"/workloads\")\n\tif err != nil {\n\t\treturn newWL, api, fmt.Errorf(\"create workload - %s\", err)\n\t}\n\n\t// Call the API\n\tworkloadJSON, err := json.Marshal(workload)\n\tif err != nil {\n\t\treturn newWL, api, fmt.Errorf(\"create workload - %s\", err)\n\t}\n\tapi, err = apicall(\"POST\", apiURL.String(), pce, workloadJSON, false)\n\tif err != nil {\n\t\treturn newWL, api, fmt.Errorf(\"create workload - %s\", err)\n\t}\n\n\t// Marshal JSON\n\tjson.Unmarshal([]byte(api.RespBody), &newWL)\n\n\treturn newWL, api, nil\n}", "func (c *Client) CreateWorkload(ctx context.Context, params *CreateWorkloadInput, optFns ...func(*Options)) (*CreateWorkloadOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateWorkloadInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateWorkload\", params, optFns, addOperationCreateWorkloadMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateWorkloadOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (in *Workload) DeepCopy() *Workload {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Workload)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WorkloadService) GetWorkload(namespace string, workloadName string, includeServices bool) (*models.Workload, error) {\n\tmodel := &models.Workload{}\n\n\tdeployment, err := in.k8s.GetDeployment(namespace, workloadName)\n\tif deployment == nil || err != nil {\n\t\treturn nil, err\n\t}\n\tmodel.Parse(deployment)\n\n\tselector := labels.FormatLabels(deployment.Spec.Template.Labels)\n\tpods, err := in.k8s.GetPods(namespace, selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmodel.SetPods(pods)\n\n\tif includeServices {\n\t\tservices, err := in.k8s.GetServices(namespace, deployment.Spec.Template.Labels)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmodel.SetServices(services)\n\t}\n\n\treturn model, nil\n}", "func New(name string, ts Templates, o ...Option) *xpworkloadv1alpha1.KubernetesApplication {\n\topts := &options{\n\t\tnamespace: corev1.NamespaceDefault,\n\t\tcs: &metav1.LabelSelector{}, // The empty selector selects all clusters.\n\t}\n\n\tfor _, apply := range o {\n\t\tapply(opts)\n\t}\n\n\ta := &xpworkloadv1alpha1.KubernetesApplication{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: opts.namespace,\n\t\t\tName: name,\n\t\t\tLabels: opts.labels,\n\t\t\tAnnotations: opts.annotations,\n\t\t\tOwnerReferences: opts.owners,\n\t\t},\n\t\tSpec: xpworkloadv1alpha1.KubernetesApplicationSpec{\n\t\t\tResourceSelector: &metav1.LabelSelector{MatchLabels: opts.labels},\n\t\t\tClusterSelector: opts.cs,\n\t\t\tResourceTemplates: make([]xpworkloadv1alpha1.KubernetesApplicationResourceTemplate, len(ts)),\n\t\t},\n\t\tStatus: xpworkloadv1alpha1.KubernetesApplicationStatus{\n\t\t\tCluster: opts.cluster,\n\t\t},\n\t}\n\n\tfor i, t := range ts {\n\t\tsecrets := opts.secrets.Get(t)\n\t\trt := xpworkloadv1alpha1.KubernetesApplicationResourceTemplate{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t// TODO(negz): Handle the case in which we have templates for\n\t\t\t\t// two resources with the same kind and name but different API\n\t\t\t\t// versions. The below format string will result in a name\n\t\t\t\t// conflict.\n\t\t\t\tName: strings.ToLower(fmt.Sprintf(\"%s-%s-%s\", name, t.GetKind(), t.GetName())),\n\t\t\t\tLabels: opts.labels,\n\t\t\t\tAnnotations: opts.annotations,\n\t\t\t},\n\t\t\tSpec: xpworkloadv1alpha1.KubernetesApplicationResourceSpec{\n\t\t\t\tTemplate: t,\n\t\t\t\tSecrets: make([]corev1.LocalObjectReference, len(secrets)),\n\t\t\t},\n\t\t}\n\n\t\tfor i, name := range secrets {\n\t\t\trt.Spec.Secrets[i] = corev1.LocalObjectReference{Name: name}\n\t\t}\n\n\t\ta.Spec.ResourceTemplates[i] = rt\n\t}\n\n\treturn a\n}", "func GetWorkload(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WorkloadState, opts ...pulumi.ResourceOption) (*Workload, error) {\n\tvar resource Workload\n\terr := ctx.ReadResource(\"example::Workload\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *service) CreateWorkload(id string, payload io.Reader, contentType string) (string, error) {\n\tprefix := async.StoragePath(s.clusterUID, s.apiName)\n\tlog := s.logger.With(zap.String(\"id\", id), zap.String(\"contentType\", contentType))\n\n\tpayloadPath := async.PayloadPath(prefix, id)\n\tlog.Debug(\"uploading payload\", zap.String(\"path\", payloadPath))\n\tif err := s.storage.Upload(payloadPath, payload, contentType); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Debug(\"sending message to queue\")\n\tif err := s.queue.SendMessage(id, id); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstatusPath := fmt.Sprintf(\"%s/%s/status/%s\", prefix, id, async.StatusInQueue)\n\tlog.Debug(fmt.Sprintf(\"setting status to %s\", async.StatusInQueue))\n\tif err := s.storage.Upload(statusPath, strings.NewReader(\"\"), \"text/plain\"); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn id, nil\n}", "func newWorkloadDeployer(in *WorkloadDeployerInput) (*workloadDeployer, error) {\n\tws, err := workspace.Use(afero.NewOsFs())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefaultSession, err := in.SessionProvider.Default()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create default: %w\", err)\n\t}\n\tenvSession, err := in.SessionProvider.FromRole(in.Env.ManagerRoleARN, in.Env.Region)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create env session with region %s: %w\", in.Env.Region, err)\n\t}\n\tdefaultSessEnvRegion, err := in.SessionProvider.DefaultWithRegion(in.Env.Region)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create default session with region %s: %w\", in.Env.Region, err)\n\t}\n\tresources, err := cloudformation.New(defaultSession, cloudformation.WithProgressTracker(os.Stderr)).GetAppResourcesByRegion(in.App, in.Env.Region)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get application %s resources from region %s: %w\", in.App.Name, in.Env.Region, err)\n\t}\n\n\tvar addons stackBuilder\n\taddons, err = addon.ParseFromWorkload(in.Name, ws)\n\tif err != nil {\n\t\tvar notFoundErr *addon.ErrAddonsNotFound\n\t\tif !errors.As(err, &notFoundErr) {\n\t\t\treturn nil, fmt.Errorf(\"parse addons stack for workload %s: %w\", in.Name, err)\n\t\t}\n\t\taddons = nil // so that we can check for no addons with nil comparison\n\t}\n\n\trepoName := RepoName(in.App.Name, in.Name)\n\trepository := repository.NewWithURI(\n\t\tecr.New(defaultSessEnvRegion), repoName, resources.RepositoryURLs[in.Name])\n\tstore := config.NewSSMStore(identity.New(defaultSession), ssm.New(defaultSession), aws.StringValue(defaultSession.Config.Region))\n\tenvDescriber, err := describe.NewEnvDescriber(describe.NewEnvDescriberConfig{\n\t\tApp: in.App.Name,\n\t\tEnv: in.Env.Name,\n\t\tConfigStore: store,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmft, err := envDescriber.Manifest()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read the manifest used to deploy environment %s: %w\", in.Env.Name, err)\n\t}\n\tenvConfig, err := manifest.UnmarshalEnvironment(mft)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal the manifest used to deploy environment %s: %w\", in.Env.Name, err)\n\t}\n\n\tcfn := cloudformation.New(envSession, cloudformation.WithProgressTracker(os.Stderr))\n\n\tlabeledTermPrinter := func(fw syncbuffer.FileWriter, bufs []*syncbuffer.LabeledSyncBuffer, opts ...syncbuffer.LabeledTermPrinterOption) LabeledTermPrinter {\n\t\treturn syncbuffer.NewLabeledTermPrinter(fw, bufs, opts...)\n\t}\n\tdocker := dockerengine.New(exec.NewCmd())\n\treturn &workloadDeployer{\n\t\tname: in.Name,\n\t\tapp: in.App,\n\t\tenv: in.Env,\n\t\timage: in.Image,\n\t\tresources: resources,\n\t\tworkspacePath: ws.Path(),\n\t\tfs: afero.NewOsFs(),\n\t\ts3Client: s3.New(envSession),\n\t\taddons: addons,\n\t\trepository: repository,\n\t\tdeployer: cfn,\n\t\ttmplGetter: cfn,\n\t\tendpointGetter: envDescriber,\n\t\tspinner: termprogress.NewSpinner(log.DiagnosticWriter),\n\t\ttemplateFS: template.New(),\n\t\tenvVersionGetter: in.EnvVersionGetter,\n\t\toverrider: in.Overrider,\n\t\tdocker: docker,\n\t\tcustomResources: in.customResources,\n\t\tdefaultSess: defaultSession,\n\t\tdefaultSessWithEnvRegion: defaultSessEnvRegion,\n\t\tenvSess: envSession,\n\t\tstore: store,\n\t\tenvConfig: envConfig,\n\t\tlabeledTermPrinter: labeledTermPrinter,\n\n\t\tmft: in.Mft,\n\t\trawMft: in.RawMft,\n\t}, nil\n}", "func (in *WorkloadSpec) DeepCopy() *WorkloadSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WorkloadSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func WorkloadNew(homeDirectory string, org string) {\n\n\t// Verify that env vars are set properly and determine the working directory.\n\tdir, err := VerifyEnvironment(homeDirectory, false, false, \"\")\n\tif err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, \"'%v %v' %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, err)\n\t}\n\n\tif org == \"\" && os.Getenv(DEVTOOL_HZN_ORG) == \"\" {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, \"'%v %v' must specify either --org or set the %v environment variable.\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, DEVTOOL_HZN_ORG)\n\t}\n\n\t// Create the working directory.\n\tif err := CreateWorkingDir(dir); err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, \"'%v %v' %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, err)\n\t}\n\n\t// If there are any horizon metadata files already in the directory then we wont create any files.\n\tcmd := fmt.Sprintf(\"%v %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND)\n\tFileNotExist(dir, cmd, USERINPUT_FILE, UserInputExists)\n\tFileNotExist(dir, cmd, WORKLOAD_DEFINITION_FILE, WorkloadDefinitionExists)\n\t//FileNotExist(dir, cmd, DEPENDENCIES_FILE, DependenciesExists)\n\n\tif org == \"\" {\n\t\torg = os.Getenv(DEVTOOL_HZN_ORG)\n\t}\n\n\t// Create the metadata files.\n\tif err := CreateUserInputs(dir, true, false, org); err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, \"'%v %v' %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, err)\n\t} else if err := CreateWorkloadDefinition(dir, org); err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, \"'%v %v' %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, err)\n\t}\n\t// } else if err := CreateDependencies(dir); err != nil {\n\t// \tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, \"'%v %v' %v\", WORKLOAD_COMMAND, WORKLOAD_CREATION_COMMAND, err)\n\t// }\n\n\tfmt.Printf(\"Created horizon metadata files in %v. Edit these files to define and configure your new %v.\\n\", dir, WORKLOAD_COMMAND)\n\n}", "func (helpers *framegraphInfoHelpers) newWorkloadInfo(renderpass *api.FramegraphRenderpass, compute *api.FramegraphCompute) {\n\tif helpers.wlInfo != nil {\n\t\tpanic(\"Creating a new workloadInfo while there is already one active\")\n\t}\n\thelpers.wlInfo = &workloadInfo{\n\t\tid: helpers.currWorkloadId,\n\t\trenderpass: renderpass,\n\t\tcompute: compute,\n\t\tnodes: []dependencygraph2.NodeID{},\n\t\tdeps: make(map[uint64]struct{}),\n\t\timageAccesses: make(map[uint64]*api.FramegraphImageAccess),\n\t\tbufferAccesses: make(map[uint64]*api.FramegraphBufferAccess),\n\t}\n\thelpers.currWorkloadId++\n}", "func (h *H) AddWorkload(name, project string) {\n\th.InstalledWorkloads[name] = project\n}", "func produceWorkloadInfo(opts string) (*pb.WorkloadInfo, error) {\n\tninputs := FlexVolumeInputs{}\n\terr := json.Unmarshal([]byte(opts), &ninputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twlInfo := pb.WorkloadInfo{\n\t\tAttrs: &pb.WorkloadInfo_WorkloadAttributes{\n\t\t\tUid: ninputs.UID,\n\t\t\tWorkload: ninputs.Name,\n\t\t\tNamespace: ninputs.Namespace,\n\t\t\tServiceaccount: ninputs.ServiceAccount,\n\t\t},\n\t\tWorkloadpath: ninputs.UID,\n\t}\n\treturn &wlInfo, nil\n}", "func createStartWorkload(vCpus int, memMB int, diskMB int) *payloads.Start {\n\tvar work payloads.Start\n\n\twork.Start.InstanceUUID = \"c73322e8-d5fe-4d57-874c-dcee4fd368cd\"\n\twork.Start.ImageUUID = \"b265f62b-e957-47fd-a0a2-6dc261c7315c\"\n\n\treqVcpus := payloads.RequestedResource{\n\t\tType: \"vcpus\",\n\t\tValue: vCpus,\n\t\tMandatory: true,\n\t}\n\treqMem := payloads.RequestedResource{\n\t\tType: \"mem_mb\",\n\t\tValue: memMB,\n\t\tMandatory: true,\n\t}\n\twork.Start.RequestedResources = append(work.Start.RequestedResources, reqVcpus)\n\twork.Start.RequestedResources = append(work.Start.RequestedResources, reqMem)\n\n\t//TODO: add EstimatedResources\n\n\twork.Start.FWType = payloads.EFI\n\twork.Start.InstancePersistence = payloads.Host\n\n\treturn &work\n}", "func NewWorkloadV1(conn *grpc.ClientConn, logger log.Logger) workload.ServiceWorkloadV1Client {\n\n\tvar lAbortMigrationEndpoint endpoint.Endpoint\n\t{\n\t\tlAbortMigrationEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AbortMigration\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAbortMigrationEndpoint = trace.ClientEndPoint(\"WorkloadV1:AbortMigration\")(lAbortMigrationEndpoint)\n\t}\n\tvar lAutoAddEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoAddEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoAddEndpoint\",\n\t\t\tworkload.EncodeGrpcReqEndpoint,\n\t\t\tworkload.DecodeGrpcRespEndpoint,\n\t\t\t&workload.Endpoint{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoAddEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoAddEndpoint\")(lAutoAddEndpointEndpoint)\n\t}\n\tvar lAutoAddWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoAddWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoAddWorkload\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoAddWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoAddWorkload\")(lAutoAddWorkloadEndpoint)\n\t}\n\tvar lAutoDeleteEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoDeleteEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoDeleteEndpoint\",\n\t\t\tworkload.EncodeGrpcReqEndpoint,\n\t\t\tworkload.DecodeGrpcRespEndpoint,\n\t\t\t&workload.Endpoint{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoDeleteEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoDeleteEndpoint\")(lAutoDeleteEndpointEndpoint)\n\t}\n\tvar lAutoDeleteWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoDeleteWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoDeleteWorkload\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoDeleteWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoDeleteWorkload\")(lAutoDeleteWorkloadEndpoint)\n\t}\n\tvar lAutoGetEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoGetEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoGetEndpoint\",\n\t\t\tworkload.EncodeGrpcReqEndpoint,\n\t\t\tworkload.DecodeGrpcRespEndpoint,\n\t\t\t&workload.Endpoint{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoGetEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoGetEndpoint\")(lAutoGetEndpointEndpoint)\n\t}\n\tvar lAutoGetWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoGetWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoGetWorkload\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoGetWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoGetWorkload\")(lAutoGetWorkloadEndpoint)\n\t}\n\tvar lAutoLabelEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoLabelEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoLabelEndpoint\",\n\t\t\tworkload.EncodeGrpcReqLabel,\n\t\t\tworkload.DecodeGrpcRespEndpoint,\n\t\t\t&workload.Endpoint{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoLabelEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoLabelEndpoint\")(lAutoLabelEndpointEndpoint)\n\t}\n\tvar lAutoLabelWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoLabelWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoLabelWorkload\",\n\t\t\tworkload.EncodeGrpcReqLabel,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoLabelWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoLabelWorkload\")(lAutoLabelWorkloadEndpoint)\n\t}\n\tvar lAutoListEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoListEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoListEndpoint\",\n\t\t\tworkload.EncodeGrpcReqListWatchOptions,\n\t\t\tworkload.DecodeGrpcRespEndpointList,\n\t\t\t&workload.EndpointList{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoListEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoListEndpoint\")(lAutoListEndpointEndpoint)\n\t}\n\tvar lAutoListWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoListWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoListWorkload\",\n\t\t\tworkload.EncodeGrpcReqListWatchOptions,\n\t\t\tworkload.DecodeGrpcRespWorkloadList,\n\t\t\t&workload.WorkloadList{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoListWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoListWorkload\")(lAutoListWorkloadEndpoint)\n\t}\n\tvar lAutoUpdateEndpointEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoUpdateEndpointEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoUpdateEndpoint\",\n\t\t\tworkload.EncodeGrpcReqEndpoint,\n\t\t\tworkload.DecodeGrpcRespEndpoint,\n\t\t\t&workload.Endpoint{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoUpdateEndpointEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoUpdateEndpoint\")(lAutoUpdateEndpointEndpoint)\n\t}\n\tvar lAutoUpdateWorkloadEndpoint endpoint.Endpoint\n\t{\n\t\tlAutoUpdateWorkloadEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"AutoUpdateWorkload\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlAutoUpdateWorkloadEndpoint = trace.ClientEndPoint(\"WorkloadV1:AutoUpdateWorkload\")(lAutoUpdateWorkloadEndpoint)\n\t}\n\tvar lFinalSyncMigrationEndpoint endpoint.Endpoint\n\t{\n\t\tlFinalSyncMigrationEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"FinalSyncMigration\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlFinalSyncMigrationEndpoint = trace.ClientEndPoint(\"WorkloadV1:FinalSyncMigration\")(lFinalSyncMigrationEndpoint)\n\t}\n\tvar lFinishMigrationEndpoint endpoint.Endpoint\n\t{\n\t\tlFinishMigrationEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"FinishMigration\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlFinishMigrationEndpoint = trace.ClientEndPoint(\"WorkloadV1:FinishMigration\")(lFinishMigrationEndpoint)\n\t}\n\tvar lStartMigrationEndpoint endpoint.Endpoint\n\t{\n\t\tlStartMigrationEndpoint = grpctransport.NewClient(\n\t\t\tconn,\n\t\t\t\"workload.WorkloadV1\",\n\t\t\t\"StartMigration\",\n\t\t\tworkload.EncodeGrpcReqWorkload,\n\t\t\tworkload.DecodeGrpcRespWorkload,\n\t\t\t&workload.Workload{},\n\t\t\tgrpctransport.ClientBefore(trace.ToGRPCRequest(logger)),\n\t\t\tgrpctransport.ClientBefore(dummyBefore),\n\t\t).Endpoint()\n\t\tlStartMigrationEndpoint = trace.ClientEndPoint(\"WorkloadV1:StartMigration\")(lStartMigrationEndpoint)\n\t}\n\treturn workload.EndpointsWorkloadV1Client{\n\t\tClient: workload.NewWorkloadV1Client(conn),\n\n\t\tAbortMigrationEndpoint: lAbortMigrationEndpoint,\n\t\tAutoAddEndpointEndpoint: lAutoAddEndpointEndpoint,\n\t\tAutoAddWorkloadEndpoint: lAutoAddWorkloadEndpoint,\n\t\tAutoDeleteEndpointEndpoint: lAutoDeleteEndpointEndpoint,\n\t\tAutoDeleteWorkloadEndpoint: lAutoDeleteWorkloadEndpoint,\n\t\tAutoGetEndpointEndpoint: lAutoGetEndpointEndpoint,\n\t\tAutoGetWorkloadEndpoint: lAutoGetWorkloadEndpoint,\n\t\tAutoLabelEndpointEndpoint: lAutoLabelEndpointEndpoint,\n\t\tAutoLabelWorkloadEndpoint: lAutoLabelWorkloadEndpoint,\n\t\tAutoListEndpointEndpoint: lAutoListEndpointEndpoint,\n\t\tAutoListWorkloadEndpoint: lAutoListWorkloadEndpoint,\n\t\tAutoUpdateEndpointEndpoint: lAutoUpdateEndpointEndpoint,\n\t\tAutoUpdateWorkloadEndpoint: lAutoUpdateWorkloadEndpoint,\n\t\tFinalSyncMigrationEndpoint: lFinalSyncMigrationEndpoint,\n\t\tFinishMigrationEndpoint: lFinishMigrationEndpoint,\n\t\tStartMigrationEndpoint: lStartMigrationEndpoint,\n\t}\n}", "func NewWorkbookOperation()(*WorkbookOperation) {\n m := &WorkbookOperation{\n Entity: *NewEntity(),\n }\n return m\n}", "func (conf *Config) ApplyWorkload(client *pilosa.Client, wl *workloadSpec) (err error) {\n\tif conf.Time {\n\t\tbefore := time.Now()\n\t\tfmt.Printf(\" beginning workload %s\\n\", wl.Name)\n\t\tdefer func() {\n\t\t\tafter := time.Now()\n\t\t\tvar completed = \"completed\"\n\t\t\tif err != nil {\n\t\t\t\tcompleted = \"failed\"\n\t\t\t}\n\t\t\tfmt.Printf(\" workload %s %s in %v\\n\", wl.Name, completed, after.Sub(before))\n\t\t}()\n\t}\n\terr = conf.ApplyTasks(client, wl.Tasks)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BoundServicesChange imports the currently bound services into the deployment. It takes a ServiceList, not just names, as it has to create/retrieve the associated service binding secrets. It further takes a set of the old services. This enables incremental modification of the deployment (add, remove affected, instead of wholsesale replacement).
func (a *Workload) BoundServicesChange(ctx context.Context, userName string, oldServices NameSet, newServices interfaces.ServiceList) error { app, err := Get(ctx, a.cluster, a.app) if err != nil { // Should not happen. Application was validated to exist // already somewhere by callers. return err } owner := metav1.OwnerReference{ APIVersion: app.GetAPIVersion(), Kind: app.GetKind(), Name: app.GetName(), UID: app.GetUID(), } bindings, err := ToBinds(ctx, newServices, a.app.Name, owner, userName) if err != nil { return err } // Create name-keyed maps from old/new slices for quick lookup and decision. No linear searches. new := map[string]struct{}{} for _, s := range newServices { new[s.Name()] = struct{}{} } // Read, modify and write the deployment return retry.RetryOnConflict(retry.DefaultRetry, func() error { // Retrieve the latest version of Deployment before attempting update // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver deployment, err := a.Deployment(ctx) if err != nil { return err } // The action is done in multiple iterations over the deployment's volumes and volumemounts. // The first iteration over each determines removed services (in old, not in new). The second // iteration, over the new services now, adds all which are not in old, i.e. actually new. newVolumes := []corev1.Volume{} newMounts := []corev1.VolumeMount{} for _, volume := range deployment.Spec.Template.Spec.Volumes { _, hasold := oldServices[volume.Name] _, hasnew := new[volume.Name] // Note that volumes which are not in old are passed and kept. These are the volumes // not related to services. if hasold && !hasnew { continue } newVolumes = append(newVolumes, volume) } // TODO: Iterate over containers and find the one matching the app name for _, mount := range deployment.Spec.Template.Spec.Containers[0].VolumeMounts { _, hasold := oldServices[mount.Name] _, hasnew := new[mount.Name] // Note that volumes which are in not in old are passed and kept. These are the volumes // not related to services. if hasold && !hasnew { continue } newMounts = append(newMounts, mount) } for _, binding := range bindings { // Skip services which already exist if _, hasold := oldServices[binding.service]; hasold { continue } newVolumes = append(newVolumes, corev1.Volume{ Name: binding.service, VolumeSource: corev1.VolumeSource{ Secret: &corev1.SecretVolumeSource{ SecretName: binding.resource, }, }, }) newMounts = append(newMounts, corev1.VolumeMount{ Name: binding.service, ReadOnly: true, MountPath: fmt.Sprintf("/services/%s", binding.service), }) } // Write the changed set of mounts and volumes back to the deployment ... deployment.Spec.Template.Spec.Volumes = newVolumes deployment.Spec.Template.Spec.Containers[0].VolumeMounts = newMounts // ... and then the cluster. _, err = a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Update( ctx, deployment, metav1.UpdateOptions{}) return err }) }
[ "func (p *pusher) ReconcileBindings(ctx context.Context, appName string, app *v1alpha1.App, opts ...PushOption) error {\n\tcfg := PushOptionDefaults().Extend(opts).toConfig()\n\tlogger := logging.FromContext(ctx)\n\n\tbindings := cfg.ServiceBindings\n\tlogger.Infof(\"Binding %d services to App...\", len(bindings))\n\n\t// Create service instance bindings\n\tfor _, desiredBinding := range bindings {\n\t\tlogger.Infof(\"Checking for binding to ServiceInstance named %q...\", desiredBinding.Spec.InstanceRef.Name)\n\t\t_, err := p.bindingsClient.Get(ctx, desiredBinding.GetNamespace(), desiredBinding.Name)\n\t\tswitch {\n\t\tcase apierrs.IsNotFound(err):\n\t\t\tlogger.Infof(\"Creating binding for ServiceInstance %q...\", desiredBinding.Spec.InstanceRef.Name)\n\n\t\t\tdesiredInstanceBindingOwnerReferences := []metav1.OwnerReference{\n\t\t\t\t*kmeta.NewControllerRef(app),\n\t\t\t}\n\n\t\t\tdesiredBinding.ObjectMeta.OwnerReferences = desiredInstanceBindingOwnerReferences\n\n\t\t\tnewBinding, err := p.bindingsClient.Create(ctx, desiredBinding.GetNamespace(), &desiredBinding)\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create ServiceInstanceBinding: %s\", err)\n\t\t\t}\n\n\t\t\t_, err = p.secretsClient.CreateParamsSecret(ctx, newBinding, newBinding.Spec.ParametersFrom.Name, json.RawMessage(\"{}\"))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create binding parameters secret: %s\", err)\n\t\t\t}\n\n\t\t\t// Wait for binding to become ready\n\t\t\tlogger.Info(\"Waiting for ServiceInstanceBinding to become ready\")\n\t\t\tif _, err = p.bindingsClient.WaitForConditionReadyTrue(\n\t\t\t\tcontext.Background(), newBinding.GetNamespace(), newBinding.Name, 1*time.Second); err != nil {\n\t\t\t\treturn fmt.Errorf(\"service binding failed: %s\", err)\n\t\t\t}\n\t\t\tlogger.Info(\"Success\")\n\t\tcase err != nil:\n\t\t\treturn fmt.Errorf(\"failed to get ServiceInstanceBinding %q: %s\", desiredBinding.Name, err)\n\t\tdefault:\n\t\t\tlogger.Infof(\"Binding to ServiceInstance %q already exists.\\n\", desiredBinding.Spec.InstanceRef.Name)\n\t\t}\n\t}\n\n\tlogger.Info(\"Finished binding services.\")\n\treturn nil\n}", "func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []string, replace bool) (bool, error) {\n\tif pip == nil {\n\t\treturn false, fmt.Errorf(\"nil public IP\")\n\t}\n\n\tif pip.Tags == nil {\n\t\tpip.Tags = map[string]*string{serviceTagKey: pointer.String(\"\")}\n\t}\n\n\tserviceTagValue := pip.Tags[serviceTagKey]\n\tserviceTagValueSet := make(map[string]struct{})\n\texistingServiceNames := parsePIPServiceTag(serviceTagValue)\n\taddedNew := false\n\n\t// replace is used when unbinding the service from PIP so addedNew remains false all the time\n\tif replace {\n\t\tserviceTagValue = pointer.String(strings.Join(incomingServiceNames, \",\"))\n\t\tpip.Tags[serviceTagKey] = serviceTagValue\n\n\t\treturn false, nil\n\t}\n\n\tfor _, name := range existingServiceNames {\n\t\tif _, ok := serviceTagValueSet[name]; !ok {\n\t\t\tserviceTagValueSet[name] = struct{}{}\n\t\t}\n\t}\n\n\tfor _, serviceName := range incomingServiceNames {\n\t\tif serviceTagValue == nil || *serviceTagValue == \"\" {\n\t\t\tserviceTagValue = pointer.String(serviceName)\n\t\t\taddedNew = true\n\t\t} else {\n\t\t\t// detect duplicates\n\t\t\tif _, ok := serviceTagValueSet[serviceName]; !ok {\n\t\t\t\t*serviceTagValue += fmt.Sprintf(\",%s\", serviceName)\n\t\t\t\taddedNew = true\n\t\t\t} else {\n\t\t\t\tklog.V(10).Infof(\"service %s has been bound to the pip already\", serviceName)\n\t\t\t}\n\t\t}\n\t}\n\tpip.Tags[serviceTagKey] = serviceTagValue\n\n\treturn addedNew, nil\n}", "func (l *LoadBalancerEmulator) PatchServices() ([]string, error) {\n\treturn l.applyOnLBServices(l.updateService)\n}", "func (lb *LoadBalancerRR) OnEndpointsUpdate(allEndpoints []api.Endpoints) {\n\tregisteredEndpoints := make(map[proxy.ServicePortName]bool)\n\tlb.lock.Lock()\n\tdefer lb.lock.Unlock()\n\n\t// Update endpoints for services.\n\tfor i := range allEndpoints {\n\t\tsvcEndpoints := &allEndpoints[i]\n\n\t\t// We need to build a map of portname -> all ip:ports for that\n\t\t// portname. Explode Endpoints.Subsets[*] into this structure.\n\t\tportsToEndpoints := map[string][]hostPortPair{}\n\t\tfor i := range svcEndpoints.Subsets {\n\t\t\tss := &svcEndpoints.Subsets[i]\n\t\t\tfor i := range ss.Ports {\n\t\t\t\tport := &ss.Ports[i]\n\t\t\t\tfor i := range ss.Addresses {\n\t\t\t\t\taddr := &ss.Addresses[i]\n\t\t\t\t\tportsToEndpoints[port.Name] = append(portsToEndpoints[port.Name], hostPortPair{addr.IP, port.Port})\n\t\t\t\t\t// Ignore the protocol field - we'll get that from the Service objects.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor portname := range portsToEndpoints {\n\t\t\tsvcPort := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: svcEndpoints.Namespace, Name: svcEndpoints.Name}, Port: portname}\n\t\t\tstate, exists := lb.services[svcPort]\n\t\t\tcurEndpoints := []string{}\n\t\t\tif state != nil {\n\t\t\t\tcurEndpoints = state.endpoints\n\t\t\t}\n\t\t\tnewEndpoints := flattenValidEndpoints(portsToEndpoints[portname])\n\n\t\t\tif !exists || state == nil || len(curEndpoints) != len(newEndpoints) || !slicesEquiv(slice.CopyStrings(curEndpoints), newEndpoints) {\n\t\t\t\tglog.V(1).Infof(\"LoadBalancerRR: Setting endpoints for %s to %+v\", svcPort, newEndpoints)\n\t\t\t\tlb.updateAffinityMap(svcPort, newEndpoints)\n\t\t\t\t// OnEndpointsUpdate can be called without NewService being called externally.\n\t\t\t\t// To be safe we will call it here. A new service will only be created\n\t\t\t\t// if one does not already exist. The affinity will be updated\n\t\t\t\t// later, once NewService is called.\n\t\t\t\tstate = lb.newServiceInternal(svcPort, api.ServiceAffinity(\"\"), 0)\n\t\t\t\tstate.endpoints = slice.ShuffleStrings(newEndpoints)\n\n\t\t\t\t// Reset the round-robin index.\n\t\t\t\tstate.index = 0\n\t\t\t}\n\t\t\tregisteredEndpoints[svcPort] = true\n\t\t}\n\t}\n\t// Remove endpoints missing from the update.\n\tfor k := range lb.services {\n\t\tif _, exists := registeredEndpoints[k]; !exists {\n\t\t\tglog.V(2).Infof(\"LoadBalancerRR: Removing endpoints for %s\", k)\n\t\t\tdelete(lb.services, k)\n\t\t}\n\t}\n}", "func (s *tprStorage) ListServiceBindings() ([]*scmodel.ServiceBinding, error) {\n\tl, err := s.watcher.GetResourceClient(watch.ServiceBinding, \"default\").List(&v1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*scmodel.ServiceBinding\n\tfor _, i := range l.(*runtime.UnstructuredList).Items {\n\t\tvar tmp scmodel.ServiceBinding\n\t\terr := util.TPRObjectToSCObject(i, &tmp)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to convert object: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, &tmp)\n\t}\n\treturn ret, nil\n}", "func (c *cfService) ServiceBindings() ServiceBindings {\n\treturn newServiceBindingAPI(c.Client)\n}", "func (c *Controller) Bind(w http.ResponseWriter, r *http.Request) {\n\n\tbindingID := utils.ExtractVarsFromRequest(r, \"service_binding_guid\")\n\tinstanceID := utils.ExtractVarsFromRequest(r, \"service_instance_guid\")\n\n\tutils.Logger.Printf(\"controller.Bind instanceID: %v, bindingID: %v\\n\", instanceID, bindingID)\n\tutils.Logger.Printf(\"controller.Bind REQUEST:\\n%s\\n\\n\", dumpRequest(r))\n\n\tinstance := c.instanceMap[instanceID]\n\tif instance == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tutils.Logger.Printf(\"controller.Bind instance: %v\\n\", instance)\n\n\tbinding := c.bindingMap[bindingID]\n\tresponse := model.CreateServiceBindingResponse{}\n\tif binding != nil {\n\t\t// then just return what was stored on the binding\n\t\tutils.Logger.Printf(\"controller.Bind: %v found in binding map\\n\", bindingID)\n\t\tresponse = model.CreateServiceBindingResponse{\n\t\t\tCredentials: binding.Credential,\n\t\t}\n\t} else {\n\t\tif instance != nil {\n\t\t\tresponse = model.CreateServiceBindingResponse{\n\t\t\t\tCredentials: instance.Credential,\n\t\t\t}\n\t\t\t// put into the binding table too...\n\t\t\tc.bindingMap[bindingID] = &model.ServiceBinding{\n\t\t\t\tID: bindingID,\n\t\t\t\tServiceID: instance.ServiceID,\n\t\t\t\tServicePlanID: instance.PlanID,\n\t\t\t\tServiceInstanceID: instance.ID,\n\t\t\t\tCredential: instance.Credential,\n\t\t\t\t// Credential: model.Credential{\n\t\t\t\t// URI: instance.Credential.URI,\n\t\t\t\t// UserName: instance.Credential.UserName,\n\t\t\t\t// Password: instance.Credential.Password,\n\t\t\t\t// SASLPassword: instance.Credential.SASLPassword,\n\t\t\t\t// BucketName: instance.Credential.BucketName,\n\t\t\t\t// },\n\t\t\t}\n\t\t\terr := utils.MarshalAndRecord(c.bindingMap, conf.DataPath, conf.ServiceBindingsFileName)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t} else {\n\t\t\tutils.Logger.Printf(\"controller.Bind: %v NOT found in binding map, checking instance %v\\n\", bindingID, instanceID)\n\n\t\t\tcredential, err := c.cloudClient.GetCredentials(instance.InternalID)\n\t\t\tif err != nil {\n\t\t\t\tutils.Logger.Printf(\"controller.Bind: error in GetCredentials: %v\\n\", err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresponse = model.CreateServiceBindingResponse{\n\t\t\t\tCredentials: *credential,\n\t\t\t}\n\n\t\t\tc.bindingMap[bindingID] = &model.ServiceBinding{\n\t\t\t\tID: bindingID,\n\t\t\t\tServiceID: instance.ServiceID,\n\t\t\t\tServicePlanID: instance.PlanID,\n\t\t\t\tServiceInstanceID: instance.ID,\n\t\t\t\tCredential: *credential,\n\t\t\t}\n\t\t\terr = utils.MarshalAndRecord(c.bindingMap, conf.DataPath, conf.ServiceBindingsFileName)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}\n\n\tutils.WriteResponse(w, http.StatusCreated, response)\n}", "func (c *Config) AppendServices(newServices []*services.ServiceConfig) error {\n\tlog.Printf(\"Appending %d services.\\n\", len(newServices))\n\tif c.ServiceMap == nil {\n\t\tc.ServiceMap = make(map[string]*services.ServiceConfig)\n\t}\n\tfor _, s := range newServices {\n\t\tif _, found := c.ServiceMap[s.Name]; !found {\n\t\t\tc.ServiceMap[s.Name] = s\n\t\t\tc.Services = append(c.Services, *s)\n\t\t}\n\t}\n\treturn nil\n}", "func updateServiceBindingRegion(\n\tdone chan interface{},\n\twg *sync.WaitGroup,\n\tregionEnv *RegionEnv,\n\tserviceBindingStream chan *RegionEnv,\n) {\n\tdefer wg.Done()\n\n\t// Cluster configmap must have the \"cloud\" key for service bindings to be created.\n\tcloud, ok := regionEnv.ClusterSettings[\"CLOUD\"]\n\tif !ok {\n\t\tlog.Error(\"Cannot create or update Service Bindings in %s, as the porter2k8s config map does not have a \" +\n\t\t\t\"'cloud' key\")\n\t\tserviceBindingStream <- regionEnv\n\t\treturn\n\t}\n\n\t// Catalog Service Bindings are not required.\n\tif len(regionEnv.ServiceBindings[cloud]) == 0 {\n\t\tserviceBindingStream <- regionEnv\n\t\treturn\n\t}\n\n\tvar updateErr, getErr, watchErr error\n\tvar serviceBindingSuccessful bool\n\tvar previousServiceBinding, serviceBindingUpdate *catalogv1beta1.ServiceBinding\n\t// Clientset is region specific.\n\tserviceBindingInterface := regionEnv.CatalogClientset.ServicecatalogV1beta1().ServiceBindings(\n\t\tregionEnv.Cfg.Namespace)\n\n\tfor _, serviceBinding := range regionEnv.ServiceBindings[cloud] {\n\n\t\tname := serviceBinding.ObjectMeta.Name\n\n\t\t// Check if serviceBinding already exists.\n\t\tpreviousServiceBinding, getErr = serviceBindingInterface.Get(name, metav1.GetOptions{})\n\n\t\t// Update podDisruptionBudget if required.\n\t\tif getErr == nil {\n\t\t\tif needsUpdate(previousServiceBinding, serviceBinding) {\n\t\t\t\t// Resource Version is required to be passed back unaltered.\n\t\t\t\tserviceBinding.ObjectMeta.ResourceVersion = previousServiceBinding.ObjectMeta.ResourceVersion\n\t\t\t\tserviceBindingUpdate, updateErr = serviceBindingInterface.Update(serviceBinding)\n\t\t\t}\n\t\t} else if errors.IsNotFound(getErr) {\n\t\t\tserviceBindingUpdate, updateErr = serviceBindingInterface.Create(serviceBinding)\n\t\t} else {\n\t\t\tregionEnv.Errors = append(regionEnv.Errors, fmt.Errorf(\"unable to get service binding %s\", getErr))\n\t\t\tserviceBindingStream <- regionEnv\n\t\t\treturn\n\t\t}\n\t\tif updateErr != nil {\n\t\t\tregionEnv.Errors = append(\n\t\t\t\tregionEnv.Errors,\n\t\t\t\tfmt.Errorf(\"unable to create/update service binding %s\\n%s\", name, updateErr),\n\t\t\t)\n\t\t\tserviceBindingStream <- regionEnv\n\t\t\treturn\n\t\t}\n\n\t\tif serviceBindingUpdate != nil {\n\t\t\tlog.Infof(\"Update: %+v\", serviceBindingUpdate)\n\t\t\tserviceBindingSuccessful, watchErr = regionEnv.watchServiceBinding(serviceBindingUpdate)\n\t\t} else {\n\t\t\t// Ensure existing service binding is healthy.\n\t\t\tserviceBindingSuccessful, watchErr = regionEnv.watchServiceBinding(serviceBinding)\n\t\t}\n\n\t\tif watchErr != nil {\n\t\t\tregionEnv.Errors = append(regionEnv.Errors, fmt.Errorf(\"service binding failure %s\", watchErr))\n\t\t} else if !serviceBindingSuccessful {\n\t\t\tregionEnv.Errors = append(regionEnv.Errors, fmt.Errorf(\"unknown service binding error\"))\n\t\t}\n\t}\n\tselect {\n\tcase <-done:\n\t\tlog.Info(\"Received Done\")\n\t\treturn\n\tcase serviceBindingStream <- regionEnv:\n\t}\n}", "func ImportServices(tclient TerraformClient) error {\n\tservices := GetConfig(\"services\")\n\tserviceList := services.([]interface{})\n\tfor _, val := range serviceList {\n\t\tservice := val.(map[interface{}]interface{})\n\t\terr := tclient.ImportService(service[\"id\"].(string), service[\"name\"].(string))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func AddServices(objects Objects, firstPortOnly bool) Objects {\n\tsvcs := []runtime.Object{}\n\tfor _, o := range objects {\n\t\tswitch t := o.(type) {\n\t\tcase *appsv1.DeploymentConfig:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Selector, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *kappsv1.Deployment:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *extensionsv1beta1.Deployment:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *kappsv1beta1.Deployment:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *kappsv1beta2.Deployment:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *kappsv1.DaemonSet:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *extensionsv1beta1.DaemonSet:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\tcase *kappsv1beta2.DaemonSet:\n\t\t\tsvc := addService(t.Spec.Template.Spec.Containers, t.ObjectMeta, t.Spec.Template.Labels, firstPortOnly)\n\t\t\tif svc != nil {\n\t\t\t\tsvcs = append(svcs, svc)\n\t\t\t}\n\t\t}\n\t}\n\treturn append(objects, svcs...)\n}", "func (r *TrafficOpsReq) StartServices(syncdsUpdate *UpdateStatus, metaData *t3cutil.ApplyMetaData, cfg config.Cfg) error {\n\tserviceNeeds := t3cutil.ServiceNeedsNothing\n\tif r.Cfg.ServiceAction == t3cutil.ApplyServiceActionFlagRestart {\n\t\tserviceNeeds = t3cutil.ServiceNeedsRestart\n\t} else {\n\t\terr := error(nil)\n\t\tif serviceNeeds, err = checkReload(r.changedFiles); err != nil {\n\t\t\treturn errors.New(\"determining if service needs restarted - not reloading or restarting! : \" + err.Error())\n\t\t}\n\t}\n\n\tlog.Infof(\"t3c-check-reload returned '%+v'\\n\", serviceNeeds)\n\n\t// We have our own internal knowledge of files that have been modified as well\n\t// If check-reload does not know about these and we do, then we should initiate\n\t// a reload as well\n\tif serviceNeeds != t3cutil.ServiceNeedsRestart && serviceNeeds != t3cutil.ServiceNeedsReload {\n\t\tif r.TrafficCtlReload || r.RemapConfigReload {\n\t\t\tlog.Infof(\"ATS config files unchanged, we updated files via t3c-apply, ATS needs reload\")\n\t\t\tserviceNeeds = t3cutil.ServiceNeedsReload\n\t\t}\n\t}\n\tpackageName := \"trafficserver\"\n\tif cfg.CacheType == \"varnish\" {\n\t\tpackageName = \"varnish\"\n\t}\n\n\tif (serviceNeeds == t3cutil.ServiceNeedsRestart || serviceNeeds == t3cutil.ServiceNeedsReload) && !r.IsPackageInstalled(packageName) {\n\t\t// TODO try to reload/restart anyway? To allow non-RPM installs?\n\t\treturn errors.New(packageName + \" needs \" + serviceNeeds.String() + \" but is not installed.\")\n\t}\n\n\tsvcStatus, _, err := util.GetServiceStatus(packageName)\n\tif err != nil {\n\t\treturn errors.New(\"getting trafficserver service status: \" + err.Error())\n\t}\n\n\tif r.Cfg.ReportOnly {\n\t\tif serviceNeeds == t3cutil.ServiceNeedsRestart {\n\t\t\tlog.Errorln(\"ATS configuration has changed. The new config will be picked up the next time ATS is started.\")\n\t\t} else if serviceNeeds == t3cutil.ServiceNeedsReload {\n\t\t\tlog.Errorln(\"ATS configuration has changed. 'traffic_ctl config reload' needs to be run\")\n\t\t}\n\t\treturn nil\n\t} else if r.Cfg.ServiceAction == t3cutil.ApplyServiceActionFlagRestart {\n\t\tstartStr := \"restart\"\n\t\tif svcStatus != util.SvcRunning {\n\t\t\tstartStr = \"start\"\n\t\t}\n\t\tif _, err := util.ServiceStart(packageName, startStr); err != nil {\n\t\t\tt3cutil.WriteActionLog(t3cutil.ActionLogActionATSRestart, t3cutil.ActionLogStatusFailure, metaData)\n\t\t\treturn errors.New(\"failed to restart trafficserver\")\n\t\t}\n\t\tt3cutil.WriteActionLog(t3cutil.ActionLogActionATSRestart, t3cutil.ActionLogStatusSuccess, metaData)\n\t\tlog.Infoln(\"trafficserver has been \" + startStr + \"ed\")\n\n\t\tif !r.Cfg.NoConfirmServiceAction {\n\t\t\tlog.Infoln(\"confirming ATS restart succeeded\")\n\t\t\tif err := doTail(r.Cfg, TailDiagsLogRelative, \".*\", tailRestartEnd, TailRestartTimeOutMS); err != nil {\n\t\t\t\tlog.Errorln(\"error running tail\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Infoln(\"skipping ATS restart success confirmation\")\n\t\t}\n\t\tif *syncdsUpdate == UpdateTropsNeeded {\n\t\t\t*syncdsUpdate = UpdateTropsSuccessful\n\t\t}\n\t\treturn nil // we restarted, so no need to reload\n\t} else if r.Cfg.ServiceAction == t3cutil.ApplyServiceActionFlagReload {\n\t\tif serviceNeeds == t3cutil.ServiceNeedsRestart {\n\t\t\tif *syncdsUpdate == UpdateTropsNeeded {\n\t\t\t\t*syncdsUpdate = UpdateTropsSuccessful\n\t\t\t}\n\t\t\tlog.Errorln(\"ATS configuration has changed. The new config will be picked up the next time ATS is started.\")\n\t\t} else if serviceNeeds == t3cutil.ServiceNeedsReload {\n\t\t\tlog.Infoln(\"ATS configuration has changed, Running 'traffic_ctl config reload' now.\")\n\t\t\treloadCommand := config.TSHome + config.TrafficCtl\n\t\t\treloadArgs := []string{\"config\", \"reload\"}\n\t\t\tif cfg.CacheType == \"varnish\" {\n\t\t\t\treloadCommand = \"varnishreload\"\n\t\t\t\treloadArgs = []string{}\n\t\t\t}\n\t\t\tif _, _, err := util.ExecCommand(reloadCommand, reloadArgs...); err != nil {\n\t\t\t\tt3cutil.WriteActionLog(t3cutil.ActionLogActionATSReload, t3cutil.ActionLogStatusFailure, metaData)\n\n\t\t\t\tif *syncdsUpdate == UpdateTropsNeeded {\n\t\t\t\t\t*syncdsUpdate = UpdateTropsFailed\n\t\t\t\t}\n\t\t\t\treturn errors.New(\"ATS configuration has changed and 'traffic_ctl config reload' failed, check ATS logs: \" + err.Error())\n\t\t\t}\n\t\t\tt3cutil.WriteActionLog(t3cutil.ActionLogActionATSReload, t3cutil.ActionLogStatusSuccess, metaData)\n\n\t\t\tif *syncdsUpdate == UpdateTropsNeeded {\n\t\t\t\t*syncdsUpdate = UpdateTropsSuccessful\n\t\t\t}\n\t\t\tlog.Infoln(\"ATS 'traffic_ctl config reload' was successful\")\n\n\t\t\tif !r.Cfg.NoConfirmServiceAction {\n\t\t\t\tlog.Infoln(\"confirming ATS reload succeeded\")\n\t\t\t\tif err := doTail(r.Cfg, TailDiagsLogRelative, tailMatch, tailReloadEnd, TailReloadTimeOutMS); err != nil {\n\t\t\t\t\tlog.Errorln(\"error running tail: \", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Infoln(\"skipping ATS reload success confirmation\")\n\t\t\t}\n\t\t}\n\t\tif *syncdsUpdate == UpdateTropsNeeded {\n\t\t\t*syncdsUpdate = UpdateTropsSuccessful\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func ServiceInjector(ctx context.Context, w oam.Workload, objs []oam.Object) ([]oam.Object, error) {\n\tif objs == nil {\n\t\treturn nil, nil\n\t}\n\n\tfor _, o := range objs {\n\t\td, ok := o.(*appsv1.Deployment)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We don't add a Service if there are no containers for the Deployment.\n\t\t// This should never happen in practice.\n\t\tif len(d.Spec.Template.Spec.Containers) < 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\ts := &corev1.Service{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: serviceKind,\n\t\t\t\tAPIVersion: serviceAPIVersion,\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: d.GetName(),\n\t\t\t\tNamespace: d.GetNamespace(),\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tLabelKey: string(w.GetUID()),\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tSelector: d.Spec.Selector.MatchLabels,\n\t\t\t\tPorts: []corev1.ServicePort{},\n\t\t\t\tType: corev1.ServiceTypeLoadBalancer,\n\t\t\t},\n\t\t}\n\n\t\t// We only add a single Service for the Deployment, even if multiple\n\t\t// ports or no ports are defined on the first container. This is to\n\t\t// exclude the need for implementing garbage collection in the\n\t\t// short-term in the case that ports are modified after creation.\n\t\tif len(d.Spec.Template.Spec.Containers[0].Ports) > 0 {\n\t\t\ts.Spec.Ports = []corev1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName: d.GetName(),\n\t\t\t\t\tPort: d.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(int(d.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort)),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tobjs = append(objs, s)\n\t\tbreak\n\t}\n\treturn objs, nil\n}", "func PushServices(client kclient.ClientInterface, k8sComponents []devfile.Component, labels map[string]string, context string) error {\n\n\t// check csv support before proceeding\n\tcsvSupported, err := IsCSVSupported()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdeployed, err := ListDeployedServices(client, labels)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor key, deployedResource := range deployed {\n\t\tif deployedResource.isLinkResource {\n\t\t\tdelete(deployed, key)\n\t\t}\n\t}\n\n\tmadeChange := false\n\n\t// create an object on the kubernetes cluster for all the Kubernetes Inlined components\n\tfor _, c := range k8sComponents {\n\t\tinlined := c.Kubernetes.Inlined\n\t\tif c.Kubernetes.Uri != \"\" {\n\t\t\tinlined, err = getDataFromURI(c.Kubernetes.Uri, context, devfilefs.DefaultFs{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// get the string representation of the YAML definition of a CRD\n\t\tstrCRD := inlined\n\n\t\t// convert the YAML definition into map[string]interface{} since it's needed to create dynamic resource\n\t\td := NewDynamicCRD()\n\t\terr := yaml.Unmarshal([]byte(strCRD), &d.OriginalCRD)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !csvSupported || (isLinkResource(d.OriginalCRD[\"kind\"].(string))) {\n\t\t\t// operator hub is not installed on the cluster\n\t\t\t// or it's a service binding related resource\n\t\t\tcontinue\n\t\t}\n\n\t\tcrdName, ok := getCRDName(d.OriginalCRD)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tcr, kind, err := createOperatorService(client, d, labels, []metav1.OwnerReference{})\n\t\tdelete(deployed, cr+\"/\"+crdName)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"already exists\") {\n\t\t\t\t// this could be the case when \"odo push\" was executed after making change to code but there was no change to the service itself\n\t\t\t\t// TODO: better way to handle this might be introduced by https://github.com/openshift/odo/issues/4553\n\t\t\t\tcontinue // this ensures that services slice is not updated\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tname, _ := d.GetServiceNameFromCRD() // ignoring error because invalid yaml won't be inserted into devfile through odo\n\t\tlog.Successf(\"Created service %q on the cluster; refer %q to know how to link it to the component\", strings.Join([]string{kind, name}, \"/\"), \"odo link -h\")\n\t\tmadeChange = true\n\t}\n\n\tfor key, val := range deployed {\n\t\tif !csvSupported || (isLinkResource(val.Kind)) {\n\t\t\tcontinue\n\t\t}\n\t\terr = DeleteOperatorService(client, key)\n\t\tif err != nil {\n\t\t\treturn err\n\n\t\t}\n\n\t\tlog.Successf(\"Deleted service %q from the cluster\", key)\n\t\tmadeChange = true\n\t}\n\n\tif !madeChange {\n\t\tlog.Success(\"Services are in sync with the cluster, no changes are required\")\n\t}\n\n\treturn nil\n}", "func pushServices(ch services.ServicesChannel, definitions []Definition, adding bool) {\n\t// Iterate and convert the backend definitions into services\n\tfor _, definition := range definitions {\n\t\t// Attempt to convert the definition to a service request\n\t\tservice, err := definition.GetService()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to convert the definition: %s to a service, error: %s\", definition, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar event services.ServiceEvent\n\t\tevent.Service = service\n\t\tevent.Action = services.SERVICE_REMOVAL\n\t\tif adding {\n\t\t\tevent.Action = services.SERVICE_REQUEST\n\t\t}\n\n\t\t// We perform this in a go-routine not to allow a receiver from blocking us\n\t\tgo func() {\n\t\t\tch <- event\n\t\t}()\n\t}\n}", "func (l *loadBalancers) reconcileServices(ctx context.Context, svcs []*v1.Service, mode UpdateMode) error {\n\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): %v starting\", mode)\n\tklog.V(5).Infof(\"loadbalancer.reconcileServices(): services %#v\", svcs)\n\n\tvar err error\n\t// get IP address reservations and check if they any exists for this svc\n\tips, _, err := l.client.ProjectIPs.List(l.project, &packngo.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to retrieve IP reservations for project %s: %v\", l.project, err)\n\t}\n\n\tvalidSvcs := []*v1.Service{}\n\tfor _, svc := range svcs {\n\t\t// filter on type: only take those that are of type=LoadBalancer\n\t\tif svc.Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\t\tcontinue\n\t\t}\n\t\t// filter on name: do not try to manage the the service we created for EIP load balancer\n\t\tif svc.ObjectMeta.Name == externalServiceName && svc.ObjectMeta.Namespace == externalServiceNamespace {\n\t\t\tcontinue\n\t\t}\n\t\tvalidSvcs = append(validSvcs, svc)\n\t}\n\tklog.V(5).Infof(\"loadbalancer.reconcileServices(): valid services %#v\", validSvcs)\n\n\tswitch mode {\n\tcase ModeAdd:\n\t\t// ADDITION\n\t\tfor _, svc := range validSvcs {\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): add: service %s\", svc.Name)\n\t\t\tif err := l.addService(ctx, svc, ips); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase ModeRemove:\n\t\t// REMOVAL\n\t\tfor _, svc := range validSvcs {\n\t\t\tsvcName := serviceRep(svc)\n\t\t\tsvcTag := serviceTag(svc)\n\t\t\tclsTag := clusterTag(l.clusterID)\n\t\t\tsvcIP := svc.Spec.LoadBalancerIP\n\n\t\t\tvar svcIPCidr string\n\t\t\tipReservation := ipReservationByAllTags([]string{svcTag, emTag, clsTag}, ips)\n\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): remove: %s with existing IP assignment %s\", svcName, svcIP)\n\n\t\t\t// get the IPs and see if there is anything to clean up\n\t\t\tif ipReservation == nil {\n\t\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): remove: no IP reservation found for %s, nothing to delete\", svcName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// delete the reservation\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): remove: for %s EIP ID %s\", svcName, ipReservation.ID)\n\t\t\t_, err = l.client.ProjectIPs.Remove(ipReservation.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to remove IP address reservation %s from project: %v\", ipReservation.String(), err)\n\t\t\t}\n\t\t\t// remove it from the configmap\n\t\t\tsvcIPCidr = fmt.Sprintf(\"%s/%d\", ipReservation.Address, ipReservation.CIDR)\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): remove: for %s entry %s\", svcName, svcIPCidr)\n\t\t\tif err := l.implementor.RemoveService(ctx, svcIPCidr); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error removing IP from configmap for %s: %v\", svcName, err)\n\t\t\t}\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): remove: removed service %s from implementation\", svcName)\n\t\t}\n\tcase ModeSync:\n\t\t// what we have to do:\n\t\t// 1. get all of the services that are of type=LoadBalancer\n\t\t// 2. for each service, get its eip, if available. if it does not have one, create one for it.\n\t\t// 3. for each EIP, ensure it exists in the configmap\n\t\t// 4. get each EIP in the configmap, check if it is in our list; if not, delete\n\n\t\t// add each service that is in the known list\n\t\tfor _, svc := range validSvcs {\n\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): sync: service %s\", svc.Name)\n\t\t\tif err := l.addService(ctx, svc, ips); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// remove any service that is not in the known list\n\n\t\t// we need to get the addresses again, because we might have changed them\n\t\tklog.V(5).Info(\"loadbalancer.reconcileServices(): sync: getting all IP reservations\")\n\t\tips, _, err = l.client.ProjectIPs.List(l.project, &packngo.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve IP reservations for project %s: %v\", l.project, err)\n\t\t}\n\t\t// get all EIP that have the equinix metal tag and are allocated to this cluster\n\t\tipReservations := ipReservationsByAllTags([]string{emTag, clusterTag(l.clusterID)}, ips)\n\t\t// create a map of EIP to svcIP so we can get the CIDR\n\t\tipCidr := map[string]int{}\n\t\tfor _, ipr := range ipReservations {\n\t\t\tipCidr[ipr.Address] = ipr.CIDR\n\t\t}\n\n\t\t// create a map of all valid IPs\n\t\tvalidTags := map[string]bool{}\n\t\tvalidIPs := map[string]bool{}\n\n\t\tfor _, svc := range validSvcs {\n\t\t\tvalidTags[serviceTag(svc)] = true\n\t\t\tsvcIP := svc.Spec.LoadBalancerIP\n\t\t\tif svcIP != \"\" {\n\t\t\t\tif cidr, ok := ipCidr[svcIP]; ok {\n\t\t\t\t\tvalidIPs[fmt.Sprintf(\"%s/%d\", svcIP, cidr)] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): sync: valid tags %v\", validTags)\n\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): sync: valid svc IPs %v\", validIPs)\n\n\t\tif err := l.implementor.SyncServices(ctx, validIPs); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// remove any EIPs that do not have a reservation\n\n\t\tklog.V(5).Infof(\"loadbalancer.reconcileServices(): sync: all reservations with emTag %#v\", ipReservations)\n\t\tfor _, ipReservation := range ipReservations {\n\t\t\tvar foundTag bool\n\t\t\tfor _, tag := range ipReservation.Tags {\n\t\t\t\tif _, ok := validTags[tag]; ok {\n\t\t\t\t\tfoundTag = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// did we find a valid tag?\n\t\t\tif !foundTag {\n\t\t\t\tklog.V(2).Infof(\"loadbalancer.reconcileServices(): sync: removing reservation with service= tag but not in validTags list %#v\", ipReservation)\n\t\t\t\t// delete the reservation\n\t\t\t\t_, err = l.client.ProjectIPs.Remove(ipReservation.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to remove IP address reservation %s from project: %v\", ipReservation.String(), err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func WithServices[T any](ctx context.Context, gw bkgw.Client, svcs ServiceBindings, fn func() (T, error)) (T, error) {\n\tvar zero T\n\n\t// NB: don't use errgroup.WithCancel; we don't want to cancel on Wait\n\teg := new(errgroup.Group)\n\tstarted := make(chan *Service, len(svcs))\n\n\tfor svcID, aliases := range svcs {\n\t\tsvc, err := svcID.ToContainer()\n\t\tif err != nil {\n\t\t\treturn zero, err\n\t\t}\n\n\t\thost, err := svc.HostnameOrErr()\n\t\tif err != nil {\n\t\t\treturn zero, err\n\t\t}\n\n\t\taliases := aliases\n\t\teg.Go(func() error {\n\t\t\tsvc, err := svc.Start(ctx, gw)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"start %s (%s): %w\", host, aliases, err)\n\t\t\t}\n\t\t\tstarted <- svc\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tstartErr := eg.Wait()\n\n\tclose(started)\n\n\tdefer func() {\n\t\tgo func() {\n\t\t\t<-time.After(10 * time.Second)\n\n\t\t\tfor svc := range started {\n\t\t\t\tsvc.Detach()\n\t\t\t}\n\t\t}()\n\t}()\n\n\t// wait for all services to start\n\tif startErr != nil {\n\t\treturn zero, startErr\n\t}\n\n\treturn fn()\n}", "func (c *backingservices) List(opts kapi.ListOptions) (result *backingserviceapi.BackingServiceList, err error) {\n\tresult = &backingserviceapi.BackingServiceList{}\n\terr = c.r.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"backingservices\").\n\t\tVersionedParams(&opts, kapi.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (h *ServiceHandlers) ImportServicesHandler(ctx *gin.Context) {\n\tvar req kubtypes.ServicesList\n\tif err := ctx.ShouldBindWith(&req, binding.JSON); err != nil {\n\t\tctx.AbortWithStatusJSON(h.BadRequest(ctx, err))\n\t\treturn\n\t}\n\n\tresp := kubtypes.ImportResponse{\n\t\tImported: []kubtypes.ImportResult{},\n\t\tFailed: []kubtypes.ImportResult{},\n\t}\n\n\tfor _, svc := range req.Services {\n\t\tif err := h.ImportService(ctx.Request.Context(), svc.Namespace, svc); err != nil {\n\t\t\tlogrus.Warn(err)\n\t\t\tresp.ImportFailed(svc.Name, svc.Namespace, err.Error())\n\t\t} else {\n\t\t\tresp.ImportSuccessful(svc.Name, svc.Namespace)\n\t\t}\n\t}\n\n\tctx.JSON(http.StatusAccepted, resp)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EnvironmentChange imports the current environment into the deployment. This requires only the names of the currently existing environment variables, not the values, as the import is internally done as pod env specifications using secret key references.
func (a *Workload) EnvironmentChange(ctx context.Context, varNames []string) error { return retry.RetryOnConflict(retry.DefaultRetry, func() error { // Retrieve the latest version of Deployment before attempting update // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver deployment, err := a.Deployment(ctx) if err != nil { return err } evSecretName := a.app.MakeEnvSecretName() // 1. Remove all the old EVs referencing the app's EV secret. // 2. Add entries for the new set of EV's (S.a varNames). // 3. Replace container spec // // Note: While 1+2 could be optimized to only remove entries of // EVs not in varNames, and add only entries for varNames // not in Env, this is way more complex for what is likely // just 10 entries. I expect any gain in perf to be // negligible, and completely offset by the complexity of // understanding and maintaining it later. Full removal // and re-adding is much simpler to understand, and should // be fast enough. newEnvironment := []corev1.EnvVar{} for _, ev := range deployment.Spec.Template.Spec.Containers[0].Env { // Drop EV if pulled from EV secret of the app if ev.ValueFrom != nil && ev.ValueFrom.SecretKeyRef != nil && ev.ValueFrom.SecretKeyRef.Name == evSecretName { continue } // Keep everything else. newEnvironment = append(newEnvironment, ev) } for _, varName := range varNames { newEnvironment = append(newEnvironment, corev1.EnvVar{ Name: varName, ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ LocalObjectReference: corev1.LocalObjectReference{ Name: evSecretName, }, Key: varName, }, }, }) } deployment.Spec.Template.Spec.Containers[0].Env = newEnvironment _, err = a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Update( ctx, deployment, metav1.UpdateOptions{}) return err }) }
[ "func LoadEnvOf(svc *heroku.Service, appID string) (err error) {\n\tcfg, err := svc.ConfigVarInfoForApp(context.Background(), appID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor k, v := range cfg {\n\t\tos.Setenv(k, *v)\n\t}\n\n\treturn\n}", "func RenameEnvironment(host string, verifyTLS bool, apiKey string, project string, environment string, name string, slug string) (models.EnvironmentInfo, Error) {\n\tpostBody := map[string]string{\"project\": project, \"environment\": environment}\n\tif name != \"\" {\n\t\tpostBody[\"name\"] = name\n\t}\n\tif slug != \"\" {\n\t\tpostBody[\"slug\"] = slug\n\t}\n\tbody, err := json.Marshal(postBody)\n\tif err != nil {\n\t\treturn models.EnvironmentInfo{}, Error{Err: err, Message: \"Invalid environment info\"}\n\t}\n\n\turl, err := generateURL(host, \"/v3/environments/environment\", nil)\n\tif err != nil {\n\t\treturn models.EnvironmentInfo{}, Error{Err: err, Message: \"Unable to generate url\"}\n\t}\n\n\tstatusCode, _, response, err := PutRequest(url, verifyTLS, apiKeyHeader(apiKey), body)\n\tif err != nil {\n\t\treturn models.EnvironmentInfo{}, Error{Err: err, Message: \"Unable to rename environment\", Code: statusCode}\n\t}\n\n\tvar result map[string]interface{}\n\terr = json.Unmarshal(response, &result)\n\tif err != nil {\n\t\treturn models.EnvironmentInfo{}, Error{Err: err, Message: \"Unable to parse API response\", Code: statusCode}\n\t}\n\n\tenvironmentInfo, ok := result[\"environment\"].(map[string]interface{})\n\tif !ok {\n\t\treturn models.EnvironmentInfo{}, Error{Err: fmt.Errorf(\"Unexpected type parsing environment, expected map[string]interface{}, got %T\", result[\"environment\"]), Message: \"Unable to parse API response\", Code: statusCode}\n\t}\n\n\tinfo := models.ParseEnvironmentInfo(environmentInfo)\n\treturn info, Error{}\n}", "func (cluster *Cluster) LoadEnvironment(namespace string) (*bitesize.Environment, error) {\n\tserviceMap := make(ServiceMap)\n\n\tclient := &k8s.Client{\n\t\tNamespace: namespace,\n\t\tInterface: cluster.Interface,\n\t\tTPRClient: cluster.TPRClient,\n\t}\n\n\tns, err := client.Ns().Get()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Namespace %s not found\", namespace)\n\t}\n\tenvironmentName := ns.ObjectMeta.Labels[\"environment\"]\n\n\tservices, err := client.Service().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes services: %s\", err.Error())\n\t}\n\tfor _, service := range services {\n\t\tserviceMap.AddService(service)\n\t}\n\n\tdeployments, err := client.Deployment().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes deployments: %s\", err.Error())\n\t}\n\tfor _, deployment := range deployments {\n\t\tserviceMap.AddDeployment(deployment)\n\t}\n\n\thpas, err := client.HorizontalPodAutoscaler().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes hpas: %s\", err.Error())\n\t}\n\tfor _, hpa := range hpas {\n\t\tserviceMap.AddHPA(hpa)\n\t}\n\n\tingresses, err := client.Ingress().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes ingresses: %s\", err.Error())\n\t}\n\n\tfor _, ingress := range ingresses {\n\t\tserviceMap.AddIngress(ingress)\n\t}\n\n\tstatefulsets, err := client.StatefulSet().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes statefulsets : %s\", err.Error())\n\t}\n\n\tfor _, statefulset := range statefulsets {\n\t\tserviceMap.AddMongoStatefulSet(statefulset)\n\t}\n\n\t// we'll need the same for tprs\n\tclaims, _ := client.PVC().List()\n\tfor _, claim := range claims {\n\t\tserviceMap.AddVolumeClaim(claim)\n\t}\n\n\tfor _, supported := range k8_extensions.SupportedThirdPartyResources {\n\t\ttprs, _ := client.ThirdPartyResource(supported).List()\n\t\tfor _, tpr := range tprs {\n\t\t\tserviceMap.AddThirdPartyResource(tpr)\n\t\t}\n\t}\n\n\tbitesizeConfig := bitesize.Environment{\n\t\tName: environmentName,\n\t\tNamespace: namespace,\n\t\tServices: serviceMap.Services(),\n\t}\n\n\treturn &bitesizeConfig, nil\n}", "func (hc ApplicationsController) EnvSet(w http.ResponseWriter, r *http.Request) APIErrors {\n\tctx := r.Context()\n\tlog := tracelog.Logger(ctx)\n\n\tparams := httprouter.ParamsFromContext(ctx)\n\torgName := params.ByName(\"org\")\n\tappName := params.ByName(\"app\")\n\n\tlog.Info(\"processing environment variable assignment\",\n\t\t\"org\", orgName, \"app\", appName)\n\n\tcluster, err := kubernetes.GetCluster(ctx)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\texists, err := organizations.Exists(ctx, cluster, orgName)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn OrgIsNotKnown(orgName)\n\t}\n\n\tapp := models.NewAppRef(appName, orgName)\n\n\texists, err = application.Exists(ctx, cluster, app)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn AppIsNotKnown(appName)\n\t}\n\n\tdefer r.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tvar setRequest models.EnvVariableList\n\terr = json.Unmarshal(bodyBytes, &setRequest)\n\tif err != nil {\n\t\treturn BadRequest(err)\n\t}\n\n\terr = application.EnvironmentSet(ctx, cluster, app, setRequest)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\treturn nil\n}", "func (e *Environment) Augment(base environ.Env) {\n\texportIf := func(envKey, v string) {\n\t\tif v != \"\" {\n\t\t\tbase.Set(envKey, v)\n\t\t}\n\t}\n\n\texportIf(bootstrap.EnvCoordinatorHost, e.CoordinatorHost)\n\texportIf(bootstrap.EnvStreamPrefix, string(e.Prefix))\n\texportIf(bootstrap.EnvStreamProject, string(e.Project))\n\texportIf(bootstrap.EnvStreamServerPath, e.StreamServerURI)\n}", "func replaceEnv(cmd *exec.Cmd, key, value string) {\n\tif cmd.Env == nil {\n\t\tcmd.Env = os.Environ()\n\t}\n\tcmd.Env = append(cmd.Env, key+\"=\"+value)\n}", "func GetENV(experimentDetails *experimentTypes.ExperimentDetails) {\n\texperimentDetails.ExperimentName = Getenv(\"EXPERIMENT_NAME\", \"\")\n\texperimentDetails.AppNS = Getenv(\"APP_NS\", \"\")\n\texperimentDetails.TargetContainer = Getenv(\"APP_CONTAINER\", \"\")\n\texperimentDetails.TargetPods = Getenv(\"APP_POD\", \"\")\n\texperimentDetails.AppLabel = Getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.ChaosDuration, _ = strconv.Atoi(Getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosNamespace = Getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = Getenv(\"CHAOS_ENGINE\", \"\")\n\texperimentDetails.ChaosUID = clientTypes.UID(Getenv(\"CHAOS_UID\", \"\"))\n\texperimentDetails.ChaosPodName = Getenv(\"POD_NAME\", \"\")\n\texperimentDetails.ContainerRuntime = Getenv(\"CONTAINER_RUNTIME\", \"\")\n\texperimentDetails.NetworkInterface = Getenv(\"NETWORK_INTERFACE\", \"eth0\")\n\texperimentDetails.TargetIPs = Getenv(\"TARGET_IPs\", \"\")\n}", "func (c *Client) UpdateEnv(name, value string, encrypt, remove bool) (*http.Response, error) {\n\treturn c.post(\"/env\", common.EnvRequest{\n\t\tName: name, Value: value, Encrypt: encrypt, Remove: remove,\n\t})\n}", "func UpdateEnvVars(template *servingv1alpha1.RevisionTemplateSpec, toUpdate map[string]string, toRemove []string) error {\n\tcontainer, err := ContainerOfRevisionTemplate(template)\n\tif err != nil {\n\t\treturn err\n\t}\n\tupdated := updateEnvVarsFromMap(container.Env, toUpdate)\n\tupdated = removeEnvVars(updated, toRemove)\n\t// Sort by env key name\n\tsort.SliceStable(updated, func(i, j int) bool {\n\t\treturn updated[i].Name < updated[j].Name\n\t})\n\tcontainer.Env = updated\n\n\treturn nil\n}", "func UpdateEnv(r *client.ReleaseResource, containerName string, name string, value string) error {\n\n\tfault := false\n\tfor ci, container := range r.Containers {\n\t\tif container.Name == containerName {\n\t\t\tif len(container.Env) == 0 {\n\t\t\t\treturn errors.New(\"This container has no Envs.\")\n\t\t\t}\n\t\t\tfor ei, env := range container.Env {\n\t\t\t\tif env.Name == name {\n\t\t\t\t\tr.Containers[ci].Env[ei].Value = value\n\t\t\t\t} else {\n\t\t\t\t\treturn errors.New(\"Env not found.\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tfault = false\n\t\t\tbreak\n\t\t}\n\t\tfault = true\n\t}\n\n\t// error if no containers found.\n\tif fault {\n\t\treturn errors.New(\"Container Does Not Exist...\")\n\t}\n\n\t_, err := r.Save()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InjectEnvIntoDeployment(podSpec *corev1.PodSpec, envVars []corev1.EnvVar) error {\n\tif podSpec == nil {\n\t\treturn errors.New(\"no pod spec provided\")\n\t}\n\n\tfor i := range podSpec.Containers {\n\t\tcontainer := &podSpec.Containers[i]\n\t\tcontainer.Env = merge(container.Env, envVars)\n\t}\n\n\treturn nil\n}", "func (cluster *Cluster) ApplyEnvironment(currentEnvironment, newEnvironment *bitesize.Environment) error {\n\tvar err error\n\n\tfor _, service := range newEnvironment.Services {\n\n\t\tmapper := &translator.KubeMapper{\n\t\t\tBiteService: &service,\n\t\t\tNamespace: newEnvironment.Namespace,\n\t\t}\n\n\t\tclient := &k8s.Client{\n\t\t\tInterface: cluster.Interface,\n\t\t\tNamespace: newEnvironment.Namespace,\n\t\t\tTPRClient: cluster.TPRClient,\n\t\t}\n\n\t\tif service.Type == \"\" {\n\n\t\t\tif !shouldDeploy(currentEnvironment, newEnvironment, service.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif service.DatabaseType == \"mongo\" {\n\t\t\t\tlog.Debugf(\"Applying Stateful set for Mongo DB Service: %s \", service.Name)\n\n\t\t\t\tsecret, _ := mapper.MongoInternalSecret()\n\n\t\t\t\t//Only apply the secret if it doesnt exist. Changing this secret would cause a deployed mongo\n\t\t\t\t//cluster from being able to communicate between replicas. Need a way to update this secret\n\t\t\t\t// and redploy the mongo statefulset. For now, just protect against changing the secret\n\t\t\t\t// via environment operator\n\t\t\t\tif !client.Secret().Exists(secret.Name) {\n\t\t\t\t\tif err = client.Secret().Apply(secret); err != nil {\n\t\t\t\t\t\tlog.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstatefulset, _ := mapper.MongoStatefulSet()\n\t\t\t\tif err = client.StatefulSet().Apply(statefulset); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\n\t\t\t\tsvc, _ := mapper.HeadlessService()\n\t\t\t\tif err = client.Service().Apply(svc); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\n\t\t\t} else { //Only apply a Deployment and PVCs if this is not a DB service. The DB Statefulset creates its own PVCs\n\t\t\t\tlog.Debugf(\"Applying Deployment for Service %s \", service.Name)\n\t\t\t\tdeployment, err := mapper.Deployment()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err = client.Deployment().Apply(deployment); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\n\t\t\t\tpvc, _ := mapper.PersistentVolumeClaims()\n\t\t\t\tfor _, claim := range pvc {\n\t\t\t\t\tif err = client.PVC().Apply(&claim); err != nil {\n\t\t\t\t\t\tlog.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsvc, _ := mapper.Service()\n\t\t\t\tif err = client.Service().Apply(svc); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thpa, _ := mapper.HPA()\n\t\t\tif err = client.HorizontalPodAutoscaler().Apply(&hpa); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\n\t\t\tif service.ExternalURL != \"\" {\n\t\t\t\tingress, _ := mapper.Ingress()\n\t\t\t\tif err = client.Ingress().Apply(ingress); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\ttpr, _ := mapper.ThirdPartyResource()\n\t\t\tif err = client.ThirdPartyResource(tpr.Kind).Apply(tpr); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (c *Context) SetEnvironment(e string) { c.envName = e }", "func (gf *genericFramework) Env(key, value string) error {\n\tif gf.adam.Variables == nil {\n\t\tgf.adam.Variables = jsonutil.NewVariableMap(\"\", nil)\n\t}\n\tif _, ok := gf.adam.Variables.Get(key); ok {\n\t\treturn fmt.Errorf(\"%v has been defined\", key)\n\t}\n\tgf.adam.Variables.Set(key, jsonutil.NewStringVariable(key, value))\n\treturn nil\n}", "func (a *APIState) DeployToEnvironment(env Environment) error {\n\tputDeployURL := fmt.Sprintf(\"/api/environments/%s/deploy\", env.UUID)\n\tresp, err := a.makeRequest(http.MethodPut, putDeployURL, bytes.NewBuffer([]byte(\"{}\")))\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"deploy to env %s: %w\", env.UUID, err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"post config for module in env: expected 200, got %d\", resp.StatusCode)\n\t}\n\treturn nil\n}", "func (b *taskBuilder) env(key, value string) {\n\tif b.Spec.Environment == nil {\n\t\tb.Spec.Environment = map[string]string{}\n\t}\n\tb.Spec.Environment[key] = value\n}", "func envOverride() {\n\tvar wrk string\n\n\t// Collect variables from Environment and override value if present.\n\tlog.Printf(\"\\tCollecting the variables from Environment and override value if present...\\n\")\n\twrk = os.Getenv(\"APP01SQ_HTTP_PORT\")\n\tif len(wrk) > 0 {\n\t\thttp_port = wrk\n\t}\n\twrk = os.Getenv(\"APP01SQ_HTTP_SERVER\")\n\tif len(wrk) > 0 {\n\t\thttp_srvr = wrk\n\t}\n\twrk = os.Getenv(\"APP01SQ_BASEDIR\")\n\tif len(wrk) > 0 {\n\t\tbaseDir = wrk\n\t}\n\twrk = os.Getenv(\"APP01SQ_EXEC\")\n\tif len(wrk) > 0 {\n\t\texecPath = wrk\n\t}\n\n\twrk = os.Getenv(\"APP01SQ_DB_NAME\")\n\tif len(wrk) > 0 {\n\t\tdb_name = wrk\n\t}\n\n}", "func envUpsert(attr *syscall.ProcAttr, key string, val string) {\n\t// Future: envUpsertPrependUnique for PATH\n\tkeyEq := key + \"=\"\n\tkeyEqVal := fmt.Sprintf(\"%s=%s\", key, val)\n\tfor idx, val := range attr.Env {\n\t\tif strings.HasPrefix(val, keyEq) {\n\t\t\tattr.Env[idx] = keyEqVal\n\t\t\treturn\n\t\t}\n\t}\n\tattr.Env = append(attr.Env, keyEqVal)\n}", "func (a *Client) ModifyRuntimeEnv(params *ModifyRuntimeEnvParams) (*ModifyRuntimeEnvOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewModifyRuntimeEnvParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ModifyRuntimeEnv\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/v1/runtime_envs\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &ModifyRuntimeEnvReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ModifyRuntimeEnvOK), nil\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scale changes the number of instances (replicas) for the application's Deployment.
func (a *Workload) Scale(ctx context.Context, instances int32) error { return retry.RetryOnConflict(retry.DefaultRetry, func() error { // Retrieve the latest version of Deployment before attempting update // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver deployment, err := a.Deployment(ctx) if err != nil { return err } deployment.Spec.Replicas = &instances _, err = a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Update( ctx, deployment, metav1.UpdateOptions{}) return err }) }
[ "func (s *StatefulSetScanner) Scale(obj *Object, state *int, replicas int) error {\n\tglog.Infof(\"Scaling %s/%s to %d replicas\", obj.Namespace, obj.Name, replicas)\n\tss, err := s.getStatefulSet(obj)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetScale failed with: %s\", err)\n\t}\n\trepl := int32(replicas)\n\tss.Spec.Replicas = &repl\n\tif state != nil {\n\t\tss.ObjectMeta = updateState(ss.ObjectMeta, *state)\n\t}\n\tapps, _ := appsv1beta.NewForConfig(s.kubernetes)\n\t_, err = apps.StatefulSets(obj.Namespace).Update(ss)\n\treturn err\n}", "func (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error {\n\t// If there is only one active replica set then we should scale that up to the full count of the\n\t// deployment. If there is no active replica set, then we should scale up the newest replica set.\n\tif activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil {\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new replica set is saturated, old replica sets should be fully scaled down.\n\t// This case handles replica set adoption during a saturated new replica set.\n\tif deploymentutil.IsSaturated(deployment, newRS) {\n\t\tfor _, old := range controller.FilterActiveReplicaSets(oldRSs) {\n\t\t\tif _, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old replica sets with pods and the new replica set is not saturated.\n\t// We need to proportionally scale all replica sets (new and old) in case of a\n\t// rolling deployment.\n\tif deploymentutil.IsRollingUpdate(deployment) {\n\t\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\t\tallRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) > 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// replica sets.\n\t\tdeploymentReplicasToAdd := allowedSize - allRSsReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// replica sets from the larger to the smaller in size replica set. Scaling direction\n\t\t// drives what happens in case we are trying to scale replica sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer replica sets first, and\n\t\t// when scaling down, we should scale down older replica sets first.\n\t\tvar scalingOperation string\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd > 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))\n\t\t\tscalingOperation = \"up\"\n\n\t\tcase deploymentReplicasToAdd < 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))\n\t\t\tscalingOperation = \"down\"\n\t\t}\n\n\t\t// Iterate over all active replica sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tlogger := klog.FromContext(ctx)\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each replica set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := deploymentutil.GetProportion(logger, rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded)\n\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all replica sets\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest replica set.\n\t\t\tif i == 0 && deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[rs.Name] = nameToSize[rs.Name] + leftover\n\t\t\t\tif nameToSize[rs.Name] < 0 {\n\t\t\t\t\tnameToSize[rs.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: Use transactions when we have them.\n\t\t\tif _, _, err := dc.scaleReplicaSet(ctx, rs, nameToSize[rs.Name], deployment, scalingOperation); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func ScaleDeployment(kcontext, namespace, deploymentName string, replicas int) error {\n\tclient, err := Client(kcontext)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client: %v\", err)\n\t}\n\n\terr = wait.PollUntilContextTimeout(context.Background(), kconst.APICallRetryInterval, ReasonableMutateTime, true, func(ctx context.Context) (bool, error) {\n\t\tscale, err := client.AppsV1().Deployments(namespace).GetScale(ctx, deploymentName, meta.GetOptions{})\n\t\tif err != nil {\n\t\t\tif !IsRetryableAPIError(err) {\n\t\t\t\treturn false, fmt.Errorf(\"non-retryable failure while getting %q deployment scale: %v\", deploymentName, err)\n\t\t\t}\n\t\t\tklog.Warningf(\"failed getting %q deployment scale, will retry: %v\", deploymentName, err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif scale.Spec.Replicas != int32(replicas) {\n\t\t\tscale.Spec.Replicas = int32(replicas)\n\t\t\tif _, err = client.AppsV1().Deployments(namespace).UpdateScale(ctx, deploymentName, scale, meta.UpdateOptions{}); err != nil {\n\t\t\t\tif !IsRetryableAPIError(err) {\n\t\t\t\t\treturn false, fmt.Errorf(\"non-retryable failure while rescaling %s deployment: %v\", deploymentName, err)\n\t\t\t\t}\n\t\t\t\tklog.Warningf(\"failed rescaling %s deployment, will retry: %v\", deploymentName, err)\n\t\t\t}\n\t\t\t// repeat (if change was successful - once again to check & confirm requested scale)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\tklog.Warningf(\"failed rescaling %q deployment in %q namespace and %q context to %d replicas: %v\", deploymentName, namespace, kcontext, replicas, err)\n\t\treturn err\n\t}\n\tklog.Infof(\"%q deployment in %q namespace and %q context rescaled to %d replicas\", deploymentName, namespace, kcontext, replicas)\n\n\treturn nil\n}", "func (k *kubectlContext) Scale(resource string, scale uint) error {\n\tout, err := k.do(\"scale\", fmt.Sprintf(\"--replicas=%d\", scale), resource)\n\tk.t.Log(string(out))\n\treturn err\n}", "func ScaleDeployment(ctx context.Context, c client.Client, key client.ObjectKey, replicas int32) error {\n\tdeployment := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: key.Name,\n\t\t\tNamespace: key.Namespace,\n\t\t},\n\t}\n\n\treturn scaleResource(ctx, c, deployment, replicas)\n}", "func (s *Service) scale(replicas int) {\n\tlog.WithField(\"replicas\", replicas).Debug(\"Service scaling\")\n\ts.state = StateScaling\n\tif s.CurrentReplicas != replicas {\n\t\ts.auklet.scaleService(s.ServiceID, replicas)\n\t\ts.auklet.Lock()\n\t\ts.auklet.metrics[MetricServiceScaleEventsTotal].(prometheus.Counter).Inc()\n\t\tif replicas > s.CurrentReplicas {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleUpEventsCount].(prometheus.Counter).Inc()\n\t\t} else {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleDownEventsCount].(prometheus.Counter).Inc()\n\t\t}\n\t\ts.auklet.Unlock()\n\t}\n\n\t// after scaling return to stable state\n\ts.stable()\n}", "func (k *Kubernetes) ScaleTo(deployment, namespace string, replicas *int32) (err error) {\n\tobj, err := k.Deployment(deployment, namespace)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn k.Scale(obj, replicas)\n}", "func KubeScale(count string, deployment string) string {\n\tvar outputstring string\n\tif count == \"\" || deployment == \"\" {\n\t\toutputstring = \"\"\n\t} else if strings.HasSuffix(deployment, \".yaml\") {\n\t\toutputstring = fmt.Sprintf(\"scale --replicas=%s -f %s\", count, deployment)\n\t} else {\n\t\toutputstring = fmt.Sprintf(\"scale --replicas=%s %s\", count, deployment)\n\t}\n\treturn KubeCommand(outputstring)\n}", "func (m *Manager) Scale(shardIDs []int, shardCount int) (err error) {\n\tsg, err := NewShardGroup(m, shardIDs, shardCount)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = sg.Start()\n\treturn\n}", "func Scale(db server.Database, s Scaler) {\n\n\tresp, err := db.GetWorkers(context.TODO(), &pbr.GetWorkersRequest{})\n\tif err != nil {\n\t\tlog.Error(\"Failed GetWorkers request. Recovering.\", err)\n\t\treturn\n\t}\n\n\tfor _, w := range resp.Workers {\n\n\t\tif !s.ShouldStartWorker(w) {\n\t\t\tcontinue\n\t\t}\n\n\t\tserr := s.StartWorker(w)\n\t\tif serr != nil {\n\t\t\tlog.Error(\"Error starting worker\", serr)\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO should the Scaler instance handle this? Is it possible\n\t\t// that Initializing is the wrong state in some cases?\n\t\tw.State = pbr.WorkerState_Initializing\n\t\t_, err := db.UpdateWorker(context.TODO(), w)\n\n\t\tif err != nil {\n\t\t\t// TODO an error here would likely result in multiple workers\n\t\t\t// being started unintentionally. Not sure what the best\n\t\t\t// solution is. Possibly a list of failed workers.\n\t\t\t//\n\t\t\t// If the scheduler and database API live on the same server,\n\t\t\t// this *should* be very unlikely.\n\t\t\tlog.Error(\"Error marking worker as initializing\", err)\n\t\t}\n\t}\n}", "func ScaleDownDeployment(client clientset.Interface, deploymentObject *apps.Deployment, namespace string, replicaCount int32) {\n\ts, err := client.AppsV1().\n\t\tDeployments(namespace).\n\t\tGetScale(context.TODO(), deploymentObject.Name, metav1.GetOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tsc := *s\n\tsc.Spec.Replicas = replicaCount\n\n\t_, err = client.AppsV1().\n\t\tDeployments(namespace).\n\t\tUpdateScale(context.TODO(),\n\t\t\tdeploymentObject.Name, &sc, metav1.UpdateOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t// wait for few seconds to delete pods\n\tfor i := 0; i < 2; i++ {\n\t\ttime.Sleep(10 * time.Second)\n\t\ts, err := client.AppsV1().\n\t\t\tDeployments(namespace).\n\t\t\tGetScale(context.TODO(), deploymentObject.Name, metav1.GetOptions{})\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tif s.Spec.Replicas == replicaCount {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (m *Database) ScaleDatabaseResources(name string, scale int32) (err error) {\n\ts, err := m.client.AppsV1().Deployments(m.ns).GetScale(context.Background(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn\n\t}\n\tsc := *s\n\tsc.Spec.Replicas = scale\n\t_, err = m.client.AppsV1().Deployments(m.ns).UpdateScale(context.Background(), name, &sc, metav1.UpdateOptions{})\n\treturn\n}", "func (s *Service) Scale(ctx context.Context, scale int, timeout int) error {\n\tif s.specificiesHostPort() {\n\t\tlogrus.Warnf(\"The \\\"%s\\\" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.\", s.Name())\n\t}\n\n\tcontainers, err := s.collectContainers(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(containers) > scale {\n\t\tfoundCount := 0\n\t\tfor _, c := range containers {\n\t\t\tfoundCount++\n\t\t\tif foundCount > scale {\n\t\t\t\ttimeout = s.stopTimeout(timeout)\n\t\t\t\tif err := c.Stop(ctx, timeout); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// FIXME(vdemeester) remove volume in scale by default ?\n\t\t\t\tif err := c.Remove(ctx, false); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(containers) < scale {\n\t\terr := s.ensureImageExists(ctx, false, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = s.constructContainers(ctx, scale); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn s.up(ctx, \"\", false, options.Up{})\n}", "func (s *K8sSvc) ScaleService(ctx context.Context, cluster string, service string, desiredCount int64) error {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\t// get statefulset\n\tstatefulset, err := s.cliset.AppsV1beta2().StatefulSets(s.namespace).Get(service, metav1.GetOptions{})\n\tif err != nil {\n\t\tglog.Errorln(\"get statefulset error\", err, \"requuid\", requuid, \"service\", service, \"namespace\", s.namespace)\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"get statefulset for service\", service, \"requuid\", requuid, statefulset.Status)\n\n\t// update statefulset Replicas\n\tstatefulset.Spec.Replicas = utils.Int32Ptr(int32(desiredCount))\n\t_, err = s.cliset.AppsV1beta2().StatefulSets(s.namespace).Update(statefulset)\n\tif err != nil {\n\t\tglog.Errorln(\"update statefulset error\", err, \"requuid\", requuid, \"service\", service, \"namespace\", s.namespace)\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"ScaleService complete\", service, \"desiredCount\", desiredCount, \"requuid\", requuid)\n\treturn nil\n}", "func (w *Worker) scaleDeployment(dep types.Deployment, replicas int64) {\n\tlockRes := strconv.FormatInt(dep.ID, 10)\n\terr := w.distLock.Lock(lockRes)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to acquire deployment lock\", err)\n\t\treturn\n\t}\n\tscaledOk, stdout := w.kubectl.ScaleDeployment(dep.K8SName, replicas)\n\terr = w.distLock.Unlock(lockRes)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to release deployment lock\", err)\n\t}\n\tdep.Replicas = replicas\n\terr = w.recordRevision(dep, stdout)\n\tif err != nil {\n\t\tw.log.Error(\"Failed to record revision\", err)\n\t}\n\tif scaledOk == true {\n\t\terr = w.databaseClient.SaveDeployment(&dep)\n\t\tif err != nil {\n\t\t\tw.log.Error(\"Failed to save deployment to db\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *AppManager) ScaleDeploymentReplica(replicas int32) error {\n\tif replicas < 0 || replicas > maxReplicas {\n\t\treturn fmt.Errorf(\"%d is out of range\", replicas)\n\t}\n\n\tdeploymentsClient := m.client.Deployments(m.namespace)\n\n\tscale, err := deploymentsClient.GetScale(m.app.AppName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif scale.Spec.Replicas == replicas {\n\t\treturn nil\n\t}\n\n\tscale.Spec.Replicas = replicas\n\tm.app.Replicas = replicas\n\n\t_, err = deploymentsClient.UpdateScale(m.app.AppName, scale)\n\n\treturn err\n}", "func Scale(appName string, webCount int, workerCount int) error {\n\targs := []string{\"dokku\", \"ps:scale\", appName}\n\n\tif webCount > 0 {\n\t\twebPart := fmt.Sprintf(\"web=%v\", webCount)\n\t\targs = append(args, webPart)\n\t}\n\n\tif workerCount > 0 {\n\t\tworkerPart := fmt.Sprintf(\"worker=%v\", workerCount)\n\t\targs = append(args, workerPart)\n\t}\n\n\tlog.GeneralLogger.Println(args)\n\tcmd := common.NewShellCmd(strings.Join(args, \" \"))\n\tcmd.ShowOutput = false\n\tout, err := cmd.Output()\n\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale error:\", err.Error())\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale output:\", string(out))\n\t\treturn err\n\t}\n\tlog.GeneralLogger.Println(\"Dokku ps:scale output:\", string(out))\n\treturn nil\n}", "func (sc *ServiceController) Scale(role string, cardinal int) (bool, string) {\n\n\troleBody := make(map[string]interface{})\n\n\troleBody[\"cardinality\"] = 2\n\troleBody[\"force\"] = true\n\n\treturn sc.UpdateRole(role, roleBody)\n}", "func (r *Reconciler) scale(ctx context.Context, deployment *clusterv1.MachineDeployment, newMS *clusterv1.MachineSet, oldMSs []*clusterv1.MachineSet) error {\n\tlog := ctrl.LoggerFrom(ctx)\n\n\tif deployment.Spec.Replicas == nil {\n\t\treturn errors.Errorf(\"spec replicas for deployment %v is nil, this is unexpected\", deployment.Name)\n\t}\n\n\t// If there is only one active machine set then we should scale that up to the full count of the\n\t// deployment. If there is no active machine set, then we should scale up the newest machine set.\n\tif activeOrLatest := mdutil.FindOneActiveOrLatest(newMS, oldMSs); activeOrLatest != nil {\n\t\tif activeOrLatest.Spec.Replicas == nil {\n\t\t\treturn errors.Errorf(\"spec replicas for machine set %v is nil, this is unexpected\", activeOrLatest.Name)\n\t\t}\n\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\n\t\terr := r.scaleMachineSet(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new machine set is saturated, old machine sets should be fully scaled down.\n\t// This case handles machine set adoption during a saturated new machine set.\n\tif mdutil.IsSaturated(deployment, newMS) {\n\t\tfor _, old := range mdutil.FilterActiveMachineSets(oldMSs) {\n\t\t\tif err := r.scaleMachineSet(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old machine sets with machines and the new machine set is not saturated.\n\t// We need to proportionally scale all machine sets (new and old) in case of a\n\t// rolling deployment.\n\tif mdutil.IsRollingUpdate(deployment) {\n\t\tallMSs := mdutil.FilterActiveMachineSets(append(oldMSs, newMS))\n\t\ttotalMSReplicas := mdutil.GetReplicaCountForMachineSets(allMSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) > 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + mdutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// machine sets.\n\t\tdeploymentReplicasToAdd := allowedSize - totalMSReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// machine sets from the larger to the smaller in size machine set. Scaling direction\n\t\t// drives what happens in case we are trying to scale machine sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer machine sets first, and\n\t\t// when scaling down, we should scale down older machine sets first.\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd > 0:\n\t\t\tsort.Sort(mdutil.MachineSetsBySizeNewer(allMSs))\n\t\tcase deploymentReplicasToAdd < 0:\n\t\t\tsort.Sort(mdutil.MachineSetsBySizeOlder(allMSs))\n\t\t}\n\n\t\t// Iterate over all active machine sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tfor i := range allMSs {\n\t\t\tms := allMSs[i]\n\t\t\tif ms.Spec.Replicas == nil {\n\t\t\t\tlog.Info(\"Spec.Replicas for machine set is nil, this is unexpected.\", \"MachineSet\", ms.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each machine set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := mdutil.GetProportion(ms, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded, log)\n\t\t\t\tnameToSize[ms.Name] = *(ms.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[ms.Name] = *(ms.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all machine sets\n\t\tfor i := range allMSs {\n\t\t\tms := allMSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest machine set.\n\t\t\tif i == 0 && deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[ms.Name] += leftover\n\t\t\t\tif nameToSize[ms.Name] < 0 {\n\t\t\t\t\tnameToSize[ms.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := r.scaleMachineSet(ctx, ms, nameToSize[ms.Name], deployment); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deployment is a helper, it returns the kube deployment resource of the workload.
func (a *Workload) Deployment(ctx context.Context) (*appsv1.Deployment, error) { return a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Get( ctx, a.app.Name, metav1.GetOptions{}, ) }
[ "func kubeconDeployment(image, tag string) (*apiv1b2.Deployment, error) {\n\tom := webappMeta(helloKubeconDeploymentName, \"api\")\n\tif tag == \"\" || image == \"\" {\n\t\treturn nil, fmt.Errorf(\"error: image and tag must be defined\")\n\t}\n\tpts := &v1.PodTemplateSpec{\n\t\tObjectMeta: om,\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\tkubeconContainer(helloKubeconDeploymentName, image, tag),\n\t\t\t},\n\t\t},\n\t}\n\td := &apiv1b2.Deployment{\n\t\tObjectMeta: om,\n\t\tSpec: apiv1b2.DeploymentSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: om.Labels,\n\t\t\t},\n\t\t\tTemplate: *pts,\n\t\t},\n\t}\n\treturn d, nil\n}", "func (r *TravellerReconciler) backendDeployment(v *mydomainv1alpha1.Traveller) *appsv1.Deployment {\n\n\tlabels := labels(v, \"backend\")\n\tsize := int32(1)\n\tdep := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"hello-pod\",\n\t\t\tNamespace: v.Namespace,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &size,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: \"paulbouwer/hello-kubernetes:1.10\",\n\t\t\t\t\t\tImagePullPolicy: corev1.PullAlways,\n\t\t\t\t\t\tName: \"hello-pod\",\n\t\t\t\t\t\tPorts: []corev1.ContainerPort{{\n\t\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\t\tName: \"hello\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tcontrollerutil.SetControllerReference(v, dep, r.Scheme)\n\treturn dep\n}", "func (r *NodeFeatureDiscoveryReconciler) getDeployment(ctx context.Context, namespace string, name string) (*appsv1.Deployment, error) {\n\td := &appsv1.Deployment{}\n\terr := r.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, d)\n\treturn d, err\n}", "func (a *Workload) Get(ctx context.Context, deployment *appsv1.Deployment) *models.AppDeployment {\n\tactive := false\n\troute := \"\"\n\tstageID := \"\"\n\tstatus := \"\"\n\tusername := \"\"\n\n\t// Query application deployment for stageID and status (ready vs desired replicas)\n\n\tdeploymentSelector := fmt.Sprintf(\"app.kubernetes.io/part-of=%s,app.kubernetes.io/name=%s\", a.app.Org, a.app.Name)\n\n\tdeploymentListOptions := metav1.ListOptions{\n\t\tLabelSelector: deploymentSelector,\n\t}\n\n\tdeployments, err := a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).List(ctx, deploymentListOptions)\n\n\tif err != nil {\n\t\tstatus = pkgerrors.Wrap(err, \"failed to get Deployment status\").Error()\n\t} else if len(deployments.Items) < 1 {\n\t\tstatus = \"0/0\"\n\t} else {\n\t\tstatus = fmt.Sprintf(\"%d/%d\",\n\t\t\tdeployments.Items[0].Status.ReadyReplicas,\n\t\t\tdeployments.Items[0].Status.Replicas)\n\n\t\tstageID = deployments.Items[0].\n\t\t\tSpec.Template.ObjectMeta.Labels[\"epinio.suse.org/stage-id\"]\n\t\tusername = deployments.Items[0].Spec.Template.ObjectMeta.Labels[\"app.kubernetes.io/created-by\"]\n\n\t\tactive = true\n\t}\n\n\troutes, err := a.cluster.ListIngressRoutes(ctx, a.app.Org, names.IngressName(a.app.Name))\n\tif err != nil {\n\t\troute = err.Error()\n\t} else {\n\t\troute = routes[0]\n\t}\n\n\treturn &models.AppDeployment{\n\t\tActive: active,\n\t\tUsername: username,\n\t\tStageID: stageID,\n\t\tStatus: status,\n\t\tRoute: route,\n\t}\n}", "func deployment(deployment appsv1.Deployment) (*ResourceUsage, error) {\n\tvar (\n\t\tresourceOverhead float64 // max overhead compute resources (percent)\n\t\tpodOverhead int32 // max overhead pods during deployment\n\t)\n\n\treplicas := deployment.Spec.Replicas\n\tstrategy := deployment.Spec.Strategy\n\n\tif *replicas == 0 {\n\t\treturn &ResourceUsage{\n\t\t\tCPU: new(resource.Quantity),\n\t\t\tMemory: new(resource.Quantity),\n\t\t\tDetails: Details{\n\t\t\t\tVersion: deployment.APIVersion,\n\t\t\t\tKind: deployment.Kind,\n\t\t\t\tName: deployment.Name,\n\t\t\t\tReplicas: *replicas,\n\t\t\t\tMaxReplicas: *replicas,\n\t\t\t\tStrategy: string(strategy.Type),\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tswitch strategy.Type {\n\tcase appsv1.RecreateDeploymentStrategyType:\n\t\t// no overhead on recreate\n\t\tresourceOverhead = 1\n\t\tpodOverhead = 0\n\tcase \"\":\n\t\t// RollingUpdate is the default an can be an empty string. If so, set the defaults\n\t\t// (https://pkg.go.dev/k8s.io/api/apps/v1?tab=doc#RollingUpdateDeployment) and continue calculation.\n\t\tdefaults := intstr.FromString(\"25%\")\n\t\tstrategy = appsv1.DeploymentStrategy{\n\t\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\t\tRollingUpdate: &appsv1.RollingUpdateDeployment{\n\t\t\t\tMaxUnavailable: &defaults,\n\t\t\t\tMaxSurge: &defaults,\n\t\t\t},\n\t\t}\n\n\t\tfallthrough\n\tcase appsv1.RollingUpdateDeploymentStrategyType:\n\t\t// Documentation: https://pkg.go.dev/k8s.io/api/apps/v1?tab=doc#RollingUpdateDeployment\n\t\t// all default values are set as stated in the docs\n\t\tvar (\n\t\t\tmaxUnavailableValue intstr.IntOrString\n\t\t\tmaxSurgeValue intstr.IntOrString\n\t\t)\n\n\t\t// can be nil, if so apply default value\n\t\tif strategy.RollingUpdate == nil {\n\t\t\tmaxUnavailableValue = intstr.FromString(\"25%\")\n\t\t\tmaxSurgeValue = intstr.FromString(\"25%\")\n\t\t} else {\n\t\t\tmaxUnavailableValue = *strategy.RollingUpdate.MaxUnavailable\n\t\t\tmaxSurgeValue = *strategy.RollingUpdate.MaxSurge\n\t\t}\n\n\t\t// docs say, that the asolute number is calculated by rounding down.\n\t\tmaxUnavailable, err := intstr.GetValueFromIntOrPercent(&maxUnavailableValue, int(*replicas), false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// docs say, absolute number is calculated by rounding up.\n\t\tmaxSurge, err := intstr.GetValueFromIntOrPercent(&maxSurgeValue, int(*replicas), true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// podOverhead is the number of pods which can run more during a deployment\n\t\tpodOverhead = int32(maxSurge - maxUnavailable)\n\n\t\tresourceOverhead = (float64(podOverhead) / float64(*replicas)) + 1\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"deployment: %s deployment strategy %q is unknown\", deployment.Name, strategy.Type)\n\t}\n\n\tcpu, memory := podResources(&deployment.Spec.Template.Spec)\n\n\tmem := float64(memory.Value()) * float64(*replicas) * resourceOverhead\n\tmemory.Set(int64(math.Round(mem)))\n\n\tcpu.SetMilli(int64(math.Round(float64(cpu.MilliValue()) * float64(*replicas) * resourceOverhead)))\n\n\tresourceUsage := ResourceUsage{\n\t\tCPU: cpu,\n\t\tMemory: memory,\n\t\tDetails: Details{\n\t\t\tVersion: deployment.APIVersion,\n\t\t\tKind: deployment.Kind,\n\t\t\tName: deployment.Name,\n\t\t\tReplicas: *replicas,\n\t\t\tStrategy: string(strategy.Type),\n\t\t\tMaxReplicas: *replicas + podOverhead,\n\t\t},\n\t}\n\n\treturn &resourceUsage, nil\n}", "func Deployment(name string, description string, podSpec *kube.PodSpec, ops ...DeploymentOp) *kubeext.Deployment {\n\tmaxUnavailable := 1\n\thasRealVolume := false\n\tfor _, vol := range podSpec.Volumes {\n\t\tif vol.VolumeSource.ConfigMap == nil {\n\t\t\thasRealVolume = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasRealVolume {\n\t\t// This pod is stateless, so we can use a zero downtime\n\t\t// rollout strategy\n\t\tmaxUnavailable = 0\n\t}\n\n\tdepl := &kubeext.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"description\": description,\n\t\t\t},\n\t\t},\n\t\tSpec: kubeext.DeploymentSpec{\n\t\t\tReplicas: IntPtr(1),\n\t\t\tRevisionHistoryLimit: IntPtr(10),\n\t\t\tMinReadySeconds: 10,\n\t\t\tStrategy: kubeext.DeploymentStrategy{\n\t\t\t\tType: kubeext.RollingUpdateDeploymentStrategyType,\n\t\t\t\tRollingUpdate: &kubeext.RollingUpdateDeployment{\n\t\t\t\t\tMaxUnavailable: IntstrPtr(intstr.FromInt(maxUnavailable)),\n\t\t\t\t\tMaxSurge: IntstrPtr(intstr.FromInt(1)),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: kube.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: *podSpec,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, op := range ops {\n\t\top(depl)\n\t}\n\n\treturn depl\n}", "func Deployment() appsv1.Deployment {\n\treturn appsv1.Deployment{\n\t\tTypeMeta: TypeMeta(),\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: DefaultNamespace,\n\t\t\tName: DefaultName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tDefaultSelectorKey: DefaultSelectorValue,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tcontroller.KconfigEnabledDeploymentAnnotation: \"true\",\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\tDefaultSelectorKey: DefaultSelectorValue,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: DefaultNamespace,\n\t\t\t\t\tName: DefaultName,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\tDefaultSelectorKey: DefaultSelectorValue,\n\t\t\t\t\t},\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tcontroller.KconfigEnvRefVersionAnnotation: \"0\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\tcorev1.Container{\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func GetDeployment(accounts models.Accounts, w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation GET /applications/{appName}/deployments/{deploymentName} deployment getDeployment\n\t// ---\n\t// summary: Get deployment details\n\t// parameters:\n\t// - name: appName\n\t// in: path\n\t// description: name of Radix application\n\t// type: string\n\t// required: true\n\t// - name: deploymentName\n\t// in: path\n\t// description: name of deployment\n\t// type: string\n\t// required: true\n\t// - name: Impersonate-User\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test users (Required if Impersonate-Group is set)\n\t// type: string\n\t// required: false\n\t// - name: Impersonate-Group\n\t// in: header\n\t// description: Works only with custom setup of cluster. Allow impersonation of test group (Required if Impersonate-User is set)\n\t// type: array\n\t// items:\n\t// type: string\n\t// required: false\n\t// responses:\n\t// \"200\":\n\t// description: \"Successful get deployment\"\n\t// schema:\n\t// \"$ref\": \"#/definitions/Deployment\"\n\t// \"401\":\n\t// description: \"Unauthorized\"\n\t// \"404\":\n\t// description: \"Not found\"\n\tappName := mux.Vars(r)[\"appName\"]\n\tdeploymentName := mux.Vars(r)[\"deploymentName\"]\n\n\tdeployHandler := Init(accounts)\n\tappDeployment, err := deployHandler.GetDeploymentWithName(r.Context(), appName, deploymentName)\n\n\tif err != nil {\n\t\tradixhttp.ErrorResponse(w, r, err)\n\t\treturn\n\t}\n\n\tradixhttp.JSONResponse(w, r, appDeployment)\n}", "func createDeployment(cluster *client.VanClient, annotations map[string]string) (*v1.Deployment, error) {\n\tname := \"nginx\"\n\treplicas := int32(1)\n\tdep := &v1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: cluster.Namespace,\n\t\t\tAnnotations: annotations,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": name,\n\t\t\t},\n\t\t},\n\t\tSpec: v1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"app\": name,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{Name: \"nginx\", Image: \"quay.io/skupper/nginx-unprivileged:stable-alpine\", Ports: []corev1.ContainerPort{{Name: \"web\", ContainerPort: 8080}}, ImagePullPolicy: corev1.PullIfNotPresent},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyAlways,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Deploying resource\n\tdep, err := cluster.KubeClient.AppsV1().Deployments(cluster.Namespace).Create(context.TODO(), dep, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Wait for deployment to be ready\n\tdep, err = kube.WaitDeploymentReadyReplicas(dep.Name, cluster.Namespace, 1, cluster.KubeClient, timeout, interval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dep, nil\n}", "func (client AppsClient) GetDeployment(resourceGroupName string, name string, ID string) (result Deployment, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+[^\\.]$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewErrorWithValidationError(err, \"web.AppsClient\", \"GetDeployment\")\n\t}\n\n\treq, err := client.GetDeploymentPreparer(resourceGroupName, name, ID)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"web.AppsClient\", \"GetDeployment\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetDeploymentSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"web.AppsClient\", \"GetDeployment\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetDeploymentResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"web.AppsClient\", \"GetDeployment\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func generatorDeployment(c *configuration.Config, a *api.Apicurito) (dep client.Object) {\n\t// Define a new deployment\n\tname := DefineGeneratorName(a)\n\tdeployLabels := map[string]string{\n\t\t\"app\": \"apicurito\",\n\t\t\"component\": name,\n\t\t\"com.company\": \"Red_Hat\",\n\t\t\"rht.prod_name\": \"Red_Hat_Integration\",\n\t\t\"rht.prod_ver\": version.ShortVersion(),\n\t\t\"rht.comp\": \"Fuse\",\n\t\t\"rht.comp_ver\": version.ShortVersion(),\n\t\t\"rht.subcomp\": name,\n\t\t\"rht.subcomp_t\": \"infrastructure\",\n\t}\n\tdep = &appsv1.Deployment{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"Deployment\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: a.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(a, schema.GroupVersionKind{\n\t\t\t\t\tGroup: api.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: api.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: a.Kind,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &a.Spec.Size,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labelComponent(name),\n\t\t\t},\n\t\t\tStrategy: appsv1.DeploymentStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: deployLabels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: c.GeneratorImage,\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\t\t\tName: \"http\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8181,\n\t\t\t\t\t\t\t\tName: \"health\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 9779,\n\t\t\t\t\t\t\t\tName: \"prometheus\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8778,\n\t\t\t\t\t\t\t\tName: \"jolokia\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tFailureThreshold: 3,\n\t\t\t\t\t\t\tInitialDelaySeconds: 180,\n\t\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\t\tTimeoutSeconds: 1,\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"http\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tReadinessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tFailureThreshold: 3,\n\t\t\t\t\t\t\tInitialDelaySeconds: 10,\n\t\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\t\tTimeoutSeconds: 1,\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"http\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}", "func GetDeployment(name, namespace string) *Deployment {\n\tfor _, v := range GetDeployments() {\n\t\tif v.Name == name && v.Namespace == namespace {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func (f *fixture) buildK8sDeployment(namespace k8s.Namespace, name string) (*appsv1.Deployment, *appsv1.ReplicaSet) {\n\td := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tUID: types.UID(name + \"-uid\"),\n\t\t\tNamespace: namespace.String(),\n\t\t\tName: name,\n\t\t\tCreationTimestamp: apis.Now(),\n\t\t},\n\t}\n\trsName := name + \"-rs\"\n\trs := &appsv1.ReplicaSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tUID: types.UID(rsName + \"-uid\"),\n\t\t\tNamespace: namespace.String(),\n\t\t\tName: rsName,\n\t\t\tCreationTimestamp: apis.Now(),\n\t\t\tOwnerReferences: []metav1.OwnerReference{k8s.RuntimeObjToOwnerRef(d)},\n\t\t},\n\t}\n\n\treturn d, rs\n}", "func GetDeployResource(name string, devfileObj parser.DevfileObj, filterOptions common.DevfileOptions) (appsv1.Deployment, error) {\n\n\tcontainers, err := generator.GetContainers(devfileObj, filterOptions)\n\tif err != nil {\n\t\treturn appsv1.Deployment{}, err\n\t}\n\n\tdeployParams := generator.DeploymentParams{\n\t\tTypeMeta: generator.GetTypeMeta(\"Deployment\", \"apps/v1\"),\n\t\tContainers: containers,\n\t\tPodSelectorLabels: map[string]string{\"app\": name},\n\t}\n\n\tdeployment, err := generator.GetDeployment(devfileObj, deployParams)\n\tif err != nil {\n\t\treturn appsv1.Deployment{}, err\n\t}\n\n\treturn *deployment, nil\n}", "func Get(dev *model.Dev, namespace string, c kubernetes.Interface) (*appsv1.Deployment, error) {\n\tif namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty namespace\")\n\t}\n\n\tvar d *appsv1.Deployment\n\tvar err error\n\n\tif len(dev.Labels) == 0 {\n\t\td, err = c.AppsV1().Deployments(namespace).Get(dev.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"error while retrieving deployment %s/%s: %s\", namespace, dev.Name, err)\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdeploys, err := c.AppsV1().Deployments(namespace).List(\n\t\t\tmetav1.ListOptions{\n\t\t\t\tLabelSelector: dev.LabelsSelector(),\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(deploys.Items) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"deployment for labels '%s' not found\", dev.LabelsSelector())\n\t\t}\n\t\tif len(deploys.Items) > 1 {\n\t\t\treturn nil, fmt.Errorf(\"Found '%d' deployments for labels '%s' instead of 1\", len(deploys.Items), dev.LabelsSelector())\n\t\t}\n\t\td = &deploys.Items[0]\n\t}\n\n\treturn d, nil\n}", "func (s *deploymentServer) findDeployment(ctx context.Context, ns, name, tier string) (*appsv1.Deployment, error) {\n\t// log.Println(\"find deployment \" + ns + \" : \" + name + \".\" + tier)\n\tlog.Println(\"find deployment \" + ns + \" : \" + name)\n\tappsAPI := s.clientset.AppsV1()\n\tapiDeployments := appsAPI.Deployments(ns)\n\n\t// deployment, err := apiDeployments.Get(ctx, name+\".\"+tier, metav1.GetOptions{})\n\tdeployment, err := apiDeployments.Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\tswitch t := err.(type) {\n\t\tcase *errors.StatusError:\n\t\t\t{\n\t\t\t\tstatusCode := t.Status().Code\n\t\t\t\tif statusCode == 404 {\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"could not get deployment `%s`, got error '%v' with status %d\", name, err, statusCode)\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"could not get deployment `%s`, got error '%v'\", name, err)\n\t}\n\treturn deployment, nil\n}", "func Get(name, namespace string, config *rest.Config) (*appsv1.Deployment, error) {\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeployment, err := clientset.AppsV1().Deployments(namespace).Get(name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn deployment, nil\n}", "func (a ConfigureMonitoringAdapter) GetDeployment() string {\n\treturn \"\"\n}", "func (r *BusyboxReconciler) deploymentForBusybox(\n\tbusybox *examplecomv1alpha1.Busybox) (*appsv1.Deployment, error) {\n\tls := labelsForBusybox(busybox.Name)\n\treplicas := busybox.Spec.Size\n\n\t// Get the Operand image\n\timage, err := imageForBusybox()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdep := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: busybox.Name,\n\t\t\tNamespace: busybox.Namespace,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: ls,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: ls,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t// TODO(user): Uncomment the following code to configure the nodeAffinity expression\n\t\t\t\t\t// according to the platforms which are supported by your solution. It is considered\n\t\t\t\t\t// best practice to support multiple architectures. build your manager image using the\n\t\t\t\t\t// makefile target docker-buildx. Also, you can use docker manifest inspect <image>\n\t\t\t\t\t// to check what are the platforms supported.\n\t\t\t\t\t// More info: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity\n\t\t\t\t\t//Affinity: &corev1.Affinity{\n\t\t\t\t\t//\tNodeAffinity: &corev1.NodeAffinity{\n\t\t\t\t\t//\t\tRequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{\n\t\t\t\t\t//\t\t\tNodeSelectorTerms: []corev1.NodeSelectorTerm{\n\t\t\t\t\t//\t\t\t\t{\n\t\t\t\t\t//\t\t\t\t\tMatchExpressions: []corev1.NodeSelectorRequirement{\n\t\t\t\t\t//\t\t\t\t\t\t{\n\t\t\t\t\t//\t\t\t\t\t\t\tKey: \"kubernetes.io/arch\",\n\t\t\t\t\t//\t\t\t\t\t\t\tOperator: \"In\",\n\t\t\t\t\t//\t\t\t\t\t\t\tValues: []string{\"amd64\", \"arm64\", \"ppc64le\", \"s390x\"},\n\t\t\t\t\t//\t\t\t\t\t\t},\n\t\t\t\t\t//\t\t\t\t\t\t{\n\t\t\t\t\t//\t\t\t\t\t\t\tKey: \"kubernetes.io/os\",\n\t\t\t\t\t//\t\t\t\t\t\t\tOperator: \"In\",\n\t\t\t\t\t//\t\t\t\t\t\t\tValues: []string{\"linux\"},\n\t\t\t\t\t//\t\t\t\t\t\t},\n\t\t\t\t\t//\t\t\t\t\t},\n\t\t\t\t\t//\t\t\t\t},\n\t\t\t\t\t//\t\t\t},\n\t\t\t\t\t//\t\t},\n\t\t\t\t\t//\t},\n\t\t\t\t\t//},\n\t\t\t\t\tSecurityContext: &corev1.PodSecurityContext{\n\t\t\t\t\t\tRunAsNonRoot: &[]bool{true}[0],\n\t\t\t\t\t\t// IMPORTANT: seccomProfile was introduced with Kubernetes 1.19\n\t\t\t\t\t\t// If you are looking for to produce solutions to be supported\n\t\t\t\t\t\t// on lower versions you must remove this option.\n\t\t\t\t\t\tSeccompProfile: &corev1.SeccompProfile{\n\t\t\t\t\t\t\tType: corev1.SeccompProfileTypeRuntimeDefault,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\tName: \"busybox\",\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\t// Ensure restrictive context for the container\n\t\t\t\t\t\t// More info: https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted\n\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\tRunAsNonRoot: &[]bool{true}[0],\n\t\t\t\t\t\t\tAllowPrivilegeEscalation: &[]bool{false}[0],\n\t\t\t\t\t\t\tCapabilities: &corev1.Capabilities{\n\t\t\t\t\t\t\t\tDrop: []corev1.Capability{\n\t\t\t\t\t\t\t\t\t\"ALL\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Set the ownerRef for the Deployment\n\t// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/\n\tif err := ctrl.SetControllerReference(busybox, dep, r.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\treturn dep, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get returns the state of the app deployment encoded in the workload.
func (a *Workload) Get(ctx context.Context, deployment *appsv1.Deployment) *models.AppDeployment { active := false route := "" stageID := "" status := "" username := "" // Query application deployment for stageID and status (ready vs desired replicas) deploymentSelector := fmt.Sprintf("app.kubernetes.io/part-of=%s,app.kubernetes.io/name=%s", a.app.Org, a.app.Name) deploymentListOptions := metav1.ListOptions{ LabelSelector: deploymentSelector, } deployments, err := a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).List(ctx, deploymentListOptions) if err != nil { status = pkgerrors.Wrap(err, "failed to get Deployment status").Error() } else if len(deployments.Items) < 1 { status = "0/0" } else { status = fmt.Sprintf("%d/%d", deployments.Items[0].Status.ReadyReplicas, deployments.Items[0].Status.Replicas) stageID = deployments.Items[0]. Spec.Template.ObjectMeta.Labels["epinio.suse.org/stage-id"] username = deployments.Items[0].Spec.Template.ObjectMeta.Labels["app.kubernetes.io/created-by"] active = true } routes, err := a.cluster.ListIngressRoutes(ctx, a.app.Org, names.IngressName(a.app.Name)) if err != nil { route = err.Error() } else { route = routes[0] } return &models.AppDeployment{ Active: active, Username: username, StageID: stageID, Status: status, Route: route, } }
[ "func Get(name, namespace string, config *rest.Config) (*appsv1.Deployment, error) {\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeployment, err := clientset.AppsV1().Deployments(namespace).Get(name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn deployment, nil\n}", "func (app *ApplicationStatus) Get() int {\n\tapp.Lock()\n\tdefer app.Unlock()\n\n\treturn app.code\n}", "func Get(dev *model.Dev, namespace string, c kubernetes.Interface) (*appsv1.Deployment, error) {\n\tif namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty namespace\")\n\t}\n\n\tvar d *appsv1.Deployment\n\tvar err error\n\n\tif len(dev.Labels) == 0 {\n\t\td, err = c.AppsV1().Deployments(namespace).Get(dev.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"error while retrieving deployment %s/%s: %s\", namespace, dev.Name, err)\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdeploys, err := c.AppsV1().Deployments(namespace).List(\n\t\t\tmetav1.ListOptions{\n\t\t\t\tLabelSelector: dev.LabelsSelector(),\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(deploys.Items) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"deployment for labels '%s' not found\", dev.LabelsSelector())\n\t\t}\n\t\tif len(deploys.Items) > 1 {\n\t\t\treturn nil, fmt.Errorf(\"Found '%d' deployments for labels '%s' instead of 1\", len(deploys.Items), dev.LabelsSelector())\n\t\t}\n\t\td = &deploys.Items[0]\n\t}\n\n\treturn d, nil\n}", "func GetAppStatus(appName string) string {\n\tif !common.IsDeployed(appName) {\n\t\treturn \"NOT DEPLOYED\"\n\t}\n\n\terr := apps.CommandLocked([]string{appName})\n\tif err == nil {\n\t\treturn \"BUILDING\"\n\t}\n\n\tcontainerIDs, err := common.GetAppContainerIDs(appName, \"\")\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(err.Error())\n\t\treturn \"\"\n\t}\n\tfor _, containerID := range containerIDs {\n\t\tstatus, err := common.DockerInspect(containerID, \"'{{.State.Status}}'\")\n\t\tif err != nil {\n\t\t\tlog.ErrorLogger.Println(err.Error())\n\t\t\treturn \"\"\n\t\t}\n\t\tif status != \"exited\" {\n\t\t\treturn \"DEPLOYED\"\n\t\t}\n\t}\n\n\treturn \"STOPPED\"\n}", "func (s *REST) Get(ctx kubeapi.Context, id string) (runtime.Object, error) {\n\tdeploymentConfig, err := s.registry.GetDeploymentConfig(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn deploymentConfig, err\n}", "func (i *InstallConfig) getApp() (app *appservice.Application, err error) {\n\tenv, err := localenv.NewLocalEnvironment(localenv.LocalEnvironmentArgs{\n\t\tStateDir: i.StateDir,\n\t\tReadonlyBackend: true,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tdefer env.Close()\n\tif i.AppPackage != \"\" {\n\t\tloc, err := loc.MakeLocator(i.AppPackage)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tapp, err = env.Apps.GetApp(*loc)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn app, nil\n\t}\n\tapp, err = install.GetApp(env.Apps)\n\tif err != nil {\n\t\ti.WithError(err).Warn(\"Failed to find application package.\")\n\t\tif trace.IsNotFound(err) {\n\t\t\treturn nil, trace.NotFound(\"specified state directory %v does not \"+\n\t\t\t\t\"contain application data, please provide a path to the \"+\n\t\t\t\t\"unpacked installer tarball or specify an application \"+\n\t\t\t\t\"package via --app flag\", i.StateDir)\n\t\t}\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn app, nil\n}", "func (ai *AppInteractor) Get(id string) (domain.App, error) {\n\treturn ai.AppRepository.Get(id)\n}", "func (s appDeploymentNamespaceLister) Get(name string) (*v1beta1.AppDeployment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"appdeployment\"), name)\n\t}\n\treturn obj.(*v1beta1.AppDeployment), nil\n}", "func (cc *Controller) GetDeployment(c *gin.Context) {\n\tid := c.Param(\"deploymentID\")\n\n\td, err := cc.SqlClient.GetDeployment(id)\n\tif err != nil {\n\t\tif err == gorm.ErrRecordNotFound {\n\t\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"deployment not found\"})\n\n\t\t\treturn\n\t\t} else {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\n\t\t\treturn\n\t\t}\n\t}\n\n\t// MySQL requires that timestamp columns have a default of CURRENT_TIMESTAMP\n\t// in GCP, so if the deployment is still in a running state, set the EndTime to be nil.\n\tif d.Status == statusRunning {\n\t\td.EndTime = nil\n\t}\n\n\tc.JSON(http.StatusOK, d)\n}", "func (c *bGDeployments) Get(name string, options meta_v1.GetOptions) (result *v1.BGDeployment, err error) {\n\tresult = &v1.BGDeployment{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"bgdeployments\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (a *Workload) Deployment(ctx context.Context) (*appsv1.Deployment, error) {\n\treturn a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Get(\n\t\tctx, a.app.Name, metav1.GetOptions{},\n\t)\n}", "func (a ConfigureMonitoringAdapter) GetDeployment() string {\n\treturn \"\"\n}", "func GetApp(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AppState, opts ...pulumi.ResourceOption) (*App, error) {\n\tvar resource App\n\terr := ctx.ReadResource(\"aws-native:sagemaker:App\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *appsService) Get(id string) (*cache.App, error) {\n\tif _, ok := s.shared.Apps[id]; !ok {\n\t\treturn nil, fmt.Errorf(\"Not found\")\n\t}\n\treturn &cache.App{\n\t\tBundle: id,\n\t}, nil\n}", "func (client DeploymentsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, appName string, deploymentName string) (result DeploymentResource, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/DeploymentsClient.Get\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetPreparer(ctx, resourceGroupName, serviceName, appName, deploymentName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.DeploymentsClient\", \"Get\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func GetApp(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AppState, opts ...pulumi.ResourceOption) (*App, error) {\n\tvar resource App\n\terr := ctx.ReadResource(\"rancher2:index/app:App\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (f *FUOTADeploymentAPI) Get(ctx context.Context, req *pb.GetFUOTADeploymentRequest) (*pb.GetFUOTADeploymentResponse, error) {\n\tid, err := uuid.FromString(req.Id)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"id: %s\", err)\n\t}\n\n\tif valid, err := fuotaCred.NewValidator().ValidateFUOTADeploymentAccess(ctx, auth.Read, id); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\tfd, err := f.st.GetFUOTADeployment(ctx, id, false)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\tresp := pb.GetFUOTADeploymentResponse{\n\t\tFuotaDeployment: &pb.FUOTADeployment{\n\t\t\tId: fd.ID.String(),\n\t\t\tName: fd.Name,\n\t\t\tDr: uint32(fd.DR),\n\t\t\tFrequency: uint32(fd.Frequency),\n\t\t\tPayload: fd.Payload,\n\t\t\tRedundancy: uint32(fd.Redundancy),\n\t\t\tMulticastTimeout: uint32(fd.MulticastTimeout),\n\t\t\tUnicastTimeout: ptypes.DurationProto(fd.UnicastTimeout),\n\t\t\tState: string(fd.State),\n\t\t},\n\t}\n\n\tresp.CreatedAt = timestamppb.New(fd.CreatedAt)\n\tresp.UpdatedAt = timestamppb.New(fd.UpdatedAt)\n\tresp.FuotaDeployment.NextStepAfter = timestamppb.New(fd.NextStepAfter)\n\n\tswitch fd.GroupType {\n\tcase FUOTADeploymentGroupTypeB:\n\t\tresp.FuotaDeployment.GroupType = pb.MulticastGroupType_CLASS_B\n\tcase FUOTADeploymentGroupTypeC:\n\t\tresp.FuotaDeployment.GroupType = pb.MulticastGroupType_CLASS_C\n\tdefault:\n\t\treturn nil, status.Errorf(codes.Internal, \"unexpected group-type: %s\", fd.GroupType)\n\t}\n\n\treturn &resp, nil\n}", "func (s *Store) GetApp(name string) (*App, error) {\n\tsp, err := s.GetSnapshot().FastForward()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn getApp(name, sp)\n}", "func GetDeployment(ctx context.Context, db sqlx.Queryer, id uuid.UUID) (Deployment, error) {\n\tvar d Deployment\n\terr := sqlx.Get(db, &d, \"select * from deployment where id = $1\", id)\n\tif err != nil {\n\t\treturn d, fmt.Errorf(\"sql select error: %w\", err)\n\t}\n\n\treturn d, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewRepository returns Repository with given middleware.Pool
func NewRepository(db middleware.Pool) *Repository { return &Repository{Database: db} }
[ "func NewRepo(c backend.Credentials) (*Repo, error) {\n var err error\n r := &Repo{}\n r.Session, err = NewSession(c[\"dbhost\"])\n if err != nil {\n return nil, err\n }\n\n r.Db = r.Session.DB(c[\"dbname\"])\n return r, nil\n}", "func newRepository() Repository {\n\tif cfg == nil {\n\t\tpanic(fmt.Errorf(\"missing configuration\"))\n\t}\n\tif log == nil {\n\t\tpanic(fmt.Errorf(\"missing logger\"))\n\t}\n\n\tp2p.SetConfig(cfg)\n\tp2p.SetLogger(log)\n\n\t// create connections\n\tcaBridge, dbBridge, rpcBridge, geoBridge, err := connect(cfg, log)\n\tif err != nil {\n\t\tlog.Fatal(\"repository init failed\")\n\t\treturn nil\n\t}\n\n\t// construct the proxy instance\n\tp := proxy{\n\t\tcache: caBridge,\n\t\tdb: dbBridge,\n\t\trpc: rpcBridge,\n\t\tgeoip: geoBridge,\n\t\tlog: log,\n\t\tcfg: cfg,\n\n\t\t// get the map of governance contracts\n\t\tgovContracts: governanceContractsMap(cfg.Governance),\n\n\t\t// keep reference to the SOL compiler\n\t\tsolCompiler: cfg.Compiler.DefaultSolCompilerPath,\n\t}\n\n\t// return the proxy\n\treturn &p\n}", "func NewRepository(db *pgx.ConnPool) HistoryRepository {\n\treturn Repository{\n\t\tdb: db,\n\t}\n}", "func newRepository(\n\tid borges.RepositoryID,\n\tsto storage.Storer,\n\tfs billy.Filesystem,\n\tm borges.Mode,\n\ttransactional bool,\n\tl *Location,\n) (*Repository, error) {\n\trepo, err := git.Open(sto, nil)\n\tif err != nil {\n\t\tif err == git.ErrRepositoryNotExists {\n\t\t\trepo, err = git.Init(sto, nil)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, borges.ErrLocationNotExists.Wrap(err, id)\n\t\t}\n\t}\n\n\treturn &Repository{\n\t\tid: id,\n\t\trepo: repo,\n\t\ts: sto,\n\t\tfs: fs,\n\t\tmode: m,\n\t\ttransactional: transactional,\n\t\tlocation: l,\n\t\tcreateVersion: -1,\n\t}, nil\n}", "func NewPool(fn ResolverFactory) *Pool {\n\treturn &Pool{\n\t\tfactory: fn,\n\t}\n}", "func getNewPool(cfg *config.Pool) *pool {\n\tvar p pool\n\n\tp.lockDuration = cfg.LockDuration\n\n\tp.locks = make(map[*config.Resource]*ResourceLock)\n\tfor _, resource := range cfg.Resources {\n\t\tp.locks[resource] = nil\n\t}\n\n\tkeys, _ := storage.GetKeys(storageKey)\n\tfor _, key := range keys {\n\t\tvar lock ResourceLock\n\t\tif err := storage.Read(storageKey, key, &lock); err != nil {\n\t\t\tlog.Errorf(\"[Pool] unable to restore lock for '%s': %s\", key, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor k := range p.locks {\n\t\t\tif k.Name == key {\n\t\t\t\tlock.Resource = *k\n\t\t\t\tp.locks[k] = &lock\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn &p\n}", "func NewRepository(repoName string) *Repository {\n\n\tclientIndex := model.ByEquality(\"ClientId\")\n\tclientIndex.Unique = true\n\t//\tuserIndex := model.ByEquality(\"UserId\")\n\t//\tuserIndex.Unique = true\n\n\treturn &Repository{\n\t\tName: repoName,\n\t\tmesssages: model.NewTable(store.DefaultStore, repoName, model.Indexes(clientIndex), nil),\n\t}\n}", "func NewRepository(db *sql.DB) *repository {\n\treturn &repository{db: db}\n}", "func newPool(m *waddrmgr.Manager, poolID []byte) *Pool {\n\treturn &Pool{\n\t\tID: poolID,\n\t\tseriesLookup: make(map[uint32]*SeriesData),\n\t\tmanager: m,\n\t}\n}", "func NewRepository(collection Collection) BasicRepository {\n\treturn &basicRepositoryUsecase{\n\t\tcollectionName: collection,\n\t}\n}", "func NewRepo(a *config.AppConfig) *Repository {\n\treturn &Repository{ //returns the referenc to a Repository\n\t\tApp: a, // populate in \"App\" from type \"Repository\n\t}\n}", "func newRepo(r *github.Repository) Repo {\n\tvar lang string\n\tif r.Language != nil {\n\t\tlang = *r.Language\n\t} else {\n\t\tlang = \"-\"\n\t}\n\treturn Repo{*r.HTMLURL, lang, *r.StargazersCount, *r.ForksCount}\n}", "func New() *Pool {\n\treturn &Pool{}\n}", "func New(prototype Aggregate, opts ...Option) *Repository {\n\tt := reflect.TypeOf(prototype)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tr := &Repository{\n\t\tprototype: t,\n\t\tstore: newMemoryStore(),\n\t\tserializer: NewJSONSerializer(),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n\n\treturn r\n}", "func NewRepo(cfg *Config) (*Repo, error) {\r\n\tdb, err := bolt.Open(cfg.Path, 0600, cfg.Opts)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn &Repo{\r\n\t\tDB: db,\r\n\t\tbucket: cfg.Bucket,\r\n\t}, nil\r\n}", "func NewRepo(fwa IAdapter) Repo {\n\treturn Repo{\n\t\tfarmWorkerAdapter: fwa,\n\t}\n}", "func NewRepository(funcs template.FuncMap) *Repository {\n\trepo := Repository{\n\t\tfiles: make(map[string]string),\n\t\ttemplates: make(map[string]*template.Template),\n\t\tfuncs: funcs,\n\t}\n\n\tif repo.funcs == nil {\n\t\trepo.funcs = make(template.FuncMap)\n\t}\n\n\treturn &repo\n}", "func New(db *db.DB) core.RepositoryStore {\n\treturn &repoStore{db}\n}", "func NewPool() *Pool {\n\treturn &Pool{\n\t\tresourceQueue: make(chan Resource),\n\t\tresourceCount: 0,\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transaction returns a middleware.Transaction that could execute multiple commands as a transaction
func (r *Repository) Transaction() (middleware.Transaction, error) { return r.Database.Transaction() }
[ "func Transaction(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tt, ctx := orm.NewTransaction(r.Context())\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tt.Rollback()\n\t\t\t\t// Panic to let recoverer handle 500\n\t\t\t\tpanic(rec)\n\t\t\t} else {\n\t\t\t\terr := t.Commit()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func Transaction(muts ...TransactionMutator) (result *TransactionBuilder) {\n\tresult = &TransactionBuilder{}\n\tresult.Mutate(muts...)\n\tresult.Mutate(Defaults{})\n\treturn\n}", "func (s *SessionStore) Transaction(callback func(*SessionStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&SessionStore{store})\n\t})\n}", "func TransactionMiddleware() middleware.TransactionMiddleware {\n\tdb := gormer.GetDB()\n\ttxnDataSQL := gormrepo.NewTxnDataSQL(db)\n\ttransactionMiddleware := middleware.NewTransactionMiddleware(txnDataSQL)\n\treturn transactionMiddleware\n}", "func Transaction(up, down Step, force bool) Step {\n\t// special case - if not up - there is nothing to do - no need to create transaction\n\tif up == nil {\n\t\treturn nil\n\t}\n\n\t// special case - if up and not down - there is no to rollback - no need to create transaction\n\tif down == nil {\n\t\treturn up\n\t}\n\n\t// there is something to up and something to rollback, full transaction\n\treturn &transaction{up, down, force}\n}", "func (tx *tX) Transaction() (*tX, error) {\n\treturn tx, nil\n}", "func NewTransactionMiddleware() *TransactionMiddleware {\n\treturn &TransactionMiddleware{}\n}", "func (b *RaftBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error {\n\tcommand := &LogData{\n\t\tOperations: make([]*LogOperation, len(txns)),\n\t}\n\tfor i, txn := range txns {\n\t\top := &LogOperation{}\n\t\tswitch txn.Operation {\n\t\tcase physical.PutOperation:\n\t\t\top.OpType = putOp\n\t\t\top.Key = txn.Entry.Key\n\t\t\top.Value = txn.Entry.Value\n\t\tcase physical.DeleteOperation:\n\t\t\top.OpType = deleteOp\n\t\t\top.Key = txn.Entry.Key\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%q is not a supported transaction operation\", txn.Operation)\n\t\t}\n\n\t\tcommand.Operations[i] = op\n\t}\n\n\tb.l.RLock()\n\terr := b.applyLog(ctx, command)\n\tb.l.RUnlock()\n\treturn err\n}", "func (s *StoreSqlite) Transaction(block func()) error {\n\tvar err error\n\n\tif s.currentTransaction != nil {\n\t\tlog.Fatalln(\"NO CONCURRENT TRANSACTIONS\")\n\t}\n\ttransaction, err := s.Db.Begin()\n\tgotils.CheckNotFatal(err)\n\n\ts.currentTransaction = transaction\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tblock()\n\n\terr = transaction.Commit()\n\tgotils.CheckNotFatal(err)\n\ts.currentTransaction = nil\n\n\treturn err\n}", "func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error) {\n\tpanicked := true\n\n\tif committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {\n\t\t// nested transaction\n\t\tif !db.DisableNestedTransaction {\n\t\t\terr = db.SavePoint(fmt.Sprintf(\"sp%p\", fc)).Error\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\t// Make sure to rollback when panic, Block error or Commit error\n\t\t\t\tif panicked || err != nil {\n\t\t\t\t\tdb.RollbackTo(fmt.Sprintf(\"sp%p\", fc))\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\terr = fc(db.Session(&Session{NewDB: db.clone == 1}))\n\t} else {\n\t\ttx := db.Begin(opts...)\n\t\tif tx.Error != nil {\n\t\t\treturn tx.Error\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// Make sure to rollback when panic, Block error or Commit error\n\t\t\tif panicked || err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t}\n\t\t}()\n\n\t\tif err = fc(tx); err == nil {\n\t\t\tpanicked = false\n\t\t\treturn tx.Commit().Error\n\t\t}\n\t}\n\n\tpanicked = false\n\treturn\n}", "func (s *PollStore) Transaction(callback func(*PollStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PollStore{store})\n\t})\n}", "func (s *Session) Transaction() *Transaction {\n\t// acquire lock\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.txn\n}", "func (c *Conn) Transaction(fn func(*Conn) error) error {\r\n\tvar (\r\n\t\ttx = c.Begin()\r\n\t\tconn = &Conn{}\r\n\t)\r\n\tcopier.Copy(conn, c)\r\n\tconn.DB = tx\r\n\tif err := fn(conn); err != nil {\r\n\t\ttx.Rollback()\r\n\t\treturn err\r\n\t}\r\n\ttx.Commit()\r\n\treturn nil\r\n}", "func (m Middleware) Tx(db *sql.DB) TxFunc {\n\treturn func(f func(tx daos.Transaction, w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tt, err := db.Begin()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tl := m.log.WithRequest(r)\n\t\t\t\tif p := recover(); p != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(p)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\terr = t.Commit()\n\t\t\t\t\tl.Info(\"transaction commited\")\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terr = f(t, w, r)\n\t\t}\n\t}\n}", "func (ingest *Ingestion) Transaction(\n\tid int64,\n\ttx *core.Transaction,\n\tfee *core.TransactionFee,\n) error {\n\n\tsql := ingest.transactionInsertBuilder(id, tx, fee)\n\t_, err := ingest.DB.Exec(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Transaction(db *sql.DB, fns ...func(DB) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, fn := range fns {\n\t\terr := fn(tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\terr = interpretScanError(err)\n\treturn err\n}", "func (n *Node) Transaction(f func(*NodeTx) error) error {\n\treturn n.transaction.Transaction(n.node.DB(), func(tx database.Tx) error {\n\t\treturn f(n.builder(tx))\n\t})\n}", "func (context *Context) Transaction(req map[string]interface{}) (rsp map[string]interface{}, err error) {\n\t// Handle the special case where we are just processing a response\n\tvar reqJSON []byte\n\tif req == nil {\n\t\treqJSON = []byte(\"\")\n\t} else {\n\n\t\t// Marshal the request to JSON\n\t\treqJSON, err = note.JSONMarshal(req)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"error marshaling request for module: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// Perform the transaction\n\trspJSON, err2 := context.TransactionJSON(reqJSON)\n\tif err2 != nil {\n\t\terr = fmt.Errorf(\"error from TransactionJSON: %s\", err2)\n\t\treturn\n\t}\n\n\t// Unmarshal for convenience of the caller\n\terr = note.JSONUnmarshal(rspJSON, &rsp)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error unmarshaling reply from module: %s %s: %s\", err, note.ErrCardIo, rspJSON)\n\t\treturn\n\t}\n\n\t// Done\n\treturn\n}", "func TransactionlMiddleware(db *sqlx.DB) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\ttx := db.MustBegin()\n\t\tc.Set(\"Tx\", tx)\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Errorln(\"Panic, transaction rollback\")\n\t\t\t\ttx.Rollback()\n\t\t\t\tpanic(err)\n\t\t\t} else {\n\t\t\t\tlog.Debugln(\"Commiting transaction\")\n\t\t\t\ttx.Commit()\n\t\t\t}\n\t\t}()\n\t\tc.Next()\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate returns the standard deviation of a base indicator
func (sdi StandardDeviationIndicator) Calculate(index int) big.Decimal { return VarianceIndicator{ Indicator: sdi.Indicator, }.Calculate(index).Sqrt() }
[ "func stdDev(data []int) float64 {\n\treturn math.Sqrt(variance(data))\n}", "func stdDev(n, numerator, denominator int) int {\n\tp := float64(numerator) / float64(denominator)\n\tsigma := math.Sqrt(float64(n) * p * (1 - p))\n\treturn int(math.Ceil(sigma))\n}", "func (sr Series) Std(nMinus1 bool) float64 {\n\tvar std float64\n\tif sr.Dtype == \"string\" {\n\t\tstd = math.NaN()\n\t}\n\n\tif sr.Dtype == \"float64\" {\n\t\tif values, ok := sr.Values.(helper.NumpythonicFloatArray); ok {\n\t\t\tstd = values.Std(nMinus1)\n\t\t}\n\t}\n\n\treturn std\n}", "func (h *pingHistory) stdDev() float64 {\n\treturn math.Sqrt(h.variance())\n}", "func (e *exemplarSampler) standardDeviation() float64 {\n\tif e.count < 2 {\n\t\treturn 0\n\t}\n\treturn math.Sqrt(e.m2 / float64(e.count-1))\n}", "func meanSd(data []float64) (mean, sd float64) {\n\tn := 0.0\n\tmean = 0.0\n\tm2 := 0.0\n\tfor _, x := range data {\n\t\tn++\n\t\tdelta := x - mean\n\t\tmean += delta / n\n\t\tif n > 1 {\n\t\t\tm2 += delta * (x - mean)\n\t\t}\n\t}\n\tsd = sqrt(m2 / (n - 1))\n\treturn\n}", "func StdDev(values []float64) float64 {\n\tvar sum float64\n\tmean := Mean(values)\n\tfor i := 0; i < len(values); i++ {\n\t\ttemp := values[i] - mean\n\t\tsum += temp * temp\n\t}\n\treturn math.Sqrt(sum / float64(len(values)-1))\n}", "func (s sample) StdDev() float64 {\n\treturn math.Sqrt(s.Variance())\n}", "func (s Series) StdDev() (float64, error) {\n\tvals, err := s.Float(false)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstdDev := stat.StdDev(vals, nil)\n\treturn stdDev, nil\n}", "func stDev(a []float64) (s float64) {\n\tm := mean(a)\n\tfor _, v := range a {\n\t\ts += (v - m) * (v - m)\n\t}\n\treturn math.Sqrt(s / float64(len(a)))\n}", "func (s *NumSeries) StdDev() float64 {\n\treturn math.Sqrt(s.Variance())\n}", "func StandardDeviation(values []float64) float64 {\n\tarithmeticMean := ArithmeticMean(values)\n\tvar squaredDifferences []float64\n\tfor _, v := range values {\n\t\tdifference := v - arithmeticMean\n\t\tsquaredDifferences = append(squaredDifferences, difference*difference)\n\t}\n\treturn math.Sqrt((1 / float64(len(values)-1)) * Sum(squaredDifferences))\n}", "func CalculateStdev(data []int) float64 {\n\tmean := CalculateMean(data)\n\tvar squareSum float64\n\tfor _, value := range data {\n\t\tsquareSum += math.Pow((float64(value) - mean), 2)\n\t}\n\treturn math.Sqrt(squareSum / (float64(len(data) - 1)))\n}", "func (sg *SampleGroup) StdDev() float64 {\n\tif !sg.HasSamples() {\n\t\treturn 0\n\t}\n\tavg := float64(sg.AvgRate())\n\tsum := float64(0)\n\tfor _, c := range sg.Samples {\n\t\tsum += math.Pow(float64(c.Rate())-avg, 2)\n\t}\n\tvariance := sum / float64(len(sg.Samples))\n\treturn math.Sqrt(variance)\n}", "func (bin Binomial) StdDev() float64 {\n\treturn math.Sqrt(bin.Variance())\n}", "func (ds *Dataset) StandardDeviation() float64 {\n\treturn math.Sqrt(ds.Variance())\n}", "func (df *DataFrame) Std() *series.Series {\n\treturn df.math(\"std\", (*series.Series).Std)\n}", "func StandardDeviation(numbers []float64) float64 {\n\treturn math.Sqrt(Variance(numbers))\n}", "func (r *RunningStats) Stddev() float64 {\n\treturn math.Sqrt(r.Var())\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewClient Creates a new client to communicate with the Sentry API.
func NewClient(api string, baseURI string, org string) *Client { if !strings.HasSuffix(baseURI, "/") { baseURI += "/" } return &Client{ client: &http.Client{}, sentryAPIKey: api, sentryURI: baseURI, sentryOrg: org, } }
[ "func NewClient(dsn string) *Client {\n\tif dsn == \"\" {\n\t\treturn nil\n\t}\n\n\tclient, err := sentry.NewClient(sentry.ClientOptions{\n\t\tDsn: dsn,\n\t\tRelease: env.Version(),\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &Client{hub: sentry.NewHub(client, sentry.NewScope())}\n}", "func New(\n\tsentryAddress *node.Address,\n\tsentryCert *x509.Certificate,\n\tnodeIdentity *identity.Identity,\n) (*Client, error) {\n\tc := &Client{\n\t\tlogger: logging.GetLogger(\"sentry/client\"),\n\t\tsentryAddress: sentryAddress,\n\t\tsentryCert: sentryCert,\n\t\tnodeIdentity: nodeIdentity,\n\t}\n\n\tif err := c.createConnection(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create a connection to sentry node: %w\", err)\n\t}\n\n\treturn c, nil\n}", "func NewClient() *Client {\n\tclientId := os.Getenv(clientIdEnvVar)\n\tif clientId == \"\" {\n\t\tlog.Fatalf(\"Please provide client id by setting %s\", clientIdEnvVar)\n\t}\n\treturn &Client{\n\t\thttp: &http.Client{},\n\t\tbaseAddr: \"https://api.seatGeek.com/2/\",\n\t\tclientId: clientId}\n}", "func NewSentryClient(options sentry.ClientOptions) (*sentry.Client, error) {\n\tclient, err := sentry.NewClient(options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// init sentry hub\n\tsentry.Init(options)\n\treturn client, nil\n}", "func newClient() *sts.STS {\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\tconfig := aws.NewConfig()\n\tif debug {\n\t\tconfig.WithLogLevel(aws.LogDebugWithHTTPBody)\n\t}\n\treturn sts.New(sess, config)\n}", "func NewClient(ctx context.Context, credentials *Credentials) (*Client, error) {\n\tctx, cancel := context.WithTimeout(ctx, 1*time.Minute)\n\tdefer cancel()\n\n\tssn, err := GetSession(credentials)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get session\")\n\t}\n\n\tclient := &Client{\n\t\tssn: ssn,\n\t}\n\treturn client, nil\n}", "func ExampleNewClient() {\n\t// initialize registrar\n\treg, err := dosaRenamed.NewRegistrar(\"test\", \"myteam.myservice\", cte1)\n\tif err != nil {\n\t\t// registration will fail if the object is tagged incorrectly\n\t\tfmt.Printf(\"NewRegistrar error: %s\", err)\n\t\treturn\n\t}\n\n\t// use a devnull connector for example purposes\n\tconn := devnull.NewConnector()\n\n\t// create the client using the registrar and connector\n\tclient := dosaRenamed.NewClient(reg, conn)\n\n\terr = client.Initialize(context.Background())\n\tif err != nil {\n\t\tfmt.Printf(\"Initialize error: %s\", err)\n\t\treturn\n\t}\n}", "func newClient() (client *Client) {\n\n\tclient = new(Client)\n\n\tid := <-uuidBuilder\n\tclient.Id = id.String()\n\tclient.subscriptions = make(map[string]bool)\n\n\tclients[client.Id] = client\n\n\tlog.WithField(\"clientID\", id.String()).Info(\"Created new Client\")\n\treturn\n}", "func newClient(project string) (*client, error) {\n\tctx := context.Background()\n\tcl, err := pubsub.NewClient(ctx, project)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &client{\n\t\tclient: cl,\n\t}, nil\n}", "func NewClient(ctx context.Context, projectID string, sensor instana.TracerLogger, opts ...option.ClientOption) (*Client, error) {\n\tc, err := pubsub.NewClient(ctx, projectID, opts...)\n\treturn &Client{c, projectID, sensor}, err\n}", "func NewClient(parent *apiresource.APIResource, pathContext map[string]string) *Client {\n\tapiResource := apiresource.NewAPIResourceWithParent(parent, pathContext)\n\n\treturn &Client{apiResource}\n}", "func newClient(hecURL url.URL, hecToken, index, hostname string, skipTLSVerify bool) *splunk.Client {\n\thttpTransport := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: skipTLSVerify,\n\t\t},\n\t}\n\thttpClient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t\tTransport: httpTransport,\n\t}\n\n\tif hecURL.Path == \"\" || hecURL.Path == \"/\" {\n\t\thecURL.Path = eventURLPath\n\t}\n\n\treturn &splunk.Client{\n\t\tHTTPClient: httpClient,\n\t\tURL: hecURL.String(),\n\t\tHostname: hostname,\n\t\tToken: hecToken,\n\t\tIndex: index,\n\t}\n}", "func newClient(cs ConnectionSettings) *client {\n\treturn &client{\n\t\tConnectionSettings: cs,\n\t}\n}", "func NewClient(registryURL string) *Client {\n\treturn &Client{\n\t\turl: registryURL + \"/sgulreg/services\",\n\t\thttpClient: http.DefaultClient,\n\t\treqMux: &sync.RWMutex{},\n\t\tregistered: false,\n\t}\n}", "func NewClient(iamClient *iam.Client, config *Config) (*Client, error) {\n\treturn newClient(iamClient, config)\n}", "func NewClient(enabled bool, address, token, source, sourceType, index string) Client {\n\tif enabled {\n\t\turl := address + \"/services/collector/raw\"\n\t\tsplunkClient := splunk.NewClient(nil, url, token, source, sourceType, index)\n\t\treturn Client{ClientImpl: splunkClient}\n\t}\n\treturn Client{ClientImpl: nil}\n}", "func NewClient(accountID, apiKey string) *Client {\n\treturn &Client{\n\t\taccountID: accountID,\n\t\tapiKey: apiKey,\n\t\tresty: resty.New().SetHostURL(apiURL).SetAuthToken(apiKey),\n\t\tlogger: log.New(\"labstack\"),\n\t}\n}", "func New(cfg client.Config) (*client.Client, error) {\n\t// creating new client\n\tcli, err := mustNewClient(&cfg)\n\n\t// check for error in creating client\n\tif err != nil {\n\t\treturn nil, err // forward error\n\t}\n\n\t// returning new client\n\treturn cli, nil\n}", "func NewClient(url, apiKey string) *Client {\n\treturn &Client{\n\t\turl: url,\n\t\tapiKey: apiKey,\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the constructor rejects unsupported URLs.
func TestBadUrl(t *testing.T) { _, err := NewTransport("ftp://www.example.com", nil, nil, nil, nil) if err == nil { t.Error("Expected error") } _, err = NewTransport("https://www.example", nil, nil, nil, nil) if err == nil { t.Error("Expected error") } }
[ "func validURL(url string) bool {\n\treturn true\n}", "func (r URL) Valid(v interface{}) error {\n\tval, ok := v.(string)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"wrong data type, expected string, got: %T\", v))\n\t}\n\n\turl, err := url.Parse(val)\n\tif err != nil {\n\t\tif r.Err != nil {\n\t\t\treturn r.Err\n\t\t}\n\t\treturn err\n\t}\n\n\tif r.Scheme != \"\" && url.Scheme != r.Scheme {\n\t\treturn r.Err\n\t}\n\n\treturn nil\n}", "func URL(data ValidationData) error {\n\tv, err := helper.ToString(data.Value)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a string\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tparsed, err := url.Parse(v)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a valid URL\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Scheme != \"http\" && parsed.Scheme != \"https\" {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid scheme '%s'\", parsed.Scheme),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Host == \"\" || strings.IndexRune(parsed.Host, '\\\\') > 0 {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid host ('%s')\", parsed.Host),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (metaDataConfig MetaDataConfig) validateURL() bool{\n\n _, webSiteErr := url.ParseRequestURI(metaDataConfig.Website)\n _, sourceErr := url.ParseRequestURI(metaDataConfig.Source)\n \n if webSiteErr != nil || sourceErr != nil {\n return false\n } else {\n return true\n }\n}", "func (m *URL) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func MustNewURL(u string) URL {\n\tpu, err := url.Parse(u)\n\tif err != nil {\n\t\tlogger.Panicf(\"BUG: cannot parse u=%q: %s\", u, err)\n\t}\n\treturn URL{\n\t\turl: pu,\n\t}\n}", "func URL(url string, required bool) ValidateFunc {\n\treturn func() error {\n\t\tif isEmptyStr(url) {\n\t\t\treturn requiredErr(required, \"URL cannot be empty\")\n\t\t}\n\t\tif ok := regURL.MatchString(url); !ok {\n\t\t\treturn fmt.Errorf(\"invalid URL `%s`\", url)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func validateURL(rawurl string) error {\n\tu, err := url.ParseRequestURI(rawurl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(u.Scheme) == 0 {\n\t\treturn fmt.Errorf(\"Invalid scheme: %s\", rawurl)\n\t}\n\n\tif len(u.Host) == 0 {\n\t\treturn fmt.Errorf(\"Invalid host: %s\", rawurl)\n\t}\n\n\treturn nil\n}", "func TestMoreURI(t *testing.T) {\n\tt.Parallel()\n\n\tinvalidURIs := []string{\n\t\t\"mailto://{}:{}@host.domain.com\",\n\t\t\"https://user:passwd@[FF02::3::5:8080\",\n\t\t\"https://user:passwd@[FF02::3::5:8080/?#\",\n\t\t\"https://user:passwd@[FF02::3::5:8080#\",\n\t\t\"https://user:passwd@[FF02::3::5:8080#abc\",\n\n\t\t// this test comes from the format test in JSONSchema-test suite\n\t\t\"//foo.bar/?baz=qux#quux\", // missing scheme and //\n\n\t\t// from https://docs.microsoft.com/en-gb/dotnet/api/system.uri.iswellformeduristring?view=netframework-4.7.2#System_Uri_IsWellFormedUriString_System_String_System_UriKind_\n\t\t\"http://www.contoso.com/path???/file name\", // The string is not correctly escaped.\n\t\t\"c:\\\\directory\\filename\", // The string is an absolute Uri that represents an implicit file Uri.\n\t\t\"http:\\\\host/path/file\", // The string contains unescaped backslashes even if they will be treated as forward slashes\n\t\t\"www.contoso.com/path/file\", // The string represents a hierarchical absolute Uri and does not contain \"://\"\n\t\t\"2013.05.29_14:33:41\", // relative URIs with a colon (':') in their first segment are not considered well-formed.\n\n\t\t// from https://metacpan.org/source/SONNEN/Data-Validate-URI-0.07/t/is_uri.t\n\t\t\"\",\n\t\t\"foo\",\n\t\t\"foo@bar\",\n\t\t\"http://<foo>\", // illegal characters\n\t\t\"://bob/\", // empty scheme\n\t\t\"1http://bob\", // bad scheme\n\t\t\"http://example.w3.org/%illegal.html\",\n\t\t\"http://example.w3.org/%a\", // partial escape\n\t\t\"http://example.w3.org/%a/foo\", // partial escape\n\t\t\"http://example.w3.org/%at\", // partial escape\n\n\t\t// from https://github.com/python-hyper/rfc3986/blob/master/tests/test_validators.py\n\t\t\"https://user:passwd@[21DA:00D3:0000:2F3B:02AA:00FF:FE28:9C5A]:8080:8090/a?query=value#fragment\", // multiple ports\n\t\t\"https://user:passwd@[FF02::3::5]:8080/a?query=value#fragment\", // invalid IPv6\n\t\t\"https://user:passwd@[FADF:01%en0]:8080/a?query=value#fragment\", // invalid IPv6\n\t\t\"https://user:passwd@256.256.256.256:8080/a?query=value#fragment\", // invalid IPv4\n\t\t\"https://user:passwd@[FADF:01%en0:8080/a?query=value#fragment\", // invalid IPv6 (missing bracket)\n\n\t\t// from github.com/scalatra/rl: URI parser in scala\n\t\t\"http://www.exa mple.org\",\n\n\t\t// and others..\n\t\t\"?invalidscheme://www.example.com\",\n\t\t\"inv;alidscheme://www.example.com\",\n\t\t\"http://www.example.org/hello/world.txt/?id=5&pa{}rt=three#there-you-go\", // invalid char in query\n\t\t\"http://www.example.org/hello/world.txt/?id=5&part=three#there-you-go{}\", // invalid char in fragment\n\t\t\"scheme://user:passwd@[]/invalid\", // empty IPV6\n\n\t\t// invalid fragment\n\t\t\"http://example.w3.org/legit#ill[egal\",\n\n\t\t// pathological input\n\t\t\"?//x\",\n\t\t\"#//x\",\n\t\t\"://x\",\n\n\t\t// trailing empty fragment, invalid path\n\t\t\"http://example.w3.org/%legit#\",\n\t}\n\n\tvalidURIs := []string{\n\t\t\"http:////foo.html\", // empty host, correct path (see issue#3)\n\t\t\"urn://example-bin.org/path\",\n\t\t\"https://example-bin.org/path\",\n\t\t\"https://example-bin.org/path?\",\n\t\t\"mailto://u:p@host.domain.com#\", // empty fragment\n\t\t\"mailto://u:p@host.domain.com?#\", // empty query + fragment\n\t\t\"http:\",\n\t\t\"foo:\",\n\n\t\t// this one is dubious: Microsoft (.Net) recognize the C:/... string as a path and\n\t\t// states this as incorrect uri -- all other validators state a host \"c\" and state this uri as a valid one\n\t\t\"file://c:/directory/filename\",\n\n\t\t// from https://metacpan.org/source/SONNEN/Data-Validate-URI-0.07/t/is_uri.t\n\t\t// (many of those come from the rfc3986 examples)\n\t\t\"http://localhost/\",\n\t\t\"http://example.w3.org/path%20with%20spaces.html\",\n\t\t\"http://example.w3.org/%20\",\n\t\t\"ftp://ftp.is.co.za/rfc/rfc1808.txt\",\n\t\t\"ftp://ftp.is.co.za/../../../rfc/rfc1808.txt\",\n\t\t\"http://www.ietf.org/rfc/rfc2396.txt\",\n\t\t\"ldap://[2001:db8::7]/c=GB?objectClass?one\",\n\t\t\"mailto:John.Doe@example.com\", // valid but counter-intuitive: userinfo is actually a path\n\t\t\"mailto://John.Doe@example.com\", // this is the right way\n\t\t\"news:comp.infosystems.www.servers.unix\",\n\t\t\"tel:+1-816-555-1212\",\n\t\t\"telnet://192.0.2.16:80/\",\n\t\t\"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n\t\t\"http://www.richardsonnen.com/\",\n\n\t\t// from https://github.com/python-hyper/rfc3986/blob/master/tests/test_validators.py\n\t\t\"ssh://ssh@git.openstack.org:22/sigmavirus24\",\n\t\t\"https://git.openstack.org:443/sigmavirus24\",\n\t\t\"ssh://git.openstack.org:22/sigmavirus24?foo=bar#fragment\",\n\t\t\"git://github.com\",\n\t\t\"https://user:passwd@[21DA:00D3:0000:2F3B:02AA:00FF:FE28:9C5A]:8080/a?query=value#fragment\",\n\t\t\"https://user:passwd@[::1%25lo]:8080/a?query=value#fragment\",\n\t\t\"https://user:passwd@[FF02:30:0:0:0:0:0:5%25en1]:8080/a?query=value#fragment\",\n\t\t\"https://user:passwd@127.0.0.1:8080/a?query=value#fragment\",\n\t\t\"https://user:passwd@http-bin.org:8080/a?query=value#fragment\",\n\n\t\t// from github.com/scalatra/rl: URI parser in scala\n\t\t\"http://www.example.org:8080\",\n\t\t\"http://www.example.org/\",\n\t\t\"http://www.詹姆斯.org/\",\n\t\t\"http://www.example.org/hello/world.txt\",\n\t\t\"http://www.example.org/hello/world.txt/?id=5&part=three\",\n\t\t\"http://www.example.org/hello/world.txt/?id=5&part=three#there-you-go\",\n\t\t\"http://www.example.org/hello/world.txt/#here-we-are\",\n\n\t\t// trailing empty fragment: legit\n\t\t\"http://example.w3.org/legit#\",\n\t}\n\n\tt.Run(\"with invalid URIs\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tfor _, toPin := range invalidURIs {\n\t\t\tinvURI := toPin\n\n\t\t\tt.Run(fmt.Sprintf(\"should be invalid: %q\", invURI), func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\n\t\t\t\trequire.Falsef(t, IsURI(invURI),\n\t\t\t\t\t\"expected %q to be an invalid URI\", invURI,\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"with valid URIs\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tfor _, toPin := range validURIs {\n\t\t\tvalidURI := toPin\n\n\t\t\tt.Run(fmt.Sprintf(\"should be valid: %q\", validURI), func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\n\t\t\t\trequire.Truef(t, IsURI(validURI),\n\t\t\t\t\t\"expected %q to be a valid URI\", validURI,\n\t\t\t\t)\n\n\t\t\t\t_, err := Parse(validURI)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n}", "func Test_GetImageFromUrl_badUrl(t *testing.T) {\n\tb, err := GetImageFromUrl(\"some-bad-url\")\n\n\tassert.Equal(t, `Error getting image: Get some-bad-url: unsupported protocol scheme \"\"`, err.Error())\n\tassert.Equal(t, []byte(nil), b)\n}", "func ValidURL(str string) bool {\n\tu, err := url.Parse(str)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false\n\t}\n\tif u.Scheme == \"\" || u.Host == \"\" || u.Path == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func validURL(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif u.Host == \"\" {\n\t\treturn false\n\t}\n\tswitch u.Scheme {\n\tcase \"http\", \"https\":\n\tdefault:\n\t\treturn false\n\t}\n\tfor _, r := range u.RawQuery {\n\t\t// https://tools.ietf.org/html/rfc3986#section-3.4 defines:\n\t\t//\n\t\t//\tquery = *( pchar / \"/\" / \"?\" )\n\t\t//\tpchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n\t\t//\tunreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n\t\t//\tpct-encoded = \"%\" HEXDIG HEXDIG\n\t\t//\tsub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n\t\t//\t\t\t/ \"*\" / \"+\" / \",\" / \";\" / \"=\"\n\t\t//\n\t\t// check for these\n\t\tswitch {\n\t\tcase r >= '0' && r <= '9':\n\t\tcase r >= 'A' && r <= 'Z':\n\t\tcase r >= 'a' && r <= 'z':\n\t\tdefault:\n\t\t\tswitch r {\n\t\t\tcase '/', '?',\n\t\t\t\t':', '@',\n\t\t\t\t'-', '.', '_', '~',\n\t\t\t\t'%', '!', '$', '&', '\\'', '(', ')', '*', '+', ',', ';', '=':\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func isValidHostURL(hostURL string) bool {\n\tif strings.TrimSpace(hostURL) == \"\" {\n\t\treturn false\n\t}\n\turl := client.NewURL(hostURL)\n\tif url.Scheme != \"https\" && url.Scheme != \"http\" {\n\t\treturn false\n\t}\n\tif url.Path != \"\" && url.Path != \"/\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func LegalURL(url string) bool {\n\treturn linksRegexp.MatchString(url)\n}", "func URLValidator(message ...string) regexpValidator {\n\tregex := `^(https?|ftp)(:\\/\\/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+)$`\n\tif len(message) > 0 {\n\t\treturn RegexpValidator(regex, message[0])\n\t} else {\n\t\treturn RegexpValidator(regex, \"Enter a valid url.\")\n\t}\n}", "func IsURLValid(value string) bool {\n\tcheck := value != \"\" && !strings.Contains(value, \".gif\") && !strings.Contains(value, \"logo\") && !strings.Contains(value, \"mobilebanner\")\n\n\tif check {\n\t\treturn strings.HasPrefix(value, \"http\") || strings.HasPrefix(value, \"https\")\n\t}\n\n\treturn check\n}", "func (h *Handlers) ValidateURL(input string) bool {\n\tu, err := url.Parse(input)\n\n\tfmt.Println(err, u.Scheme, u.Host)\n\tif err != nil || u.Scheme == \"\" || !strings.Contains(u.Host, \".\") {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (s *htmlState) checkURL(raw string) {\n\tif s.ignore&issueURL != 0 {\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(raw, \"mailto:\") {\n\t\tif strings.Index(raw, \"@\") == -1 {\n\t\t\ts.err(fmt.Errorf(\"not an email address\"))\n\t\t}\n\t\treturn\n\t}\n\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\ts.err(fmt.Errorf(\"bad URL '%s': %s\", raw, err.Error()))\n\t\treturn\n\t}\n\tif u.Opaque != \"\" {\n\t\ts.err(fmt.Errorf(\"bad URL part '%s'\", u.Opaque))\n\t\treturn\n\t}\n\n\tif strings.Index(raw, \" \") != -1 {\n\t\ts.err(fmt.Errorf(\"unencoded space in URL\"))\n\t}\n}", "func ValidateURL(u url.URL) error {\n\t_, err := url.ParseRequestURI(u.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texp := regexp.MustCompile(`http(s)?://(www.)?.*..*/`)\n\tif !exp.MatchString(u.String()) {\n\t\treturn errors.New(\"Invalid URL or wrong scheme\")\n\t}\n\n\texp2 := regexp.MustCompile(`.jp(e?)g$|.css$|.ico$`)\n\tif exp2.MatchString(u.String()) {\n\t\treturn errors.New(\"Bad document type\")\n\t}\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for failure when the query is too short to be valid.
func TestShortQuery(t *testing.T) { var qerr *queryError doh, _ := NewTransport(testURL, ips, nil, nil, nil) _, err := doh.Query([]byte{}) if err == nil { t.Error("Empty query should fail") } else if !errors.As(err, &qerr) { t.Errorf("Wrong error type: %v", err) } else if qerr.status != BadQuery { t.Errorf("Wrong error status: %d", qerr.status) } _, err = doh.Query([]byte{1}) if err == nil { t.Error("One byte query should fail") } else if !errors.As(err, &qerr) { t.Errorf("Wrong error type: %v", err) } else if qerr.status != BadQuery { t.Errorf("Wrong error status: %d", qerr.status) } }
[ "func IsOverQueryLimit(err error) bool {\n\tif e, ok := err.(*apiError); ok {\n\t\treturn e.Status == \"OVER_QUERY_LIMIT\"\n\t}\n\treturn false\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func validateQuery(schema *gqlast.Schema, query *gqlast.QueryDocument) error {\n\t// Validate the query against the schema, erroring if there's an issue.\n\terr := gqlvalidator.Validate(schema, query)\n\tif err != nil {\n\t\t// We use strings.TrimSuffix to remove the '.' characters that the library\n\t\t// authors include on most of their validation errors. This should be safe,\n\t\t// since variable names in their error messages are usually quoted, and\n\t\t// this affects only the last character(s) in the string.\n\t\t// NOTE(philipc): We know the error location will be in the query string,\n\t\t// because schema validation always happens before this function is called.\n\t\treturn fmt.Errorf(\"%s in GraphQL query string at location %d:%d\", strings.TrimSuffix(err[0].Message, \".\"), err[0].Locations[0].Line, err[0].Locations[0].Column)\n\t}\n\treturn nil\n}", "func validateQueryContext(ctx context.Context) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\tswitch err := ctx.Err(); err {\n\t\tcase context.Canceled:\n\t\t\treturn ErrQueryCancelled\n\t\tcase context.DeadlineExceeded:\n\t\t\treturn ErrQueryTimeout\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func validateTimeout(timeout time.Duration) error {\n\tif timeout < time.Millisecond {\n\t\treturn nosqlerr.NewIllegalArgument(\"Timeout must be greater than or equal to 1 millisecond\")\n\t}\n\n\treturn nil\n}", "func (q Query) Validate(fck func(k, v string) error, sck func(k string) error) error {\n\tif err := fck(q.FilterBy, q.FilterVal); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sck(q.SortBy); err != nil {\n\t\treturn err\n\t}\n\n\tif q.Limit < 1 {\n\t\treturn NewError(nil, http.StatusBadRequest, \"invalid limit\")\n\t}\n\n\tif q.Page < 1 {\n\t\treturn NewError(nil, http.StatusBadRequest, \"invalid page\")\n\t}\n\n\treturn nil\n}", "func hasValidTopValuesQuery(query interface{}) error {\n\tqueryConverted := query.(map[string]interface{})\n\t// check query limit\n\tif len(queryConverted) > 5 {\n\t\treturn errors.New(\"Top Values Validator: the top values query has a limit of 5 queries by request.\")\n\t}\n\t// check column limit\n\tfor _, value := range queryConverted {\n\t\tif len(value.(map[string]interface{})) > 6 {\n\t\t\treturn errors.New(\"Top Values Validator: the query exceeds the limit of columns per query in request\")\n\t\t}\n\t}\n\treturn nil\n}", "func validateNeighborsQuery(value string) (string, error) {\n\tif len(value) < 3 {\n\t\t// Maybe make configurable,\n\t\t// A length of 3 would be sufficient for \"DFN\" and\n\t\t// other shorthands.\n\t\treturn \"\", ErrQueryTooShort\n\t}\n\treturn value, nil\n}", "func ValidateQuery(query string) (bool, error) {\n\n\t// simple sql pattern\n\tpattern := \"(select|SELECT) ([a-zA-Z]+(,[a-zA-Z]+)*) (from|FROM) [a-zA-Z]+(\\\\.[a-zA-Z]+)* ((limit|LIMIT) [0-9]+)? ((orderby|ORDERBY) (asc|desc|ASC|DESC))?;\"\n\tmatched, err := regexp.MatchString(pattern, query)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn matched, nil\n}", "func hasValidCountQuery(query interface{}) error {\n\tswitch query.(type) {\n\tcase []interface{}:\n\t\tquerySize := len(query.([]interface{}))\n\t\tif querySize > 10 {\n\t\t\treturn errors.New(\"Count Query Validator: the query count entity has a limit of 10 queries by request.\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func validatePrefixQuery(value string) (string, error) {\n\t// We should at least provide 2 chars\n\tif len(value) < 2 {\n\t\treturn \"\", ErrQueryTooShort\n\t}\n\tif !strings.Contains(value, \":\") && !strings.Contains(value, \".\") {\n\t\treturn \"\", ErrQueryIncomplete\n\t}\n\treturn value, nil\n}", "func TooShort(name, in string, min int64, value interface{}) *Validation {\n\tvar msg string\n\tif in == \"\" {\n\t\tmsg = fmt.Sprintf(tooShortMessageNoIn, name, min)\n\t} else {\n\t\tmsg = fmt.Sprintf(tooShortMessage, name, in, min)\n\t}\n\n\treturn &Validation{\n\t\tcode: TooShortFailCode,\n\t\tName: name,\n\t\tIn: in,\n\t\tValue: value,\n\t\tValid: min,\n\t\tmessage: msg,\n\t}\n}", "func hasValidDataExtractionQuery(query interface{}) error {\n\tqueryConverted := query.(map[string]interface{})\n\tif val, ok := queryConverted[\"columns\"]; ok {\n\t\tcolumns := reflect.ValueOf(val)\n\t\tif columns.Len() > 10 {\n\t\t\treturn errors.New(\"Data Extraction Validator: The key 'columns' in data extraction result must have up to 10 columns.\")\n\t\t}\n\t}\n\treturn nil\n}", "func (query Query) Validate() error {\n\tif strings.TrimSpace(query.Text) == \"\" {\n\t\treturn fmt.Errorf(\"invalid query\")\n\t}\n\treturn nil\n}", "func checkLimitClause(db ds.Database, l *queryparser.LimitClause) error {\n\tif l == nil {\n\t\treturn nil\n\t}\n\tif l.Limit.Value < 1 {\n\t\treturn syncql.ErrorfLimitMustBeGt0(db.GetContext(), \"[%v]limit must be > 0.\", l.Limit.Off)\n\t}\n\treturn nil\n}", "func (h *Handler) QueryFailed(validatorID ids.ShortID, requestID uint32) {\n\th.sendReliableMsg(message{\n\t\tmessageType: queryFailedMsg,\n\t\tvalidatorID: validatorID,\n\t\trequestID: requestID,\n\t})\n}", "func _1346sqlite3ExprListCheckLength(tls *crt.TLS, _pParse uintptr /* *TParse */, _pEList uintptr /* *TExprList */, _zObject uintptr /* *int8 */) {\n\tvar _mx int32\n\n\t_mx = *(*int32)(unsafe.Pointer(((*(*uintptr)(unsafe.Pointer(_pParse))) + 100) + 8))\n\tif _pEList == 0 || (*(*int32)(unsafe.Pointer(_pEList))) <= _mx {\n\t\tgoto _1\n\t}\n\n\t_553sqlite3ErrorMsg(tls, _pParse, ts+26375 /* \"too many columns in %s\" */, _zObject)\n_1:\n}", "func (s SQLQuery) Validate() error {\n\tstr := strings.ToLower(string(s))\n\tif !strings.HasPrefix(str, \"select\") {\n\t\treturn ErrNotSQLQuery\n\t}\n\treturn nil\n}", "func isInsufficientSpace(err error) bool {\n\treturn strings.Contains(strings.ToLower(err.Error()), \"insufficient free space\")\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that all fields of m1 match those of m2, except for Header.ID and Additionals.
func queriesMostlyEqual(m1 dnsmessage.Message, m2 dnsmessage.Message) bool { // Make fields we don't care about match, so that equality check is easy. m1.Header.ID = m2.Header.ID m1.Additionals = m2.Additionals return reflect.DeepEqual(m1, m2) }
[ "func (r *Record) Eq(other *Record) bool {\n\n\t// We disregard leader in equality tests, since LineMARC doesn't have one,\n\t// and it will be generated by decoders and encoder.\n\t/*\n\t\t// Leader equal?\n\t\tif r.Leader != other.Leader {\n\t\t\treturn false\n\t\t}\n\t*/\n\n\t// Control Fields equal?\n\tif len(r.CtrlFields) != len(other.CtrlFields) {\n\t\treturn false\n\t}\n\n\tsort.Sort(r.CtrlFields)\n\tsort.Sort(other.CtrlFields)\n\n\tfor i, f := range r.CtrlFields {\n\t\tif other.CtrlFields[i] != f {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Data Fields equal?\n\tif len(r.DataFields) != len(other.DataFields) {\n\t\treturn false\n\t}\n\n\tsort.Sort(r.DataFields)\n\tsort.Sort(other.DataFields)\n\n\tfor i, f := range r.DataFields {\n\t\tif o := other.DataFields[i]; o.Tag != f.Tag || o.Ind1 != f.Ind1 || o.Ind2 != f.Ind2 {\n\t\t\treturn false\n\t\t}\n\t\t// SubFields equal?\n\t\tif len(f.SubFields) != len(other.DataFields[i].SubFields) {\n\t\t\treturn false\n\t\t}\n\n\t\tsort.Sort(f.SubFields)\n\t\tsort.Sort(other.DataFields[i].SubFields)\n\n\t\tfor j, s := range f.SubFields {\n\t\t\tif other.DataFields[i].SubFields[j] != s {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\t// All fields equal\n\treturn true\n}", "func sameHeaders(h1 map[string]string, h2 map[string]string) bool {\n\t//Check both nil\n\tif h1 == nil && h2 == nil {\n\t\treturn true\n\t}\n\n\t//Check one nil\n\tif h1 == nil || h2 == nil {\n\t\treturn false\n\t}\n\n\t//Checl length\n\tif len(h1) != len(h2) {\n\t\treturn false\n\t}\n\n\t//Check every value and key in the other map\n\tfor key, value := range h1 {\n\n\t\t//Check if the key is in the other map\n\t\tval, ok := h2[key]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\t//check the value\n\t\tif val != value {\n\t\t\treturn false\n\t\t}\n\n\t}\n\n\t//If nothig was wrong return true (the maps are equal)\n\treturn true\n}", "func (f *Form) FieldsMatch(f1, f2 string, shouldTheyMatch bool) {\n\tfield1 := f.Get(f1)\n\tfield2 := f.Get(f2)\n\tif (field1 == field2 && shouldTheyMatch == true) || (field1 != field2 && shouldTheyMatch == false) {\n\t\treturn\n\t} else if (field1 == field2 && shouldTheyMatch == false) || (field1 != field2 && shouldTheyMatch == true) {\n\t\tf.Errors.Add(\"password\", \"Password and password confirmation do not match\")\n\t}\n}", "func (h Header) rowsAreEqual(h2 Header) bool {\n\tif len(h.headerRows) != len(h2.headerRows) {\n\t\treturn false\n\t}\n\tfor i, r := range h.headerRows {\n\t\tif r != h2.headerRows[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equalMetadatas(md, md2 Metadata) error {\n\t// Check Aggregate Fields\n\tif md.AggregateHealth != md2.AggregateHealth {\n\t\treturn fmt.Errorf(\"AggregateHealth not equal, %v and %v\", md.AggregateHealth, md2.AggregateHealth)\n\t}\n\tif md.AggregateLastHealthCheckTime != md2.AggregateLastHealthCheckTime {\n\t\treturn fmt.Errorf(\"AggregateLastHealthCheckTimes not equal, %v and %v\", md.AggregateLastHealthCheckTime, md2.AggregateLastHealthCheckTime)\n\t}\n\tif md.AggregateMinRedundancy != md2.AggregateMinRedundancy {\n\t\treturn fmt.Errorf(\"AggregateMinRedundancy not equal, %v and %v\", md.AggregateMinRedundancy, md2.AggregateMinRedundancy)\n\t}\n\tif md.AggregateModTime != md2.AggregateModTime {\n\t\treturn fmt.Errorf(\"AggregateModTimes not equal, %v and %v\", md.AggregateModTime, md2.AggregateModTime)\n\t}\n\tif md.AggregateNumFiles != md2.AggregateNumFiles {\n\t\treturn fmt.Errorf(\"AggregateNumFiles not equal, %v and %v\", md.AggregateNumFiles, md2.AggregateNumFiles)\n\t}\n\tif md.AggregateNumStuckChunks != md2.AggregateNumStuckChunks {\n\t\treturn fmt.Errorf(\"AggregateNumStuckChunks not equal, %v and %v\", md.AggregateNumStuckChunks, md2.AggregateNumStuckChunks)\n\t}\n\tif md.AggregateNumSubDirs != md2.AggregateNumSubDirs {\n\t\treturn fmt.Errorf(\"AggregateNumSubDirs not equal, %v and %v\", md.AggregateNumSubDirs, md2.AggregateNumSubDirs)\n\t}\n\tif md.AggregateRemoteHealth != md2.AggregateRemoteHealth {\n\t\treturn fmt.Errorf(\"AggregateRemoteHealth not equal, %v and %v\", md.AggregateRemoteHealth, md2.AggregateRemoteHealth)\n\t}\n\tif md.AggregateRepairSize != md2.AggregateRepairSize {\n\t\treturn fmt.Errorf(\"AggregateRepairSize not equal, %v and %v\", md.AggregateRepairSize, md2.AggregateRepairSize)\n\t}\n\tif md.AggregateSize != md2.AggregateSize {\n\t\treturn fmt.Errorf(\"AggregateSize not equal, %v and %v\", md.AggregateSize, md2.AggregateSize)\n\t}\n\tif md.AggregateStuckHealth != md2.AggregateStuckHealth {\n\t\treturn fmt.Errorf(\"AggregateStuckHealth not equal, %v and %v\", md.AggregateStuckHealth, md2.AggregateStuckHealth)\n\t}\n\tif md.AggregateStuckSize != md2.AggregateStuckSize {\n\t\treturn fmt.Errorf(\"AggregateStuckSize not equal, %v and %v\", md.AggregateStuckSize, md2.AggregateStuckSize)\n\t}\n\n\t// Aggregate Skynet Fields\n\tif md.AggregateSkynetFiles != md2.AggregateSkynetFiles {\n\t\treturn fmt.Errorf(\"AggregateSkynetFiles not equal, %v and %v\", md.AggregateSkynetFiles, md2.AggregateSkynetFiles)\n\t}\n\tif md.AggregateSkynetSize != md2.AggregateSkynetSize {\n\t\treturn fmt.Errorf(\"AggregateSkynetSize not equal, %v and %v\", md.AggregateSkynetSize, md2.AggregateSkynetSize)\n\t}\n\n\t// Check SiaDir Fields\n\tif md.Health != md2.Health {\n\t\treturn fmt.Errorf(\"Healths not equal, %v and %v\", md.Health, md2.Health)\n\t}\n\tif md.LastHealthCheckTime != md2.LastHealthCheckTime {\n\t\treturn fmt.Errorf(\"LastHealthCheckTime not equal, %v and %v\", md.LastHealthCheckTime, md2.LastHealthCheckTime)\n\t}\n\tif md.MinRedundancy != md2.MinRedundancy {\n\t\treturn fmt.Errorf(\"MinRedundancy not equal, %v and %v\", md.MinRedundancy, md2.MinRedundancy)\n\t}\n\tif md.ModTime != md2.ModTime {\n\t\treturn fmt.Errorf(\"ModTime not equal, %v and %v\", md.ModTime, md2.ModTime)\n\t}\n\tif md.NumFiles != md2.NumFiles {\n\t\treturn fmt.Errorf(\"NumFiles not equal, %v and %v\", md.NumFiles, md2.NumFiles)\n\t}\n\tif md.NumStuckChunks != md2.NumStuckChunks {\n\t\treturn fmt.Errorf(\"NumStuckChunks not equal, %v and %v\", md.NumStuckChunks, md2.NumStuckChunks)\n\t}\n\tif md.NumSubDirs != md2.NumSubDirs {\n\t\treturn fmt.Errorf(\"NumSubDirs not equal, %v and %v\", md.NumSubDirs, md2.NumSubDirs)\n\t}\n\tif md.RemoteHealth != md2.RemoteHealth {\n\t\treturn fmt.Errorf(\"RemoteHealth not equal, %v and %v\", md.RemoteHealth, md2.RemoteHealth)\n\t}\n\tif md.RepairSize != md2.RepairSize {\n\t\treturn fmt.Errorf(\"RepairSize not equal, %v and %v\", md.RepairSize, md2.RepairSize)\n\t}\n\tif md.Size != md2.Size {\n\t\treturn fmt.Errorf(\"Sizes not equal, %v and %v\", md.Size, md2.Size)\n\t}\n\tif md.StuckHealth != md2.StuckHealth {\n\t\treturn fmt.Errorf(\"StuckHealth not equal, %v and %v\", md.StuckHealth, md2.StuckHealth)\n\t}\n\tif md.StuckSize != md2.StuckSize {\n\t\treturn fmt.Errorf(\"StuckSize not equal, %v and %v\", md.StuckSize, md2.StuckSize)\n\t}\n\n\t// Skynet Fields\n\tif md.SkynetFiles != md2.SkynetFiles {\n\t\treturn fmt.Errorf(\"SkynetFiles not equal, %v and %v\", md.SkynetFiles, md2.SkynetFiles)\n\t}\n\tif md.SkynetSize != md2.SkynetSize {\n\t\treturn fmt.Errorf(\"SkynetSize not equal, %v and %v\", md.SkynetSize, md2.SkynetSize)\n\t}\n\n\treturn nil\n}", "func MatchHeaders(fromReq, fromDB map[string]string) bool {\n\tvar matched = false\n\tfor k, dbVal := range fromDB {\n\t\tif headerVal, ok := fromReq[k]; ok && headerVal == dbVal {\n\t\t\tmatched = true\n\t\t} else {\n\t\t\t// return early if we get a different value\n\t\t\treturn false\n\t\t}\n\t}\n\treturn matched\n}", "func (h Header) isEqual(h2 Header) bool {\n\tif h.underlineCh != h2.underlineCh {\n\t\treturn false\n\t}\n\tif len(h.headerRows) != len(h2.headerRows) {\n\t\treturn false\n\t}\n\tif h.dataRowsPrinted != h2.dataRowsPrinted {\n\t\treturn false\n\t}\n\tif h.repeatHdrInterval != h2.repeatHdrInterval {\n\t\treturn false\n\t}\n\tif h.headerRowCount != h2.headerRowCount {\n\t\treturn false\n\t}\n\tif h.printHdr != h2.printHdr {\n\t\treturn false\n\t}\n\tif h.hdrPrinted != h2.hdrPrinted {\n\t\treturn false\n\t}\n\tif h.underlineHdr != h2.underlineHdr {\n\t\treturn false\n\t}\n\tif !h.rowsAreEqual(h2) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (o1 StructTestObject) Diff(o2 StructTestObject) metago.Diff {\n\tchgs := make([]metago.Chg, 0)\n\n\t{\n\t\tva, vb := o1.B, o2.B\n\t\tif !va.Equals(vb) {\n\t\t\tchgs = append(chgs, metago.NewStructChg(&StructTestObjectBSREF, va.Diff(vb)))\n\t\t}\n\t}\n\n\t{\n\t\tva, vb := o1.MB, o2.MB\n\t\tfor key, va1 := range va {\n\t\t\tif vb1, ok := vb[key]; ok {\n\t\t\t\t// \"key\" exists in both \"va\" and \"vb\"\n\t\t\t\tchgs1 := make([]metago.Chg, 0)\n\t\t\t\tif !va1.Equals(vb1) {\n\t\t\t\t\tchgs1 = append(chgs1, metago.NewStructChg(&StructTestObjectMBSREF, va1.Diff(vb1)))\n\t\t\t\t}\n\t\t\t\tif len(chgs1) != 0 {\n\t\t\t\t\tchgs = append(chgs, metago.NewIntMapChg(&StructTestObjectMBSREF, key, metago.ChangeTypeModify, chgs1))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// \"key\" exists in \"va\" but not in \"vb\"\n\t\t\t\tchgs1 := make([]metago.Chg, 0)\n\t\t\t\tt := BasicAttrTypesObject{}\n\t\t\t\tchgs1 = append(chgs1, metago.NewStructChg(&StructTestObjectMBSREF, va1.Diff(t)))\n\t\t\t\tif len(chgs1) != 0 {\n\t\t\t\t\tchgs = append(chgs, metago.NewIntMapChg(&StructTestObjectMBSREF, key, metago.ChangeTypeDelete, chgs1))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor key, vb1 := range vb {\n\t\t\tif _, ok := va[key]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// \"key\" exists in vb but not int va\"\n\t\t\tchgs1 := make([]metago.Chg, 0)\n\t\t\tt := BasicAttrTypesObject{}\n\t\t\tchgs1 = append(chgs1, metago.NewStructChg(&StructTestObjectMBSREF, t.Diff(vb1)))\n\t\t\tif len(chgs1) != 0 {\n\t\t\t\tchgs = append(chgs, metago.NewIntMapChg(&StructTestObjectMBSREF, key, metago.ChangeTypeInsert, chgs1))\n\t\t\t}\n\t\t}\n\t}\n\treturn metago.Diff{Chgs: chgs}\n}", "func (m Matrix) DimsMatch(other Matrix) bool {\n\treturn m.Rows() == other.Rows() && m.Cols() == other.Cols()\n}", "func FieldsEqual(f1, f2 []*querypb.Field) bool {\n\tif len(f1) != len(f2) {\n\t\treturn false\n\t}\n\tfor i, f := range f1 {\n\t\tif !proto.Equal(f, f2[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func extIDsMatch(want, have map[string]string) bool {\n\tfor k, v := range want {\n\t\tactual, ok := have[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif actual != v {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func compareFields(s1, s2 reflect.StructField) error {\n\tif s1.Name != s2.Name {\n\t\treturn fmt.Errorf(\"field %s name = %q, want %q\", s1.Name, s1.Name, s2.Name)\n\t}\n\tif s1.Tag != s2.Tag {\n\t\treturn fmt.Errorf(\"field %s tag = %q, want %q\", s1.Name, s1.Tag, s2.Tag)\n\t}\n\tif s1.Type.Name() != s2.Type.Name() {\n\t\treturn fmt.Errorf(\"field %s type = %q, want %q\", s1.Name, s1.Type.Name(), s2.Type.Name())\n\t}\n\treturn nil\n}", "func equalMetrics(m1, m2 []client.Metric) bool {\n\tif len(m1) != len(m2) {\n\t\treturn false\n\t}\n\tsort.Slice(m1, func(i, j int) bool {\n\t\treturn m1[i].Name < m1[j].Name\n\t})\n\tsort.Slice(m2, func(i, j int) bool {\n\t\treturn m2[i].Name < m2[j].Name\n\t})\n\tfor i := 0; i < len(m1); i++ {\n\t\t// compare props\n\t\tif m1[i].Name != m2[i].Name ||\n\t\t\tm1[i].StartTime != m2[i].StartTime ||\n\t\t\tm1[i].StopTime != m2[i].StopTime ||\n\t\t\tm1[i].StepTime != m2[i].StepTime {\n\t\t\treturn false\n\t\t}\n\t\t// compare values\n\t\tif len(m1[i].Values) != len(m2[i].Values) {\n\t\t\treturn false\n\t\t}\n\t\tfor j := 0; j < len(m1[i].Values); j++ {\n\t\t\ta, b := m1[i].Values[j], m2[i].Values[j]\n\t\t\tif math.IsNaN(a) && math.IsNaN(b) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a != b {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func equalBubbledMetadata(md1, md2 siadir.Metadata) error {\n\t// Check AggregateHealth\n\tif md1.AggregateHealth != md2.AggregateHealth {\n\t\treturn fmt.Errorf(\"AggregateHealth not equal, %v and %v\", md1.AggregateHealth, md2.AggregateHealth)\n\t}\n\t// Check AggregateNumFiles\n\tif md1.AggregateNumFiles != md2.AggregateNumFiles {\n\t\treturn fmt.Errorf(\"AggregateNumFiles not equal, %v and %v\", md1.AggregateNumFiles, md2.AggregateNumFiles)\n\t}\n\t// Check Size\n\tif md1.AggregateSize != md2.AggregateSize {\n\t\treturn fmt.Errorf(\"aggregate sizes not equal, %v and %v\", md1.AggregateSize, md2.AggregateSize)\n\t}\n\t// Check Health\n\tif md1.Health != md2.Health {\n\t\treturn fmt.Errorf(\"healths not equal, %v and %v\", md1.Health, md2.Health)\n\t}\n\t// Check LastHealthCheckTimes\n\tif md2.LastHealthCheckTime != md1.LastHealthCheckTime {\n\t\treturn fmt.Errorf(\"LastHealthCheckTimes not equal %v and %v\", md2.LastHealthCheckTime, md1.LastHealthCheckTime)\n\t}\n\t// Check MinRedundancy\n\tif md1.MinRedundancy != md2.MinRedundancy {\n\t\treturn fmt.Errorf(\"MinRedundancy not equal, %v and %v\", md1.MinRedundancy, md2.MinRedundancy)\n\t}\n\t// Check Mod Times\n\tif md2.ModTime != md1.ModTime {\n\t\treturn fmt.Errorf(\"ModTimes not equal %v and %v\", md2.ModTime, md1.ModTime)\n\t}\n\t// Check NumFiles\n\tif md1.NumFiles != md2.NumFiles {\n\t\treturn fmt.Errorf(\"NumFiles not equal, %v and %v\", md1.NumFiles, md2.NumFiles)\n\t}\n\t// Check NumStuckChunks\n\tif md1.NumStuckChunks != md2.NumStuckChunks {\n\t\treturn fmt.Errorf(\"NumStuckChunks not equal, %v and %v\", md1.NumStuckChunks, md2.NumStuckChunks)\n\t}\n\t// Check NumSubDirs\n\tif md1.NumSubDirs != md2.NumSubDirs {\n\t\treturn fmt.Errorf(\"NumSubDirs not equal, %v and %v\", md1.NumSubDirs, md2.NumSubDirs)\n\t}\n\t// Check StuckHealth\n\tif md1.StuckHealth != md2.StuckHealth {\n\t\treturn fmt.Errorf(\"stuck healths not equal, %v and %v\", md1.StuckHealth, md2.StuckHealth)\n\t}\n\treturn nil\n}", "func typeEquality(t1, t2 reflect.Type, all bool) error {\n\tt1Fields, t2Fields := make(map[string]bool), make(map[string]bool)\n\tfor i := 0; i < t1.NumField(); i++ {\n\t\tt1Fields[t1.Field(i).Name] = true\n\t}\n\tfor i := 0; i < t2.NumField(); i++ {\n\t\tt2Fields[t2.Field(i).Name] = true\n\t}\n\n\t// Only compare all fields if 'all' is set to true\n\t// If this is set to false, it effectively only checks that all fields\n\t// in t1 are present in t2\n\tif all {\n\t\tif !reflect.DeepEqual(t1Fields, t2Fields) {\n\t\t\treturn fmt.Errorf(\"type = %+v, want %+v\", t1Fields, t2Fields)\n\t\t}\n\t}\n\n\tfor n := range t1Fields {\n\t\tf1, _ := t1.FieldByName(n)\n\t\tf2, _ := t2.FieldByName(n)\n\t\tif err := compareFields(f1, f2); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestColumnMatching(t *testing.T) {\n\tvar tests = []identityTest{\n\t\t{\n\t\t\tname: \"extra unmatched columns\",\n\t\t\tleft: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"a\", enc: val.DatetimeEnc},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tright: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"b\", enc: val.GeometryEnc},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatches: []match{\n\t\t\t\t{\n\t\t\t\t\tleftTbl: \"t\", rightTbl: \"t\",\n\t\t\t\t\tcolumnMatches: [][2]string{\n\t\t\t\t\t\t{\"pk\", \"pk\"},\n\t\t\t\t\t\t// columns 'a', 'b' unmatched\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"unmatched columns with name collision\",\n\t\t\tleft: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"c0\", enc: val.YearEnc},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tright: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"c0\", enc: val.JSONEnc},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatches: []match{\n\t\t\t\t{\n\t\t\t\t\tleftTbl: \"t\", rightTbl: \"t\",\n\t\t\t\t\tcolumnMatches: [][2]string{\n\t\t\t\t\t\t{\"pk\", \"pk\"},\n\t\t\t\t\t\t// columns 'c0', 'c0' unmatched\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"heuristic column matching\",\n\t\t\tleft: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"a\", enc: val.Int64Enc, sample: []int{1, 2, 3, 4, 5}},\n\t\t\t\t\t\t{name: \"b\", enc: val.Int64Enc, sample: []int{6, 7, 8, 9, 10}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tright: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"pk\", enc: val.Int32Enc, pk: true},\n\t\t\t\t\t\t{name: \"x\", enc: val.Int64Enc, sample: []int{1, 2, 3, -4, -5}},\n\t\t\t\t\t\t{name: \"y\", enc: val.Int64Enc, sample: []int{6, 7, -8, -9, -10}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatches: []match{\n\t\t\t\t{\n\t\t\t\t\tleftTbl: \"t\", rightTbl: \"t\",\n\t\t\t\t\tcolumnMatches: [][2]string{\n\t\t\t\t\t\t{\"pk\", \"pk\"},\n\t\t\t\t\t\t{\"a\", \"x\"},\n\t\t\t\t\t\t// columns 'b', 'y' unmatched\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"keyless table union\",\n\t\t\tleft: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"c0\", enc: val.Int32Enc, sample: []int{1, 2, 3, 4}},\n\t\t\t\t\t\t{name: \"c1\", enc: val.Int32Enc, sample: []int{5, 6, 7, 8}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tright: []table{\n\t\t\t\t{\n\t\t\t\t\tname: \"t\",\n\t\t\t\t\tcols: []column{\n\t\t\t\t\t\t{name: \"c0\", enc: val.Int32Enc, sample: []int{1, 2, 3, 4}},\n\t\t\t\t\t\t{name: \"c2\", enc: val.Int32Enc, sample: []int{5, 6, 7, 8}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatches: []match{\n\t\t\t\t{\n\t\t\t\t\tleftTbl: \"t\", rightTbl: \"t\",\n\t\t\t\t\tcolumnMatches: [][2]string{\n\t\t\t\t\t\t{\"c0\", \"c0\"},\n\t\t\t\t\t\t// columns 'c1', 'c2' unmatched\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ttestIdentity(t, test)\n\t\t})\n\t}\n}", "func testEqField(a, b []zapcore.Field) bool {\n\n\tif a == nil && b == nil {\n\t\treturn true\n\t}\n\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\ttemp := false\n\tfor _, i := range a {\n\t\tfor _, j := range b {\n\t\t\tif i != j {\n\t\t\t\ttemp = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttemp = true\n\t\t\tbreak\n\t\t}\n\t\tif !temp {\n\t\t\treturn temp\n\t\t}\n\t}\n\n\treturn temp\n}", "func metadataMatches(currentMetadata metav1.ObjectMeta, desiredMetadata metav1.ObjectMeta) bool {\n\treturn containsAll(currentMetadata.Labels, desiredMetadata.Labels) && containsAll(currentMetadata.Annotations, desiredMetadata.Annotations)\n}", "func (q *QueryItem) MustSame(q1 *QueryItem) error {\n\tif (q == nil) != (q1 == nil) {\n\t\treturn errors.Errorf(\"one is nil but another is not, self: %t, another: %t\", q == nil, q1 == nil)\n\t}\n\n\tif q.Null != q1.Null {\n\t\treturn errors.Errorf(\"one is NULL but another is not, self: %t, another: %t\", q.Null, q1.Null)\n\t}\n\n\tif q.ValType.Name() != q1.ValType.Name() {\n\t\treturn errors.Errorf(\"column type diff, self: %s, another: %s\", q.ValType.Name(), q1.ValType.Name())\n\t}\n\n\tif q.ValString != q1.ValString {\n\t\treturn errors.Errorf(\"column data diff, self: %s, another: %s\", q.ValString, q1.ValString)\n\t}\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that a DOH response is returned correctly.
func TestResponse(t *testing.T) { doh, _ := NewTransport(testURL, ips, nil, nil, nil) transport := doh.(*transport) rt := makeTestRoundTripper() transport.client.Transport = rt // Fake server. go func() { <-rt.req r, w := io.Pipe() rt.resp <- &http.Response{ StatusCode: 200, Body: r, Request: &http.Request{URL: parsedURL}, } // The DOH response should have a zero query ID. var modifiedQuery dnsmessage.Message = simpleQuery modifiedQuery.Header.ID = 0 w.Write(mustPack(&modifiedQuery)) w.Close() }() resp, err := doh.Query(simpleQueryBytes) if err != nil { t.Error(err) } // Parse the response as a DNS message. respParsed := mustUnpack(resp) // Query() should reconstitute the query ID in the response. if respParsed.Header.ID != simpleQuery.Header.ID || !queriesMostlyEqual(*respParsed, simpleQuery) { t.Errorf("Unexpected response %v", resp) } }
[ "func CheckResponse(r *http.Response) error {\n\tswitch r.StatusCode {\n\tcase 200, 201, 202, 204, 304:\n\t\treturn nil\n\t}\n\n\terrorResponse := &ErrorResponse{Response: r}\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err == nil && data != nil {\n\t\tvar raw interface{}\n\t\tif err := json.Unmarshal(data, &raw); err != nil {\n\t\t\terrorResponse.Message = \"failed to parse unknown error format\"\n\t\t}\n\n\t\terrorResponse.Message = fhir.ParseError(raw)\n\t}\n\n\treturn errorResponse\n}", "func containsDIDDocument(resp *http.Response) bool {\n\treturn resp.StatusCode == http.StatusOK && resp.Header.Get(\"Content-type\") == \"application/did+ld+json\"\n}", "func checkResponse(r io.Reader) error {\n\tresponse, err := ParseResponse(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.IsFailure() {\n\t\treturn errors.New(response.GetMessage())\n\t}\n\n\treturn nil\n\n}", "func checkResponse(t *testing.T, resp *http.Response, err error) {\n\tassert.Nil(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n}", "func CheckResponse(body *[]byte) (err error) {\n\n\tpre := new(PxgRetError)\n\n\tdecErr := json.Unmarshal(*body, &pre)\n\n\tif decErr == io.EOF {\n\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t}\n\tif decErr != nil {\n\t\terr = decErr\n\t}\n\n\tif pre.Error != nil {\n\t\terr = pre.Error\n\t}\n\n\treturn err\n}", "func notExistentDID(resp *http.Response) bool {\n\treturn resp.StatusCode == http.StatusNotFound\n}", "func CheckResponse(r *http.Response) error {\n\tif r.StatusCode == http.StatusOK {\n\t\treturn nil\n\t}\n\n\tresp := new(ErrorResponse)\n\n\tif r.StatusCode == http.StatusInternalServerError || r.StatusCode == http.StatusNotFound {\n\t\treturn resp\n\t}\n\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal(data, resp); err != nil {\n\t\treturn err\n\t}\n\n\treturn resp\n}", "func isInvalidResponse(response DownloadUriResponse) bool {\n\tif response.DownloadSessionId == \"\" || response.FileUri == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestResponseValid(t *testing.T) {\n\tt.Run(\"Single JSON\", testResponseSingleJSON)\n\tt.Run(\"Single String\", testResponseSingleString)\n\tt.Run(\"Multiple Objects\", testResponseMultObj)\n\tt.Run(\"Multiple IDs\", testResponseMultID)\n\tt.Run(\"Geofence\", testResponseFence)\n\tt.Run(\"Server Error\", testResponseSrvErr)\n}", "func (cl *RestClient) CheckResponse() {\n\tfor i := range cl.messages {\n\t\tcl.messages[i] = RemoveTime(cl.messages[i])\n\t}\n\tif len(cl.res.Results) != len(cl.messages) {\n\t\tcl.test.Errorf(\"Results # != Messages #\")\n\t\treturn\n\t}\n\tfor i := range cl.res.Results {\n\t\tif cl.res.Results[i] != cl.messages[i] {\n\t\t\tcl.test.Errorf(\"Rest CheckResponse got %v want %v.\", cl.messages[i], cl.res.Results[i])\n\t\t\tcl.test.Errorf(\"Name: %v\\nResults: %v\\nMessages: %v\\n\", cl.name, cl.res.Results, cl.messages)\n\t\t\tfor x := range cl.res.Results {\n\t\t\t\tcl.test.Errorf(\"\\nResult: %v\\nMessage: %v\\n\\n\\n\", cl.res.Results[x], cl.messages[x])\n\t\t\t}\n\t\t\tcl.test.Errorf(\"\\nResult: %v\", cl.res.Results[len(cl.res.Results)-1])\n\t\t\tcl.test.Errorf(\"\\nResult#: %v Message#: %v\\n\", len(cl.res.Results), len(cl.messages))\n\t\t\tbreak\n\t\t}\n\t}\n}", "func CheckResponse(r *http.Response) error {\n\tif c := r.StatusCode; 200 <= c && c <= 299 {\n\t\treturn nil\n\t}\n\terrorResponse := &ErrorResponse{Response: r}\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err == nil && data != nil {\n\t\tjson.Unmarshal(data, errorResponse)\n\t}\n\treturn errorResponse\n}", "func ValidateResponse(res *http.Response) (err error) {\n\tvar resLength int\n\t// non 200 errors\n\tif res.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Received %d status code\\n\", res.StatusCode)\n\t} else if res.Header[\"Content-Type\"][0] != \"application/json\" {\n\t\terr = fmt.Errorf(\"Content type not spplication/json. Received => %s\\n\", res.Header[\"Content-Type\"][0])\n\t} else {\n\t\tif len(res.Header[\"Content-Length\"]) > 0 {\n\t\t\tresLength, err = strconv.Atoi(res.Header[\"Content-Length\"][0])\n\t\t\tif err == nil && resLength < (CONTENT_LENGTH-100) || resLength > (CONTENT_LENGTH+100) {\n\t\t\t\terr = fmt.Errorf(\"content-Length mismatch 905 vs %d\\n\", resLength)\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func CheckResponse(r *http.Response) error {\n\tif c := r.StatusCode; 200 <= c && c <= 299 {\n\t\treturn nil\n\t}\n\n\terrorResponse := &ErrorResponse{Response: r}\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err == nil && data != nil {\n\t\tjson.Unmarshal(data, &errorResponse.ErrorStatus)\n\t}\n\n\treturn errorResponse\n}", "func checkResponse(r *http.Response) error {\n\tif r.StatusCode >= 200 && r.StatusCode <= 299 {\n\t\treturn nil\n\t}\n\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(data) == 0 {\n\t\treturn fmt.Errorf(\"%v %v: empty error body\", r.Request.Method, r.Request.URL)\n\t}\n\n\terrResp := new(errorResponse)\n\terr = json.Unmarshal(data, errResp)\n\tif err != nil {\n\t\terrResp.Message = string(data)\n\t}\n\n\tif r.StatusCode == 401 {\n\t\tswitch errResp.Code {\n\t\tcase \"expired_auth_token\":\n\t\t\treturn ErrExpiredToken\n\t\tcase \"unauthorized\":\n\t\t\treturn ErrUnauthorized\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"%v %v %v %v: %v %v\", r.Proto, r.StatusCode, r.Request.Method, r.Request.URL, errResp.Code, errResp.Message)\n}", "func checkResp(resp *http.Response, err error) (*http.Response, error) {\n\t// If err is already set, we can't connect to the endpoint.\n\tif err != nil {\n\t\treturn resp, fmt.Errorf(\"Can't connect to AppCatalyst endpoint, make sure the REST API daemon is active\")\n\t}\n\n\tswitch i := resp.StatusCode; {\n\t// Valid request, return the response.\n\tcase i == 200 || i == 201 || i == 202 || i == 204:\n\t\treturn resp, nil\n\t\t// Invalid request, parse the XML error returned and return it.\n\tcase i == 400 || i == 401 || i == 403 || i == 404 || i == 405 || i == 406 || i == 408 || i == 409 || i == 415 || i == 500 || i == 503 || i == 504:\n\t\treturn nil, parseErr(resp)\n\t// Unhandled response.\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled API response, please report this issue, status code: %s\", resp.Status)\n\t}\n}", "func ValidateResponse(response *resty.Response, err error) bool {\n\tvar validation bool\n\n\tif response.RawResponse.StatusCode != 200 {\n\t\tlog.Println(response.RawResponse.Status + \" \" + response.Request.URL)\n\t\tvalidation = false\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\tvalidation = false\n\t} else {\n\t\tvalidation = true\n\t}\n\n\treturn validation\n}", "func (dr *DeleteResponse) IsOk() bool {\n\treturn dr.ok\n}", "func (c *Checker) checkDown(resp *http.Response) error {\n\t// Check status code\n\tvar validStatus map[int]bool\n\tif c.UpStatus > 0 {\n\t\t// Explicit match against expected UpStatus\n\t\tvalidStatus = map[int]bool{\n\t\t\tc.UpStatus: true,\n\t\t}\n\t} else {\n\t\t// Treat 200-204 as successful\n\t\tvalidStatus = map[int]bool{\n\t\t\thttp.StatusOK: true,\n\t\t\thttp.StatusCreated: true,\n\t\t\thttp.StatusAccepted: true,\n\t\t\thttp.StatusNonAuthoritativeInfo: true,\n\t\t\thttp.StatusNoContent: true,\n\t\t}\n\t}\n\tif !validStatus[resp.StatusCode] {\n\t\treturn fmt.Errorf(\"response status %s\", resp.Status)\n\t}\n\n\t// Check response body\n\tif c.MustContain == \"\" && c.MustNotContain == \"\" {\n\t\treturn nil\n\t}\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"reading response body: %w\", err)\n\t}\n\tbody := string(bodyBytes)\n\tif c.MustContain != \"\" && !strings.Contains(body, c.MustContain) {\n\t\treturn fmt.Errorf(\"response does not contain '%s'\", c.MustContain)\n\t}\n\tif c.MustNotContain != \"\" && strings.Contains(body, c.MustNotContain) {\n\t\treturn fmt.Errorf(\"response contains '%s'\", c.MustNotContain)\n\t}\n\n\treturn nil\n}", "func (resp *Response) OK() bool {\n\treturn resp.StatusCode < 400\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulate an empty response. (This is not a compliant server behavior.)
func TestEmptyResponse(t *testing.T) { doh, _ := NewTransport(testURL, ips, nil, nil, nil) transport := doh.(*transport) rt := makeTestRoundTripper() transport.client.Transport = rt // Fake server. go func() { <-rt.req // Make an empty body. r, w := io.Pipe() w.Close() rt.resp <- &http.Response{ StatusCode: 200, Body: r, Request: &http.Request{URL: parsedURL}, } }() _, err := doh.Query(simpleQueryBytes) var qerr *queryError if err == nil { t.Error("Empty body should cause an error") } else if !errors.As(err, &qerr) { t.Errorf("Wrong error type: %v", err) } else if qerr.status != BadResponse { t.Errorf("Wrong error status: %d", qerr.status) } }
[ "func CreateEmptyResponse(w http.ResponseWriter) {\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (r *Responder) NoContent() { r.write(http.StatusNoContent) }", "func RespondEmpty(w http.ResponseWriter, code int) {\n\tw.Header().Set(\"X-XSS-Protection\", \"1; mode=block\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Header().Set(\"X-Frame-Options\", \"DENY\")\n\tw.WriteHeader(code)\n\tw.Write(nil)\n}", "func newEmptyResponse() *Response {\n\treturn &Response{\n\t\tBody: &HTTPResponse{},\n\t\tError: &HTTPResponse{},\n\t}\n}", "func TestEmptyReply(t *testing.T) {\n\t// Initialize webwire server given only the request\n\tserver := setupServer(\n\t\tt,\n\t\t&serverImpl{\n\t\t\tonRequest: func(\n\t\t\t\t_ context.Context,\n\t\t\t\t_ wwr.Connection,\n\t\t\t\t_ wwr.Message,\n\t\t\t) (wwr.Payload, error) {\n\t\t\t\t// Return empty reply\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\twwr.ServerOptions{},\n\t)\n\n\t// Initialize client\n\tclient := newCallbackPoweredClient(\n\t\tserver.Addr().String(),\n\t\twebwireClient.Options{\n\t\t\tDefaultRequestTimeout: 2 * time.Second,\n\t\t},\n\t\tcallbackPoweredClientHooks{},\n\t)\n\n\tif err := client.connection.Connect(); err != nil {\n\t\tt.Fatalf(\"Couldn't connect: %s\", err)\n\t}\n\n\t// Send request and await reply\n\treply, err := client.connection.Request(\n\t\tcontext.Background(),\n\t\t\"\",\n\t\twwr.NewPayload(wwr.EncodingBinary, []byte(\"test\")),\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"Request failed: %s\", err)\n\t}\n\n\t// Verify reply is empty\n\treplyEncoding := reply.Encoding()\n\tif replyEncoding != wwr.EncodingBinary {\n\t\tt.Fatalf(\n\t\t\t\"Expected empty binary reply, but encoding was: %s\",\n\t\t\treplyEncoding.String(),\n\t\t)\n\t}\n\treplyData := reply.Data()\n\tif len(replyData) > 0 {\n\t\tt.Fatalf(\"Expected empty binary reply, but payload was: %v\", replyData)\n\t}\n}", "func emptyHandler(w http.ResponseWriter, req *http.Request) {}", "func emptyHandler(_ http.ResponseWriter, _ *http.Request) {\n\n}", "func NoContent() Response {\n\treturn Response{\n\t\tStatusCode: http.StatusNoContent,\n\t}\n}", "func withEmpty() option {\n\treturn func(ctx *fasthttp.RequestCtx) {\n\t\tctx.Response.SetBody(nil)\n\t\tctx.Response.SetStatusCode(fasthttp.StatusNoContent)\n\t}\n}", "func (r Response) NoContent(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.NoContent, payload, header...)\n}", "func writeSuccessNoContent(w http.ResponseWriter) {\n\twriteResponse(w, http.StatusNoContent, nil, mimeNone)\n}", "func doNothing(w http.ResponseWriter, r *http.Request) {}", "func Null() Decorator {\n\treturn func(c Client) Client {\n\t\treturn ClientFunc(func(*http.Request) (*http.Response, error) {\n\t\t\treturn &http.Response{\n\t\t\t\tStatus: http.StatusText(http.StatusNoContent),\n\t\t\t\tStatusCode: http.StatusNoContent,\n\t\t\t\tProto: \"HTTP/1.1\",\n\t\t\t\tProtoMajor: 1,\n\t\t\t\tProtoMinor: 1,\n\t\t\t\tHeader: make(map[string][]string),\n\t\t\t\tContentLength: 0,\n\t\t\t}, nil\n\t\t})\n\t}\n}", "func dummyServerResponse(w http.ResponseWriter, r *http.Request) {\n\tw.Write(dummyBytes())\n}", "func TestServeMuxHandleNoResponse(t *testing.T) {\n\tmux := dhcp6server.NewServeMux()\n\n\tr, err := dhcp6server.ParseRequest([]byte{1, 1, 2, 3}, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tw := dhcp6test.NewRecorder(r.TransactionID)\n\tmux.ServeDHCP(w, r)\n\n\tif mt := w.MessageType; mt != dhcp6.MessageType(0) {\n\t\tt.Fatalf(\"reply packet empty, but got message type: %v\", mt)\n\t}\n\tif l := len(w.Options()); l > 0 {\n\t\tt.Fatalf(\"reply packet empty, but got %d options\", l)\n\t}\n}", "func (w *ResponseWriter) NoContent() Result {\n\tif w.written {\n\t\tpanic(\"ResponseWriter was already written to\")\n\t}\n\tw.handler.commitPhase(w, NoContentResponse{})\n\tif w.written {\n\t\treturn Result{}\n\t}\n\tw.markWritten()\n\tw.rw.WriteHeader(int(StatusNoContent))\n\treturn Result{}\n}", "func CreateNoopResponse() Response {\n\treturn Response{\n\t\tRespType: RespNoop,\n\t}\n}", "func (x *Rest) replyNoContent(w *http.ResponseWriter, q *msg.Request) {\n\tresult := msg.FromRequest(q)\n\tresult.NoContent()\n\tx.respond(w, &result)\n}", "func TestRequestEmpty(t *testing.T) {\n\t// Initialize server\n\tserver := setupServer(\n\t\tt,\n\t\t&serverImpl{\n\t\t\tonRequest: func(\n\t\t\t\t_ context.Context,\n\t\t\t\t_ webwire.Connection,\n\t\t\t\tmsg webwire.Message,\n\t\t\t) (webwire.Payload, error) {\n\t\t\t\t// Expect the following request to not even arrive\n\t\t\t\tt.Error(\"Not expected but reached\")\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\twebwire.ServerOptions{},\n\t)\n\n\t// Initialize client\n\tclient := newCallbackPoweredClient(\n\t\tserver.Addr().String(),\n\t\twebwireClient.Options{\n\t\t\tDefaultRequestTimeout: 2 * time.Second,\n\t\t},\n\t\tcallbackPoweredClientHooks{},\n\t)\n\n\t// Send request without a name and without a payload.\n\t// Expect a protocol error in return not sending the invalid request off\n\t_, err := client.connection.Request(context.Background(), \"\", nil)\n\tif _, isProtoErr := err.(webwire.ProtocolErr); !isProtoErr {\n\t\tt.Fatalf(\"Expected a protocol error, got: %v\", err)\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if DoH resolver IPs are confirmed and disconfirmed when queries suceeded and fail, respectively.
func TestDohIPConfirmDisconfirm(t *testing.T) { u, _ := url.Parse(testURL) doh, _ := NewTransport(testURL, ips, nil, nil, nil) transport := doh.(*transport) hostname := u.Hostname() ipmap := transport.ips.Get(hostname) // send a valid request to first have confirmed-ip set res, _ := doh.Query(simpleQueryBytes) mustUnpack(res) ip1 := ipmap.Confirmed() if ip1 == nil { t.Errorf("IP not confirmed despite valid query to %s", u) } // simulate http-fail with doh server-ip set to previously confirmed-ip rt := makeTestRoundTripper() transport.client.Transport = rt go func() { req := <-rt.req trace := httptrace.ContextClientTrace(req.Context()) trace.GotConn(httptrace.GotConnInfo{ Conn: &fakeConn{ remoteAddr: &net.TCPAddr{ IP: ip1, // confirmed-ip from before Port: 443, }}}) rt.resp <- &http.Response{ StatusCode: 509, // some non-2xx status Body: nil, Request: &http.Request{URL: u}, } }() doh.Query(simpleQueryBytes) ip2 := ipmap.Confirmed() if ip2 != nil { t.Errorf("IP confirmed (%s) despite err", ip2) } }
[ "func Confirm(client *http.Client, remoteip, challenge, response string) (result bool) {\n\tresult = strings.HasPrefix(check(client,remoteip, challenge, response), \"true\")\n\treturn\n}", "func TestWhoisQuery(t *testing.T) {\n\t// Retry WhoisQuery up to 3 times for network timeout errors.\n\tfor i := 0; i < 3; i++ {\n\t\tres, err := WhoisQuery(\"koding.com\", \"whois.arin.net\", 5*time.Second)\n\t\tif e, ok := err.(net.Error); ok && e.Timeout() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif res == \"\" {\n\t\t\tt.Fatal(\"Whois response empty.\")\n\t\t}\n\n\t\t// Use a the street name to validate the response\n\t\tif regexp.MustCompile(`(?i)brannan`).MatchString(res) != true {\n\t\t\tt.Fatal(\"Response does not match as expected.\" +\n\t\t\t\t`Wanted the regexp \"brannan\" to match`)\n\t\t}\n\n\t\treturn\n\t}\n\n\tt.Fatal(\"exceeded max retry attempts for WhoisQuery\")\n}", "func (f *tastFixtureImpl) dutHealthCheck(ctx context.Context, d *dut.DUT, rpcHint *testing.RPCHint) error {\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// We create a new gRPC session here to exclude broken gRPC case and save reboots when\n\t// the DUT is healthy but the gRPC is broken.\n\trpcClient, err := rpc.Dial(ctx, d, rpcHint)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot create gRPC client\")\n\t}\n\tdefer rpcClient.Close(ctx)\n\n\twifiClient := wifi.NewShillServiceClient(rpcClient.Conn)\n\tif _, err := wifiClient.HealthCheck(ctx, &empty.Empty{}); err != nil {\n\t\treturn errors.Wrap(err, \"health check failed\")\n\t}\n\treturn nil\n}", "func (ndp *ndpState) doDuplicateAddressDetection(addr tcpip.Address, remaining uint8, ref *referencedNetworkEndpoint) (bool, *tcpip.Error) {\n\tif ref.getKind() != permanentTentative {\n\t\t// The endpoint should still be marked as tentative\n\t\t// since we are still performing DAD on it.\n\t\tpanic(fmt.Sprintf(\"ndpdad: addr %s is not tentative on NIC(%d)\", addr, ndp.nic.ID()))\n\t}\n\n\tif remaining == 0 {\n\t\t// DAD has resolved.\n\t\tref.setKind(permanent)\n\t\treturn true, nil\n\t}\n\n\t// Send a new NS.\n\tsnmc := header.SolicitedNodeAddr(addr)\n\tsnmcRef, ok := ndp.nic.endpoints[NetworkEndpointID{snmc}]\n\tif !ok {\n\t\t// This should never happen as if we have the\n\t\t// address, we should have the solicited-node\n\t\t// address.\n\t\tpanic(fmt.Sprintf(\"ndpdad: NIC(%d) is not in the solicited-node multicast group (%s) but it has addr %s\", ndp.nic.ID(), snmc, addr))\n\t}\n\n\t// Use the unspecified address as the source address when performing\n\t// DAD.\n\tr := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, snmc, ndp.nic.linkEP.LinkAddress(), snmcRef, false, false)\n\n\thdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6NeighborSolicitMinimumSize)\n\tpkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborSolicitMinimumSize))\n\tpkt.SetType(header.ICMPv6NeighborSolicit)\n\tns := header.NDPNeighborSolicit(pkt.NDPPayload())\n\tns.SetTargetAddress(addr)\n\tpkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n\n\tsent := r.Stats().ICMP.V6PacketsSent\n\tif err := r.WritePacket(nil, hdr, buffer.VectorisedView{}, NetworkHeaderParams{Protocol: header.ICMPv6ProtocolNumber, TTL: header.NDPHopLimit, TOS: DefaultTOS}); err != nil {\n\t\tsent.Dropped.Increment()\n\t\treturn false, err\n\t}\n\tsent.NeighborSolicit.Increment()\n\n\treturn false, nil\n}", "func (c *Checker) connectionTest() {\n\tfor i := range c.DNSList {\n\t\t_, err := net.LookupAddr(c.DNSList[i])\n\t\tif err == nil {\n\t\t\tc.Lock()\n\t\t\tif !c.connected {\n\t\t\t\tlog.Warnf(\"Internet connectivity re-established\")\n\t\t\t\tc.connected = true\n\t\t\t}\n\t\t\tc.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor i := range c.DomainList {\n\t\t_, err := net.LookupHost(c.DomainList[i])\n\t\tif err == nil {\n\t\t\tc.Lock()\n\t\t\tif !c.connected {\n\t\t\t\tlog.Warnf(\"Internet connectivity re-established\")\n\t\t\t\tc.connected = true\n\t\t\t}\n\t\t\tc.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.Lock()\n\tif c.connected {\n\t\tlog.Warnf(\"Internet connectivity lost\")\n\t\tc.connected = false\n\t}\n\tc.Unlock()\n}", "func TestHealthCheckControlsQueryService(t *testing.T) {\n\t// we need an actual grace period set, so lameduck is enabled\n\t*gracePeriod = 10 * time.Millisecond\n\tdefer func() {\n\t\t*gracePeriod = 0\n\t}()\n\n\tctx := context.Background()\n\tagent := createTestAgent(ctx, t, nil)\n\n\t/// Consume the first health broadcast triggered by ActionAgent.Start():\n\t// (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we\n\t// should be serving.\n\tif _, err := expectBroadcastData(agent.QueryServiceControl, true, \"healthcheck not run yet\", 0); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !agent.QueryServiceControl.IsServing() {\n\t\tt.Errorf(\"Query service should be running\")\n\t}\n\tif !agent.UpdateStream.IsEnabled() {\n\t\tt.Errorf(\"UpdateStream should be running\")\n\t}\n\n\t// first health check, should keep us as replica and serving,\n\t// and update the mysql port to 3306\n\tbefore := time.Now()\n\tagent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 12 * time.Second\n\tagent.runHealthCheck()\n\tti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)\n\tif err != nil {\n\t\tt.Fatalf(\"GetTablet failed: %v\", err)\n\t}\n\tif ti.Type != topodatapb.TabletType_REPLICA {\n\t\tt.Errorf(\"First health check failed to go to replica: %v\", ti.Type)\n\t}\n\tif port := topoproto.MysqlPort(ti.Tablet); port != 3306 {\n\t\tt.Errorf(\"First health check failed to update mysql port: %v\", port)\n\t}\n\tif !agent.gotMysqlPort {\n\t\tt.Errorf(\"Healthcheck didn't record it updated the MySQL port.\")\n\t}\n\tif !agent.QueryServiceControl.IsServing() {\n\t\tt.Errorf(\"Query service should be running\")\n\t}\n\tif !agent.UpdateStream.IsEnabled() {\n\t\tt.Errorf(\"UpdateStream should be running\")\n\t}\n\tif agent._healthyTime.Sub(before) < 0 {\n\t\tt.Errorf(\"runHealthCheck did not update agent._healthyTime\")\n\t}\n\tif agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType != topodatapb.TabletType_REPLICA {\n\t\tt.Errorf(\"invalid tabletserver target: %v\", agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType)\n\t}\n\tif _, err := expectBroadcastData(agent.QueryServiceControl, true, \"\", 12); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// now make the tablet unhealthy\n\tagent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 13 * time.Second\n\tagent.HealthReporter.(*fakeHealthCheck).reportError = fmt.Errorf(\"tablet is unhealthy\")\n\tbefore = time.Now()\n\tagent.runHealthCheck()\n\tti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)\n\tif err != nil {\n\t\tt.Fatalf(\"GetTablet failed: %v\", err)\n\t}\n\tif ti.Type != topodatapb.TabletType_REPLICA {\n\t\tt.Errorf(\"Unhappy health check failed to stay as replica: %v\", ti.Type)\n\t}\n\tif agent.QueryServiceControl.IsServing() {\n\t\tt.Errorf(\"Query service should not be running\")\n\t}\n\tif agent.UpdateStream.IsEnabled() {\n\t\tt.Errorf(\"UpdateStream should not be running\")\n\t}\n\tif agent._healthyTime.Sub(before) < 0 {\n\t\tt.Errorf(\"runHealthCheck did not update agent._healthyTime\")\n\t}\n\tif got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {\n\t\tt.Errorf(\"invalid tabletserver target: got = %v, want = %v\", got, topodatapb.TabletType_REPLICA)\n\t}\n\n\t// first we get the lameduck broadcast, with no error and old\n\t// replication delay\n\tif _, err := expectBroadcastData(agent.QueryServiceControl, false, \"\", 12); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// then query service is disabled since we are unhealthy now.\n\tif err := expectStateChange(agent.QueryServiceControl, false, topodatapb.TabletType_REPLICA); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// and the associated broadcast\n\tif _, err := expectBroadcastData(agent.QueryServiceControl, false, \"tablet is unhealthy\", 13); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// and nothing more.\n\tif err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s host\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\taddr, err := net.ResolveIPAddr(\"ip\", os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(\"Resolution error: \", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tconn, err := net.DialIP(\"ip4:icmp\", addr, addr)\n\tcheckError(err)\n\n\tvar msg [512]byte\n\tmsg[0] = 8 // echo\n\n\tmsg[1] = 0\n\n\tmsg[2] = 0\n\tmsg[3] = 0\n\n\tmsg[4] = 0\n\tmsg[5] = 13\n\n\tmsg[6] = 0\n\tmsg[7] = 37\n\n\tlen := 8\n\n\tcheck := checkSum(msg[0:len])\n\tmsg[2] = byte(check >> 8)\n\tmsg[3] = byte(check & 255)\n\t_, err = conn.Write(msg[0:len])\n\tcheckError(err)\n\t_, err = conn.Read(msg[0:])\n\tcheckError(err)\n\n\tfmt.Println(\"got response\")\n\n\tif msg[5] == 13 {\n\t\tfmt.Println(\"indentifier matches\")\n\t}\n\n\tif msg[7] == 37 {\n\t\tfmt.Println(\"sequence matches\")\n\t}\n\n\tos.Exit(0)\n}", "func handleHealthCheck(m *MicroService, d *net.Dialer) bool {\r\n\tchange := false\r\n\tfor i, inst := range m.Instances {\r\n\t\t_, err := d.Dial(\"tcp\", inst.Host)\r\n\t\tif err != nil {\r\n\t\t\tif !m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, true)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as DOWN\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif m.isBlacklisted(i) {\r\n\t\t\t\tm.blackList(i, false)\r\n\t\t\t\tlogInfo(\"Instance: \" + inst.Host + \" is now marked as UP\")\r\n\t\t\t\tchange = true\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn change\r\n}", "func IPIsDoHOnlyServer(ip netip.Addr) bool {\n\treturn nextDNSv6RangeA.Contains(ip) || nextDNSv6RangeB.Contains(ip) ||\n\t\tnextDNSv4RangeA.Contains(ip) || nextDNSv4RangeB.Contains(ip)\n}", "func (dc *Checker) doChecks() error {\n\n\tlog.Infoln(\"DNS Status check testing hostname:\", dc.Hostname)\n\n\t// if there's a label selector, do checks against endpoints\n\tif len(labelSelector) > 0 {\n\t\terr := dc.checkEndpoints()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// otherwise do lookup against service endpoint\n\t_, err := net.LookupHost(dc.Hostname)\n\tif err != nil {\n\t\terrorMessage := \"DNS Status check determined that \" + dc.Hostname + \" is DOWN: \" + err.Error()\n\t\tlog.Errorln(errorMessage)\n\t\treturn errors.New(errorMessage)\n\t}\n\tlog.Infoln(\"DNS Status check from service endpoint determined that\", dc.Hostname, \"was OK.\")\n\treturn nil\n}", "func CheckHost(ip *netip.Addr, cfg *pb.Config) (*pb.ServerStatus, *ntp.Response, error) {\n\n\tlog := logger.Setup()\n\n\tif cfg.Samples == 0 {\n\t\tcfg.Samples = 3\n\t}\n\n\topts := ntp.QueryOptions{\n\t\tTimeout: 3 * time.Second,\n\t}\n\n\tconfigIP := cfg.GetIP()\n\tif configIP != nil && configIP.IsValid() {\n\t\topts.LocalAddress = configIP.String()\n\t\tif natIP := cfg.GetNatIP(); natIP != nil && natIP.IsValid() {\n\t\t\topts.LocalAddress = natIP.String()\n\t\t}\n\t} else {\n\t\tlog.Error(\"Did not get valid local configuration IP\", \"configIP\", configIP)\n\t}\n\n\tif ip.IsLoopback() {\n\t\treturn nil, nil, fmt.Errorf(\"loopback address\")\n\t}\n\tif ip.IsPrivate() {\n\t\treturn nil, nil, fmt.Errorf(\"private address\")\n\t}\n\tif ip.IsMulticast() {\n\t\treturn nil, nil, fmt.Errorf(\"multicast address\")\n\t}\n\tif !ip.IsValid() {\n\t\treturn nil, nil, fmt.Errorf(\"invalid IP\")\n\t}\n\n\tresponses := []*response{}\n\n\tfor i := int32(0); i < cfg.Samples; i++ {\n\n\t\tif i > 0 {\n\t\t\t// minimum headway time is 2 seconds, https://www.eecis.udel.edu/~mills/ntp/html/rate.html\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\n\t\tipStr := ip.String()\n\t\tif ip.Is6() {\n\t\t\tipStr = \"[\" + ipStr + \"]:123\"\n\t\t}\n\n\t\tresp, err := ntp.QueryWithOptions(ipStr, opts)\n\t\tif err != nil {\n\t\t\tr := &response{\n\t\t\t\tStatus: &pb.ServerStatus{},\n\t\t\t}\n\t\t\tr.Status.SetIP(ip)\n\t\t\tif resp != nil {\n\t\t\t\tr.Response = resp\n\t\t\t\tr.Status = ntpResponseToStatus(ip, resp)\n\t\t\t}\n\t\t\tr.Error = err\n\t\t\tresponses = append(responses, r)\n\n\t\t\tlog.Debug(\"ntp query error\", \"host\", ip.String(), \"iteration\", i, \"error\", err)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tstatus := ntpResponseToStatus(ip, resp)\n\n\t\tlog.Debug(\"ntp query\", \"host\", ip.String(), \"iteration\", i, \"rtt\", resp.RTT.String(), \"offset\", resp.ClockOffset, \"error\", err)\n\n\t\t// if we get an explicit bad response in any of the samples, we error out\n\t\tif resp.Stratum == 0 || resp.Stratum == 16 {\n\t\t\tif len(resp.KissCode) > 0 {\n\t\t\t\tif resp.KissCode == \"RATE\" {\n\t\t\t\t\tstatus.Offset = nil\n\t\t\t\t}\n\t\t\t\treturn status, resp, fmt.Errorf(\"%s\", resp.KissCode)\n\t\t\t}\n\n\t\t\trefText := fmt.Sprintf(\"%#x\", resp.ReferenceID)\n\n\t\t\trefIDStr := referenceIDString(resp.ReferenceID)\n\t\t\tif utf8.Valid([]byte(refIDStr)) {\n\t\t\t\trefText = refText + \", \" + refIDStr\n\t\t\t}\n\n\t\t\treturn status, resp,\n\t\t\t\tfmt.Errorf(\"bad stratum %d (referenceID: %s)\",\n\t\t\t\t\tresp.Stratum, refText)\n\t\t}\n\n\t\tif resp.Stratum > 6 {\n\t\t\treturn status, resp, fmt.Errorf(\"bad stratum %d\", resp.Stratum)\n\t\t}\n\n\t\tresponses = append(responses, &response{\n\t\t\tStatus: status,\n\t\t\tResponse: resp,\n\t\t})\n\t}\n\n\tvar best *response\n\n\t// log.Printf(\"for %s we collected %d samples, now find the best result\", ip.String(), len(statuses))\n\n\t// todo: if there are more than 2 (3?) samples with an offset, throw\n\t// away the offset outlier(s)\n\n\tfor _, r := range responses {\n\n\t\t// log.Printf(\"status for %s / %d: offset: %s rtt: %s err: %q\", ip.String(), i, status.Offset.AsDuration(), status.RTT.AsDuration(), status.Error)\n\n\t\tif best == nil {\n\t\t\tbest = r\n\t\t\tcontinue\n\t\t}\n\n\t\t// todo: ... and it's otherwise a valid response?\n\t\tif (r.Error == nil && best.Error != nil) || (r.Status.RTT.AsDuration() < best.Status.RTT.AsDuration()) {\n\t\t\tbest = r\n\t\t}\n\t}\n\n\t// errLog := \"\"\n\t// if len(best.Error) > 0 {\n\t// \terrLog = fmt.Sprintf(\" err: %q\", best.Error)\n\t// }\n\t// log.Printf(\"best result for %s - offset: %s rtt: %s%s\",\n\t// \tip.String(), best.Offset.AsDuration(), best.RTT.AsDuration(), errLog)\n\n\tif best.Error != nil {\n\t\treturn best.Status, best.Response, fmt.Errorf(\"%s\", best.Error)\n\t}\n\n\treturn best.Status, best.Response, nil\n}", "func checkDHCPPacketInfo(bnNum int, packet gopacket.Packet, ctx *zedrouterContext) {\n\tvar isReplyAck, needUpdate, foundDstMac, isBroadcast bool\n\tvar vifInfo []types.VifNameMac\n\tvar netstatus types.NetworkInstanceStatus\n\tvar vifTrig types.VifIPTrig\n\n\t// use the IPAssigments of the NetworkInstanceStatus, since this is switched net\n\t// and the field will not be assigned or modified by others\n\tpub := ctx.pubNetworkInstanceStatus\n\titems := pub.GetAll()\n\tfor _, st := range items {\n\t\tnetstatus = st.(types.NetworkInstanceStatus)\n\t\tif netstatus.Type != types.NetworkInstanceTypeSwitch || netstatus.BridgeNum != bnNum {\n\t\t\tcontinue\n\t\t}\n\t\tvifInfo = netstatus.Vifs\n\t\tbreak\n\t}\n\tif len(vifInfo) == 0 { // there is no Mac on the bridge\n\t\tlog.Tracef(\"checkDHCPPacketInfo: no mac on the bridge\")\n\t\treturn\n\t}\n\n\tetherLayer := packet.Layer(layers.LayerTypeEthernet)\n\tif etherLayer != nil {\n\t\tetherPkt, _ := etherLayer.(*layers.Ethernet)\n\t\tif bytes.Compare(etherPkt.DstMAC, broadcastMAC) == 0 {\n\t\t\t// some DHCP servers send replies with broadcast MAC address,\n\t\t\t// need to check those in payload to see if it's for-us\n\t\t\tisBroadcast = true\n\t\t} else {\n\t\t\tfor _, vif := range vifInfo {\n\t\t\t\tif strings.Compare(etherPkt.DstMAC.String(), vif.MacAddr) == 0 {\n\t\t\t\t\tfoundDstMac = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !foundDstMac && !isBroadcast { // dhcp packet not for this bridge App ports\n\t\tlog.Tracef(\"checkDHCPPacketInfo: pkt no dst mac for us\\n\")\n\t\treturn\n\t}\n\n\tipLayer := packet.Layer(layers.LayerTypeIPv4)\n\tisIPv4 := (ipLayer != nil)\n\tif isIPv4 {\n\t\t// dhcp client will send discovery or request, server will send offer and Ack\n\t\t// in the code we wait for the Reply from server with Ack to confirm the client's IP address\n\t\tdhcpLayer := packet.Layer(layers.LayerTypeDHCPv4)\n\t\tif dhcpLayer != nil {\n\t\t\tdhcpv4, _ := dhcpLayer.(*layers.DHCPv4)\n\t\t\tif dhcpv4 != nil && dhcpv4.Operation == layers.DHCPOpReply {\n\t\t\t\topts := dhcpv4.Options\n\t\t\t\tfor _, opt := range opts {\n\t\t\t\t\tif opt.Type == layers.DHCPOptMessageType && int(opt.Data[0]) == int(layers.DHCPMsgTypeAck) {\n\t\t\t\t\t\tisReplyAck = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isReplyAck {\n\t\t\t\tlog.Tracef(\"checkDHCPPacketInfo: bn%d, Xid %d, clientip %s, yourclientip %s, clienthw %v, options %v\\n\",\n\t\t\t\t\tbnNum, dhcpv4.Xid, dhcpv4.ClientIP.String(), dhcpv4.YourClientIP.String(), dhcpv4.ClientHWAddr, dhcpv4.Options)\n\t\t\t\tfor _, vif := range vifInfo {\n\t\t\t\t\tif strings.Compare(vif.MacAddr, dhcpv4.ClientHWAddr.String()) == 0 {\n\t\t\t\t\t\tif _, ok := netstatus.IPAssignments[vif.MacAddr]; !ok {\n\t\t\t\t\t\t\tlog.Functionf(\"checkDHCPPacketInfo: mac %v assign new IP %v\\n\", vif.MacAddr, dhcpv4.YourClientIP)\n\t\t\t\t\t\t\tnetstatus.IPAssignments[vif.MacAddr] = dhcpv4.YourClientIP\n\t\t\t\t\t\t\tneedUpdate = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif netstatus.IPAssignments[vif.MacAddr].Equal(dhcpv4.YourClientIP) == false {\n\t\t\t\t\t\t\t\tlog.Functionf(\"checkDHCPPacketInfo: update mac %v, prev %v, now %v\\n\",\n\t\t\t\t\t\t\t\t\tvif.MacAddr, netstatus.IPAssignments[vif.MacAddr], dhcpv4.YourClientIP)\n\t\t\t\t\t\t\t\tnetstatus.IPAssignments[vif.MacAddr] = dhcpv4.YourClientIP\n\t\t\t\t\t\t\t\tneedUpdate = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvifTrig.MacAddr = vif.MacAddr\n\t\t\t\t\t\tvifTrig.IPAddr = dhcpv4.YourClientIP\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Tracef(\"checkDHCPPacketInfo: no dhcp layer\\n\")\n\t\t}\n\t} else {\n\t\t// XXX need to come back to handle ipv6 properly, including:\n\t\t// each MAC can have both ipv4 and ipv6 addresses\n\t\t// ipv6 can be stateful with DHCPv6 or stateless with autoconfig with RS/RA/etc\n\t\t// ipv6 can be link-local, global scope and rfc 4941 with many temporary addresses\n\t\t// which we don't know which one it will use and timeout\n\t\tdhcpLayer := packet.Layer(layers.LayerTypeDHCPv6)\n\t\tif dhcpLayer != nil {\n\t\t\tdhcpv6, _ := dhcpLayer.(*layers.DHCPv6)\n\t\t\tlog.Tracef(\"DHCPv6: Msgtype %v, LinkAddr %s, PeerAddr %s, Options %v\\n\",\n\t\t\t\tdhcpv6.MsgType, dhcpv6.LinkAddr.String(), dhcpv6.PeerAddr.String(), dhcpv6.Options)\n\t\t}\n\t}\n\n\tif needUpdate {\n\t\tlog.Functionf(\"checkDHCPPacketInfo: need update %v, %v\\n\", vifInfo, netstatus.IPAssignments)\n\t\tpub := ctx.pubNetworkInstanceStatus\n\t\tpub.Publish(netstatus.Key(), netstatus)\n\t\tctx.pubAppVifIPTrig.Publish(vifTrig.MacAddr, vifTrig)\n\t\tcheckAndPublishDhcpLeases(ctx)\n\t}\n}", "func performConnectivityChecks(allAddresses *[]Address) int {\n\terrCount := 0\n\ttimeout := time.Duration(1 * time.Second)\n\tfor i, oneAddress := range *allAddresses {\n\t\tfmt.Printf(\"Checking connectivity to [%s]\\n\", oneAddress.Description)\n\t\tclient := http.Client{\n\t\t\tTimeout: timeout,\n\t\t}\n\t\t_, err := client.Get(oneAddress.URL)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"unable to connect to item [%d]: [%s] with error [%v]\", i, oneAddress.Description, err)\n\t\t\terrCount++\n\t\t}\n\t}\n\n\treturn errCount\n}", "func queryDelegatorProxyCheck(dlgAddr sdk.AccAddress, expIsProxy bool, expHasProxy bool,\n\texpTotalDlgTokens *sdk.Dec, expBoundToProxy *sdk.AccAddress, expBoundDelegators []sdk.AccAddress) actResChecker {\n\treturn func(t *testing.T, beforeStatus, afterStatus IValidatorStatus, resultCtx *ActionResultCtx) bool {\n\n\t\tctx := getNewContext(resultCtx.tc.mockKeeper.MountedStore, resultCtx.tc.currentHeight)\n\n\t\t//query delegator from keeper directly\n\t\tdlg, found := resultCtx.tc.mockKeeper.Keeper.GetDelegator(ctx, dlgAddr)\n\t\trequire.True(t, found)\n\n\t\tb1 := assert.Equal(t, expIsProxy, dlg.IsProxy)\n\t\tb2 := assert.Equal(t, expHasProxy, dlg.HasProxy())\n\t\tb3 := true\n\t\tif expTotalDlgTokens != nil {\n\t\t\tb3 = assert.Equal(t, expTotalDlgTokens.String(), dlg.TotalDelegatedTokens.String(), dlg)\n\t\t}\n\n\t\tvar b4 bool\n\t\tif expBoundToProxy != nil {\n\t\t\tb4 = assert.Equal(t, *expBoundToProxy, dlg.ProxyAddress)\n\t\t} else {\n\t\t\tb4 = dlg.ProxyAddress == nil\n\t\t}\n\n\t\tb5 := true\n\t\tif expBoundDelegators != nil && len(expBoundDelegators) > 0 {\n\t\t\tq := NewQuerier(resultCtx.tc.mockKeeper.Keeper)\n\t\t\tpara := types.NewQueryDelegatorParams(dlgAddr)\n\t\t\tbz, _ := types.ModuleCdc.MarshalJSON(para)\n\t\t\tdata, err := q(ctx, []string{types.QueryProxy}, abci.RequestQuery{Data: bz})\n\t\t\trequire.NoError(t, err)\n\n\t\t\trealProxiedDelegators := []sdk.AccAddress{}\n\t\t\trequire.NoError(t, ModuleCdc.UnmarshalJSON(data, &realProxiedDelegators))\n\n\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), len(realProxiedDelegators))\n\t\t\tif b5 {\n\t\t\t\tcnt := 0\n\t\t\t\tfor _, e := range expBoundDelegators {\n\t\t\t\t\tfor _, r := range realProxiedDelegators {\n\t\t\t\t\t\tif r.Equals(e) {\n\t\t\t\t\t\t\tcnt++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb5 = assert.Equal(t, len(expBoundDelegators), cnt)\n\t\t\t}\n\t\t}\n\n\t\t// check if the shares correct\n\t\tb6 := true\n\t\tif len(dlg.GetShareAddedValidatorAddresses()) > 0 {\n\t\t\texpectDlgShares, err := keeper.SimulateWeight(getGlobalContext().BlockTime().Unix(), (dlg.TotalDelegatedTokens.Add(dlg.Tokens)))\n\t\t\tb6 = err == nil\n\t\t\tb6 = b6 && assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t} else {\n\t\t\texpectDlgShares := sdk.ZeroDec()\n\t\t\tb6 = assert.Equal(t, expectDlgShares.String(), dlg.Shares.String(), dlg)\n\t\t}\n\n\t\tconstraintCheckRes := delegatorConstraintCheck(dlg)(t, beforeStatus, afterStatus, resultCtx)\n\n\t\tr := b1 && b2 && b3 && b4 && b5 && b6 && constraintCheckRes\n\t\tif !r {\n\t\t\tresultCtx.tc.printParticipantSnapshot(resultCtx.t)\n\t\t}\n\n\t\treturn r\n\t}\n}", "func checkGossip(t *testing.T, c cluster.Cluster, d time.Duration, f checkGossipFunc) {\n\terr := util.RetryForDuration(d, func() error {\n\t\tselect {\n\t\tcase <-stopper:\n\t\t\tt.Fatalf(\"interrupted\")\n\t\t\treturn nil\n\t\tcase <-time.After(1 * time.Second):\n\t\t}\n\n\t\tvar infoStatus gossip.InfoStatus\n\t\tfor i := 0; i < c.NumNodes(); i++ {\n\t\t\tif err := util.GetJSON(cluster.HTTPClient, c.URL(i)+\"/_status/gossip/local\", &infoStatus); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := f(infoStatus.Infos); err != nil {\n\t\t\t\treturn errors.Errorf(\"node %d: %s\", i, err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tt.Fatal(errors.Errorf(\"condition failed to evaluate within %s: %s\", d, err))\n\t}\n}", "func testDns(t *testing.T) {\n\ttargetTxts := []*discovery.TxtData{\n\t\tgetTxtData(clientCluster, \"dns-client-cluster\"),\n\t\tgetTxtData(serverCluster, \"dns-server-cluster\"),\n\t}\n\n\ttxts, err := search_domain_operator.Wan(\"127.0.0.1:8053\", registryDomain, true)\n\tassert.NilError(t, err, \"Error during WAN DNS discovery\")\n\n\tassert.Equal(t, len(txts), len(targetTxts))\n\tassert.Assert(t, func() bool {\n\t\tfor _, target := range targetTxts {\n\t\t\tcontains := false\n\t\t\tfor _, txt := range txts {\n\t\t\t\tif txt.ID == target.ID && txt.ApiUrl == target.ApiUrl && txt.Namespace == target.Namespace {\n\t\t\t\t\tcontains = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !contains {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}(), \"Retrieved data does not match the expected DNS records\")\n}", "func verifyServeHostnameServiceUp(c *client.Client, ns, host string, expectedPods []string, serviceIP string, servicePort int) error {\n\texecPodName := createExecPodOrFail(c, ns, \"execpod-\")\n\tdefer func() {\n\t\tdeletePodOrFail(c, ns, execPodName)\n\t}()\n\n\t// Loop a bunch of times - the proxy is randomized, so we want a good\n\t// chance of hitting each backend at least once.\n\tbuildCommand := func(wget string) string {\n\t\treturn fmt.Sprintf(\"for i in $(seq 1 %d); do %s http://%s:%d 2>&1 || true; echo; done\",\n\t\t\t50*len(expectedPods), wget, serviceIP, servicePort)\n\t}\n\tcommands := []func() string{\n\t\t// verify service from node\n\t\tfunc() string {\n\t\t\tcmd := \"set -e; \" + buildCommand(\"wget -q --timeout=0.2 --tries=1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q on host %v\", cmd, host)\n\t\t\tresult, err := framework.SSH(cmd, host, framework.TestContext.Provider)\n\t\t\tif err != nil || result.Code != 0 {\n\t\t\t\tframework.LogSSHResult(result)\n\t\t\t\tframework.Logf(\"error while SSH-ing to node: %v\", err)\n\t\t\t}\n\t\t\treturn result.Stdout\n\t\t},\n\t\t// verify service from pod\n\t\tfunc() string {\n\t\t\tcmd := buildCommand(\"wget -q -T 1 -O -\")\n\t\t\tframework.Logf(\"Executing cmd %q in pod %v/%v\", cmd, ns, execPodName)\n\t\t\t// TODO: Use exec-over-http via the netexec pod instead of kubectl exec.\n\t\t\toutput, err := framework.RunHostCmd(ns, execPodName, cmd)\n\t\t\tif err != nil {\n\t\t\t\tframework.Logf(\"error while kubectl execing %q in pod %v/%v: %v\\nOutput: %v\", cmd, ns, execPodName, err, output)\n\t\t\t}\n\t\t\treturn output\n\t\t},\n\t}\n\n\texpectedEndpoints := sets.NewString(expectedPods...)\n\tBy(fmt.Sprintf(\"verifying service has %d reachable backends\", len(expectedPods)))\n\tfor _, cmdFunc := range commands {\n\t\tpassed := false\n\t\tgotEndpoints := sets.NewString()\n\n\t\t// Retry cmdFunc for a while\n\t\tfor start := time.Now(); time.Since(start) < kubeProxyLagTimeout; time.Sleep(5 * time.Second) {\n\t\t\tfor _, endpoint := range strings.Split(cmdFunc(), \"\\n\") {\n\t\t\t\ttrimmedEp := strings.TrimSpace(endpoint)\n\t\t\t\tif trimmedEp != \"\" {\n\t\t\t\t\tgotEndpoints.Insert(trimmedEp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// TODO: simply checking that the retrieved endpoints is a superset\n\t\t\t// of the expected allows us to ignore intermitten network flakes that\n\t\t\t// result in output like \"wget timed out\", but these should be rare\n\t\t\t// and we need a better way to track how often it occurs.\n\t\t\tif gotEndpoints.IsSuperset(expectedEndpoints) {\n\t\t\t\tif !gotEndpoints.Equal(expectedEndpoints) {\n\t\t\t\t\tframework.Logf(\"Ignoring unexpected output wgetting endpoints of service %s: %v\", serviceIP, gotEndpoints.Difference(expectedEndpoints))\n\t\t\t\t}\n\t\t\t\tpassed = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.Logf(\"Unable to reach the following endpoints of service %s: %v\", serviceIP, expectedEndpoints.Difference(gotEndpoints))\n\t\t}\n\t\tif !passed {\n\t\t\t// Sort the lists so they're easier to visually diff.\n\t\t\texp := expectedEndpoints.List()\n\t\t\tgot := gotEndpoints.List()\n\t\t\tsort.StringSlice(exp).Sort()\n\t\t\tsort.StringSlice(got).Sort()\n\t\t\treturn fmt.Errorf(\"service verification failed for: %s\\nexpected %v\\nreceived %v\", serviceIP, exp, got)\n\t\t}\n\t}\n\treturn nil\n}", "func (suite *TestDbNqmSuite) TestGetPingTaskState(c *C) {\n\ttestedCases := []struct {\n\t\tagentId int\n\t\texpectedStatus int\n\t} {\n\t\t{2001, NO_PING_TASK}, // The agent has no ping task\n\t\t{2002, NO_PING_TASK}, // The agent has ping task, which are disabled\n\t\t{2003, HAS_PING_TASK}, // The agent has ping task(enabled, with ISP filter)\n\t\t{2004, HAS_PING_TASK}, // The agent has ping task(enabled, with province filter)\n\t\t{2005, HAS_PING_TASK}, // The agent has ping task(enabled, with city filter)\n\t\t{2006, HAS_PING_TASK}, // The agent has ping task(enabled, with name tag filter)\n\t\t{2007, HAS_PING_TASK}, // The agent has ping task(enabled, with group tag filter)\n\t\t{2010, HAS_PING_TASK_MATCH_ANY_TARGET}, // The agent has ping task(enabled, without filters)\n\t}\n\n\tfor _, v := range testedCases {\n\t\ttestedResult, err := getPingTaskState(v.agentId)\n\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(testedResult, Equals, v.expectedStatus)\n\t}\n}", "func DetectAttacks(callback func(), addr string){\n\t// create pinger and set the IP address if it is a real IP address\n\t// (otherwise throw a fit)\n\tp := fastping.NewPinger()\n\tra, err := net.ResolveIPAddr(\"ip4:icmp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.AddIPAddr(ra)\n\n\t// received is used to tell when a ping has been successfully received\n\t// done is for when it hasn't\n\t// create timer here so that it can be used in different scopes and can just be reset later\n\treceived := false\n\tdone := make(chan bool)\n\ttimer := time.NewTimer(100 * time.Second)\n\n\t// called when a ping response is received\n\tp.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {\n\t\tlog.Println(\"Got ping response from\", addr, \"in\", rtt)\n\t\treceived = true\n\t}\n\n\t// called at the end of a loop of p.RunLoop()\n\tp.OnIdle = func() {\n\t\t// if no ping has been received, exit and go back to the main function\n\t\tif !received {\n\t\t\tcallback()\n\t\t\tdone <- true\n\t\t}\n\n\t\t// reset the timer for the next run loop\n\t\ttimer.Reset(time.Second)\n\t\treceived = false\n\t}\n\n\t// GOOOOOOOOOOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!!!!\n\tp.RunLoop()\n\n\t// when either there has been an error or a timeout (DDOS ATTACK!!!), leave\n\tselect {\n\tcase <-p.Done():\n\tcase <-done:\n\t}\n\n\t// if something goes wrong, panic\n\tif p.Err() != nil {\n\t\tlog.Fatal(p.Err())\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a TCP query that results in failure. When a query fails, Accept should close the TCP socket.
func TestAcceptFail(t *testing.T) { doh := newFakeTransport() client, server := makePair() // Start the forwarder running. go Accept(doh, server) lbuf := make([]byte, 2) // Send Query queryData := simpleQueryBytes binary.BigEndian.PutUint16(lbuf, uint16(len(queryData))) client.Write(lbuf) client.Write(queryData) // Indicate that the query failed doh.err = errors.New("fake error") // Read query queryRead := <-doh.query if !bytes.Equal(queryRead, queryData) { t.Error("Query mismatch") } // Accept should have closed the socket. n, _ := client.Read(lbuf) if n != 0 { t.Error("Expected to read 0 bytes") } }
[ "func TestInvalidConn(t *testing.T) {\n\taddr := \"0.0.0.0:9993\"\n\ts, err := net.Listen(\"tcp\", addr)\n\n\tassert.Nil(t, err)\n\tdefer s.Close()\n\n\ttimeBetSend := 0.005\n\tbytesToSend := 10000\n\ttimesToSend := 1\n\tmaxRandTime := 0.001\n\tnodeName := \"TestInvalidConn\"\n\n\tgo DealWithTCPConnections(s)\n\terr = SendTCPConnections(\"some_string\", nodeName, timeBetSend, bytesToSend, timesToSend, maxRandTime)\n\tassert.NotNil(t, err)\n}", "func WaitForTCP(ctx context.Context, rAddr string) error {\n\tdialer := net.Dialer{}\n\tconn, err := dialer.DialContext(ctx, \"tcp\", rAddr)\n\t//For loop to get around OS Dial Timeout\n\tfor err != nil {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\tconn, err = dialer.DialContext(ctx, \"tcp\", rAddr)\n\t}\n\tconn.Close()\n\treturn nil\n}", "func listenTCP() {\n\tfor {\n\t\tconn, err := tcpListener.Accept()\n\t\tif err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok && netErr.Temporary() {\n\t\t\t\tlog.Printf(\"Temporary error while accepting connection: %s\", netErr)\n\t\t\t}\n\n\t\t\tlog.Fatalf(\"Unrecoverable error while accepting connection: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tgo handleTCPConn(conn)\n\t}\n}", "func FailOnConn(t *testing.T, addr string) net.Listener {\n\tt.Helper()\n\n\ttarpit, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo func() {\n\t\tt.Helper()\n\n\t\t_, err := tarpit.Accept()\n\t\tif err == nil {\n\t\t\tt.Error(\"No connection expected\")\n\t\t}\n\t}()\n\treturn tarpit\n}", "func sendInvalidMessage(conn net.Conn, timeout time.Duration) error {\n\tfcrMsg, _ := fcrmessages.EncodeInvalidMessageResponse()\n\treturn sendTCPMessage(conn, fcrMsg, timeout)\n}", "func (self *TCPConnectionPool) attemptWrite(query []byte) (uint64, *net.TCPConn, error) {\n\tvar write_tries uint8 = 3\n\tvar last_err error\n\tvar conn_id uint64\n\tvar conn *net.TCPConn\n\tfor write_tries > 1 {\n\t\tconn_id, conn, last_err = self.Acquire()\n\t\tif last_err != nil {\n\t\t\treturn 0, nil, last_err\n\t\t}\n\t\tconn.SetWriteDeadline(time.Now().Add(time.Duration(3) * time.Second))\n\t\tnum_written, err := conn.Write(query)\n\t\tif err != nil {\n\t\t\twrite_tries--\n\t\t\terr2 := self.Release(conn_id, false)\n\t\t\tif err2 != nil {\n\t\t\t\treturn 0, nil, err2\n\t\t\t}\n\t\t\tlast_err = err\n\t\t\tcontinue\n\t\t}\n\t\tqlen := len(query)\n\t\tself.lc.Debugf(\"workflow\", \"[%s] Wrote %d bytes for query of size %d.\", self.Cls, num_written, qlen)\n\t\tif num_written != qlen {\n\t\t\twrite_tries--\n\t\t\t// a bad deal; this means we couldn't write the entire query to ephemeris\n\t\t\tself.lc.Errorf(\"workflow\", \"[%s] Mismatch between the number of bytes in the provided query and number of bytes written to the target, num_query_bytes: %d, num_written: %d\", self.Cls, qlen, num_written)\n\t\t\terr := self.Release(conn_id, true)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, nil, err\n\t\t\t}\n\t\t\tlast_err = errors.New(fmt.Sprintf(\"the entire provided query was not sent!, query length: %d, sent: %d\", qlen, num_written))\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t// after several attempts on different connections, we failed to write the query\n\tif last_err != nil {\n\t\treturn 0, nil, last_err\n\t}\n\treturn conn_id, conn, nil\n}", "func handle_conn_err(err error) {\n if err == io.EOF {\n fmt.Println(\"Connection went away\")\n } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {\n fmt.Println(\"Connection Timeout\")\n } else if operr, ok := err.(*net.OpError); ok {\n if operr.Op == \"dial\" {\n fmt.Println(\"Couldn't reach host\")\n } else if operr.Op == \"read\" {\n fmt.Println(\"Can't read closed connection\")\n } else {\n fmt.Printf(\"Failed to perform op: '%s'\\n\", operr.Op)\n }\n }\n}", "func waitTCP(addr string) {\n\tlog.Printf(\"Waiting for TCP to be available at %s\", addr)\n\t// Try once a second to connect\n\tfor startTime := time.Now(); time.Since(startTime) < 10*time.Second; time.Sleep(time.Second) {\n\t\tconn, err := net.DialTimeout(\"tcp\", addr, time.Second)\n\n\t\tif err == nil {\n\t\t\t// Connection successful\n\t\t\tlog.Printf(\"TCP came up on %s\", addr)\n\t\t\tcloseErr := conn.Close()\n\t\t\tif closeErr != nil {\n\t\t\t\tlog.Printf(\"Error closing TCP connection in waitTCP: %s\", closeErr)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"Tried to connect to %s, got error: %s. Will retry in 1 second.\", addr, err)\n\t}\n\n\t// Timed out\n\tpanic(fmt.Sprintf(\"Timeout out waiting for service to start on %s\", addr))\n}", "func TestAcceptClose(t *testing.T) {\n\tdoh := newFakeTransport()\n\tclient, server := makePair()\n\n\t// Start the forwarder running.\n\tgo Accept(doh, server)\n\n\tlbuf := make([]byte, 2)\n\t// Send Query\n\tqueryData := simpleQueryBytes\n\tbinary.BigEndian.PutUint16(lbuf, uint16(len(queryData)))\n\tclient.Write(lbuf)\n\tclient.Write(queryData)\n\n\t// Read query\n\tqueryRead := <-doh.query\n\tif !bytes.Equal(queryRead, queryData) {\n\t\tt.Error(\"Query mismatch\")\n\t}\n\n\t// Close the TCP connection\n\tclient.Close()\n\n\t// Send fake response too late.\n\tresponseData := []byte{1, 2, 8, 9, 10}\n\tdoh.response <- responseData\n}", "func waitTCPDown(addr string) {\n\tlog.Printf(\"Waiting for TCP to be down at %s\", addr)\n\t// Try once a second to connect\n\tfor startTime := time.Now(); time.Since(startTime) < 10*time.Second; time.Sleep(time.Second) {\n\t\tconn, err := net.DialTimeout(\"tcp\", addr, time.Second)\n\n\t\tif err != nil {\n\t\t\t// Connection failed\n\t\t\tlog.Printf(\"TCP went down on %s\", addr)\n\t\t\treturn\n\t\t}\n\n\t\tcloseErr := conn.Close()\n\t\tif closeErr != nil {\n\t\t\tlog.Printf(\"Error closing TCP connection in waitTCP: %s\", closeErr)\n\t\t}\n\n\t\tlog.Printf(\"Tried to connect to %s, was successful. Will retry in 1 second.\", addr)\n\t}\n\n\t// Timed out\n\tpanic(fmt.Sprintf(\"Timeout out waiting for service to stop on %s\", addr))\n}", "func WaitForTCP(waitForTarget time.Duration, uri string) error {\n\tvar u *url.URL\n\tvar err error\n\tif u, err = url.Parse(uri); err != nil {\n\t\treturn err\n\t}\n\tif u.Port() == \"\" {\n\t\tswitch u.Scheme {\n\t\tcase \"rtmp\":\n\t\t\tu.Host = u.Host + \":1935\"\n\t\t}\n\t}\n\tdailer := net.Dialer{Timeout: 2 * time.Second}\n\tstarted := time.Now()\n\tvar conn net.Conn\n\tfor {\n\t\tif conn, err = dailer.Dial(\"tcp\", u.Host); err != nil {\n\t\t\ttime.Sleep(4 * time.Second)\n\t\t\tif time.Since(started) > waitForTarget {\n\t\t\t\treturn fmt.Errorf(\"Can't connect to '%s' for more than %s\", uri, waitForTarget)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconn.Close()\n\t\tbreak\n\t}\n\treturn nil\n}", "func ErrNetClosing() error {\n\tif errNetClosing == nil {\n\t\tvar dummyServer *net.TCPListener\n\t\tif addr, err := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:0\"); err != nil {\n\t\t\treturn nil\n\t\t} else if dummyServer, err = net.ListenTCP(\"tcp\", addr); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\t// noinspection GoUnhandledErrorResult\n\t\t\tdefer dummyServer.Close()\n\t\t}\n\t\tif dummyClient, err := net.DialTCP(\"tcp\", nil, dummyServer.Addr().(*net.TCPAddr)); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\t// noinspection GoUnhandledErrorResult\n\t\t\tdummyClient.Close()\n\t\t\t_, err = dummyClient.Write(dummyMessage)\n\t\t\tif opError, ok := err.(*net.OpError); ok {\n\t\t\t\terrNetClosing = opError.Err\n\t\t\t}\n\t\t}\n\t}\n\treturn errNetClosing\n}", "func TCP(address string, timeout int) (*Connection, error) {\n c, err := net.DialTimeout(\"tcp\", address, time.Duration(timeout)*time.Second)\n return &Connection{address, c}, err\n}", "func (s *Server) Accept() error {\n var tempDelay time.Duration // how long to sleep on accept failure\n for {\n c, e := s.listener.Accept()\n if e != nil {\n if ne, ok := e.(net.Error); ok && ne.Temporary() {\n if tempDelay == 0 {\n tempDelay = 5 * time.Millisecond\n } else {\n tempDelay *= 2\n }\n if max := 1 * time.Second; tempDelay > max {\n tempDelay = max\n }\n time.Sleep(tempDelay)\n continue\n }\n return e\n }\n go s.accept(c)\n }\n}", "func (c *Conn) Reject() {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.reply(ReplyRejected)\n\tcase MAILFROM, RCPTTO:\n\t\tc.reply(ReplyBadAddr)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.reply(ReplyInvalidAuth)\n\tcase DATA:\n\t\tc.reply(ReplyRejected)\n\t}\n\tc.replied = true\n}", "func (cp *singleConnectionPool) OnFailure(c *Connection) error { return nil }", "func WaitSuccessfulDial(address string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), waitDur)\n\tvar lastErr error\n\tdefer cancel()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn multierr.Combine(ctx.Err(), lastErr)\n\t\tdefault:\n\t\t}\n\t\tvar conn net.Conn\n\t\tconn, lastErr = net.Dial(\"tcp\", address)\n\t\tif lastErr == nil {\n\t\t\treturn conn.Close()\n\t\t}\n\t\tlastErr = errors.Wrap(lastErr, 0)\n\t}\n}", "func SendTCP(address, msg string) (string, error) {\n\tconn, err := net.Dial(\"tcp\", address)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlogrus.Warn(\"Could not close TCP connection\")\n\t\t}\n\t}()\n\n\t// writes to the tcp connection\n\tfmt.Fprintf(conn, msg+\"\\n\")\n\n\tresponse, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn response, nil\n}", "func (h *Handler) QueryFailed(validatorID ids.ShortID, requestID uint32) {\n\th.sendReliableMsg(message{\n\t\tmessageType: queryFailedMsg,\n\t\tvalidatorID: validatorID,\n\t\trequestID: requestID,\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a TCP query, and closes the socket before the response is sent. This tests for crashes when a response cannot be delivered.
func TestAcceptClose(t *testing.T) { doh := newFakeTransport() client, server := makePair() // Start the forwarder running. go Accept(doh, server) lbuf := make([]byte, 2) // Send Query queryData := simpleQueryBytes binary.BigEndian.PutUint16(lbuf, uint16(len(queryData))) client.Write(lbuf) client.Write(queryData) // Read query queryRead := <-doh.query if !bytes.Equal(queryRead, queryData) { t.Error("Query mismatch") } // Close the TCP connection client.Close() // Send fake response too late. responseData := []byte{1, 2, 8, 9, 10} doh.response <- responseData }
[ "func (c Client) SendQuery(message dns.Msg) (dns.Msg, error) {\n\t// Open a new QUIC stream\n\tlog.Debugln(\"opening new quic stream\")\n\tstream, err := c.Session.OpenStream()\n\tif err != nil {\n\t\treturn dns.Msg{}, errors.New(\"quic stream open: \" + err.Error())\n\t}\n\n\t// Pack the DNS message for transmission\n\tlog.Debugln(\"packing dns message\")\n\tpacked, err := message.Pack()\n\tif err != nil {\n\t\t_ = stream.Close()\n\t\treturn dns.Msg{}, errors.New(\"dns message pack: \" + err.Error())\n\t}\n\n\t// Send the DNS query over QUIC\n\tlog.Debugln(\"writing packed format to the stream\")\n\t_, err = stream.Write(packed)\n\t_ = stream.Close()\n\tif err != nil {\n\t\treturn dns.Msg{}, errors.New(\"quic stream write: \" + err.Error())\n\t}\n\n\t// Read the response\n\tlog.Debugln(\"reading server response\")\n\tresponse, err := ioutil.ReadAll(stream)\n\tif err != nil {\n\t\treturn dns.Msg{}, errors.New(\"quic stream read: \" + err.Error())\n\t}\n\n\t// Unpack the DNS message\n\tlog.Debugln(\"unpacking response dns message\")\n\tvar msg dns.Msg\n\terr = msg.Unpack(response)\n\tif err != nil {\n\t\treturn dns.Msg{}, errors.New(\"dns message unpack: \" + err.Error())\n\t}\n\n\treturn msg, nil // nil error\n}", "func WaitForTCP(ctx context.Context, rAddr string) error {\n\tdialer := net.Dialer{}\n\tconn, err := dialer.DialContext(ctx, \"tcp\", rAddr)\n\t//For loop to get around OS Dial Timeout\n\tfor err != nil {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\tconn, err = dialer.DialContext(ctx, \"tcp\", rAddr)\n\t}\n\tconn.Close()\n\treturn nil\n}", "func SendTCP(address, msg string) (string, error) {\n\tconn, err := net.Dial(\"tcp\", address)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlogrus.Warn(\"Could not close TCP connection\")\n\t\t}\n\t}()\n\n\t// writes to the tcp connection\n\tfmt.Fprintf(conn, msg+\"\\n\")\n\n\tresponse, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn response, nil\n}", "func sendRequest(conn net.Conn, text string) {\n message := text;\n \n if _,err := conn.Write([]byte(message + \"\\n\")); err != nil {\n log.Fatal(err)\n }\n}", "func sendServerIsFullMessage(conn net.Conn){\n writer := bufio.NewWriter(conn);\n\n //send FULL Message to Client\n _, error := writer.WriteString(\"SERVER FULL\")\n if error != nil{\n fmt.Println(error)\n }\n //flushing is necessary, the writeString only takes in the string, the flush function pushes it out to the user\n flushError := writer.Flush()\n if flushError != nil {\n fmt.Println(flushError)\n }\n\n conn.Close();\n}", "func (d *Device) EndSocketSend() error {\n\td.Write([]byte(\"+++\"))\n\n\t_, err := d.Response(pause)\n\treturn err\n}", "func checkTCPClientFirst(addr string, timeout time.Duration) (err error) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tcloseErr := conn.Close()\n\t\tif closeErr != nil && err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\n\tfmt.Fprint(conn, \"HELLO\")\n\n\terr = conn.SetReadDeadline(time.Now().Add(timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.HasPrefix(buf.String(), \"TCP-CLIENT-FIRST\") {\n\t\treturn fmt.Errorf(\"unexpected response: %s\", buf.String())\n\t}\n\n\treturn nil\n}", "func (c *Client) writeQuery(conn net.Conn, query []byte) error {\n\tvar err error\n\n\tif c.Timeout > 0 {\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(c.Timeout))\n\t}\n\n\t// Write to the connection\n\tif _, ok := conn.(*net.TCPConn); ok {\n\t\tl := make([]byte, 2)\n\t\tbinary.BigEndian.PutUint16(l, uint16(len(query)))\n\t\t_, err = (&net.Buffers{l, query}).WriteTo(conn)\n\t} else {\n\t\t_, err = conn.Write(query)\n\t}\n\n\treturn err\n}", "func handleTCPCommands(conn net.Conn) {\n\n var buf [BUF_SIZE]byte\n\n for {\n\n //go into echo server mode\n n, err := conn.Read(buf[0:])\n if err != nil {\n return\n }\n _, err2 := conn.Write(buf[0:n])\n if err2 != nil {\n return\n }\n }\n\n}", "func SendAnswer(conn net.Conn, answer []byte) (err error) {\r\n\tvar n int\r\n\tvar sent int\r\n\r\n\tif len(answer) > 65535 {\r\n\t\tpanic(\"An answer must not be more than 65535\")\r\n\t}\r\n\r\n\tdefer conn.SetDeadline(time.Time{})\r\n\tconn.SetDeadline(time.Now().Add(idleTimeout))\r\n\r\n\tfor {\r\n\t\tif n, err = conn.Write(answer); err != nil {\r\n\t\t\treturn\r\n\t\t}\r\n\t\tsent = sent + n\r\n\t\tif sent < len(answer) {\r\n\t\t\tcontinue\r\n\t\t} else {\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\treturn\r\n\r\n}", "func (c *Conn) Send(opcode uint, message []byte, wireTimeout time.Duration) error {\n\tc.writeMutex.Lock()\n\tc.SetWriteMode(opcode, true)\n\t_, err := c.writeWithRetry(message, wireTimeout)\n\tc.writeMutex.Unlock()\n\treturn err\n}", "func TestAcceptFail(t *testing.T) {\n\tdoh := newFakeTransport()\n\tclient, server := makePair()\n\n\t// Start the forwarder running.\n\tgo Accept(doh, server)\n\n\tlbuf := make([]byte, 2)\n\t// Send Query\n\tqueryData := simpleQueryBytes\n\tbinary.BigEndian.PutUint16(lbuf, uint16(len(queryData)))\n\tclient.Write(lbuf)\n\tclient.Write(queryData)\n\n\t// Indicate that the query failed\n\tdoh.err = errors.New(\"fake error\")\n\n\t// Read query\n\tqueryRead := <-doh.query\n\tif !bytes.Equal(queryRead, queryData) {\n\t\tt.Error(\"Query mismatch\")\n\t}\n\n\t// Accept should have closed the socket.\n\tn, _ := client.Read(lbuf)\n\tif n != 0 {\n\t\tt.Error(\"Expected to read 0 bytes\")\n\t}\n}", "func (o *PluginDnsClient) Query(queries []utils.DnsQueryParams, socket transport.SocketApi) error {\n\tif o.IsNameServer() {\n\t\treturn fmt.Errorf(\"Querying is not permitted for Dns Name Servers!\")\n\t}\n\tquestions, err := utils.BuildQuestions(queries)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(questions) > 0 {\n\t\tdata := o.dnsPktBuilder.BuildQueryPkt(questions, o.Tctx.Simulation)\n\t\tif socket == nil {\n\t\t\treturn fmt.Errorf(\"Invalid Socket in Query!\")\n\t\t}\n\t\ttransportErr, _ := o.socket.Write(data)\n\t\tif transportErr != transport.SeOK {\n\t\t\to.stats.socketWriteError++\n\t\t\treturn transportErr.Error()\n\t\t}\n\t\to.stats.pktTxDnsQuery++ // successfully sent query\n\t\to.stats.txBytes += uint64(len(data)) // number of bytes sent\n\t}\n\treturn nil\n}", "func TestInvalidConn(t *testing.T) {\n\taddr := \"0.0.0.0:9993\"\n\ts, err := net.Listen(\"tcp\", addr)\n\n\tassert.Nil(t, err)\n\tdefer s.Close()\n\n\ttimeBetSend := 0.005\n\tbytesToSend := 10000\n\ttimesToSend := 1\n\tmaxRandTime := 0.001\n\tnodeName := \"TestInvalidConn\"\n\n\tgo DealWithTCPConnections(s)\n\terr = SendTCPConnections(\"some_string\", nodeName, timeBetSend, bytesToSend, timesToSend, maxRandTime)\n\tassert.NotNil(t, err)\n}", "func GetResponse(host string, input string) (string, error) {\n\tconn, err := net.Dial(\"tcp\", host)\n\tif err != nil {\n\t\treturn ``, err\n\t}\n\n\tdefer conn.Close()\n\n\tt := time.Time{}\n\tt.Add(30 * time.Second)\n\n\tconn.SetDeadline(t)\n\tconn.Write([]byte(input ))\n\t//fmt.Fprintf(conn, input)\n\n\tvar buf bytes.Buffer\n\ttmp := make([]byte, 256) // using small tmo buffer for demonstrating\n\tfor {\n\t\tn, err := conn.Read(tmp)\n\t\tfmt.Println(string(tmp[:n]), n)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tfmt.Println(\"read error:\", err)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t\tbuf.Write(tmp)\n\t}\n\n\tfmt.Println(\"total size:\", buf.Len())\n\n\treturn buf.String(), nil\n}", "func (h *Handler) SendQuery(ctx context.Context, ip net.IP) (err error) {\n\n\tpacket := nodeStatusRequestWireFormat(`* `)\n\t// packet.printHeader()\n\n\tif ip == nil || ip.Equal(net.IPv4zero) {\n\t\treturn fmt.Errorf(\"invalid IP=%v\", ip)\n\t}\n\t// ip[3] = 255 // Network broadcast\n\n\t// To broadcast, use network broadcast i.e 192.168.0.255 for example.\n\ttargetAddr := &net.UDPAddr{IP: ip, Port: 137}\n\tif _, err = h.conn.WriteToUDP(packet, targetAddr); err != nil {\n\t\tif ctx.Err() == nil { // not cancelled\n\t\t\treturn fmt.Errorf(\"nbns failed to send packet: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *conn) Close() (err error) {\n\tc.log.debug(\"Closing connection to %s\\n\", c.remoteAddr)\n\n\tif c.reqChan == nil {\n\t\tdefer func() {\n\t\t\t// Close network even if another error occurs\n\t\t\t//\n\t\t\tcErr := c.netConn.Close()\n\t\t\tif cErr != nil {\n\t\t\t\tc.log.debug(\"error closing network connection:\", cErr)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\terr = cErr\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Can't write if an error has been sent/received\n\tif c.err != nil {\n\t\treturn wrapError(c.err, \"checking conn err before Close\")\n\t}\n\n\t// netasciiEnc needs to be flushed if it's in use\n\tif c.netasciiEnc != nil {\n\t\tc.log.trace(\"Flushing netascii encoder\")\n\t\tif err := c.netasciiEnc.Flush(); err != nil {\n\t\t\treturn wrapError(err, \"flushing netascii encoder before Close\")\n\t\t}\n\t}\n\n\t// Write any remaining data, or 0 length DATA to end transfer\n\tif c.txBuf != nil {\n\t\tfor retries := 0; ; {\n\t\t\tif err := c.writeData(); err != nil {\n\t\t\t\treturn wrapError(err, \"writing final data before Close\")\n\t\t\t}\n\n\t\t\terr := c.getAck()\n\t\t\tif err == nil {\n\t\t\t\t// Recheck data, window could have been missed\n\t\t\t\tif c.txBuf.Len() >= int(c.blksize) {\n\t\t\t\t\tc.log.trace(\"%d\", c.txBuf.Len())\n\t\t\t\t\tc.write([]byte{})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif c.txBuf.Len() > 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Return if the transfer has erred\n\t\t\tif c.err != nil {\n\t\t\t\treturn wrapError(c.err, \"checking conn error sending ACK for final data before Close\")\n\t\t\t}\n\n\t\t\t// Retry until maxRetransmit\n\t\t\tretries++\n\t\t\tc.log.debug(\"Error receiving ACK (retry %d): %v\\n\", retries, err)\n\t\t\tif retries > c.retransmit {\n\t\t\t\tc.log.debug(\"Max retries exceeded\")\n\t\t\t\tc.sendError(ErrCodeNotDefined, \"max retries reached\")\n\t\t\t\treturn wrapError(err, \"writing final data ACK before Close\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *query) sendQuery(udpConn *net.UDPConn) {\n\tqueryStr := whosthereStr + q.name\n\tlog.Printf(\"sendQuery <%v>\\n\", queryStr)\n\n\tif q.useBroadcast {\n\t\t//## for Window8/8.1, cant recv multicast, send broadcast\n\t\tudpConn.WriteToUDP([]byte(queryStr), &broadcastUdpAddr)\n\t} else {\n\t\t// multicast\n\t\tudpConn.WriteToUDP([]byte(queryStr), &multicastUdpAddr)\n\t}\n}", "func checkTCPServerFirst(addr string, timeout time.Duration) (err error) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tcloseErr := conn.Close()\n\t\tif closeErr != nil && err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\n\terr = conn.SetReadDeadline(time.Now().Add(timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.HasPrefix(buf.String(), \"TCP-SERVER-FIRST\") {\n\t\treturn fmt.Errorf(\"unexpected response: %s\", buf.String())\n\t}\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that packing |compressedQueryBytes| constructs the same query byteforbyte.
func TestDnsMessageCompressedQueryConfidenceCheck(t *testing.T) { m := mustUnpack(compressedQueryBytes) packedBytes := mustPack(m) if len(packedBytes) != len(compressedQueryBytes) { t.Errorf("Packed query has different size than original:\n %v\n %v", packedBytes, compressedQueryBytes) } }
[ "func TestDnsMessageUncompressedQueryConfidenceCheck(t *testing.T) {\n\tm := mustUnpack(uncompressedQueryBytes)\n\tpackedBytes := mustPack(m)\n\tif len(packedBytes) >= len(uncompressedQueryBytes) {\n\t\tt.Errorf(\"Compressed query is not smaller than uncompressed query\")\n\t}\n}", "func (q *CompoundQuery) GetCompressedQuery() []byte {\n\treturn flateCompressor.MustCompressString(\n\t\tojson.MarshalJSON(q),\n\t)\n}", "func (idx *Index) QueryBytes(sctx sessionctx.Context, d []byte) (result uint64) {\n\tidx.CheckStats()\n\tif sctx != nil && sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {\n\t\tdebugtrace.EnterContextCommon(sctx)\n\t\tdefer func() {\n\t\t\tdebugtrace.RecordAnyValuesWithNames(sctx, \"Result\", result)\n\t\t\tdebugtrace.LeaveContextCommon(sctx)\n\t\t}()\n\t}\n\th1, h2 := murmur3.Sum128(d)\n\tif idx.TopN != nil {\n\t\tif count, ok := idx.TopN.QueryTopN(sctx, d); ok {\n\t\t\treturn count\n\t\t}\n\t}\n\tif idx.CMSketch != nil {\n\t\treturn idx.CMSketch.queryHashValue(sctx, h1, h2)\n\t}\n\tv, _ := idx.Histogram.EqualRowCount(sctx, types.NewBytesDatum(d), idx.StatsVer >= Version2)\n\treturn uint64(v)\n}", "func TestAddEdnsPaddingCompressedPaddedQuery(t *testing.T) {\n\tpaddedQuery := simpleQuery\n\tpaddedQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(paddedQuery.Additionals, simpleQuery.Additionals)\n\n\tpaddedQuery.Additionals = append(paddedQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{\n\t\t\t\t\t{\n\t\t\t\t\t\tCode: OptResourcePaddingCode,\n\t\t\t\t\t\tData: make([]byte, 5),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\toriginalOnWire := mustPack(&paddedQuery)\n\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&paddedQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad padded query: %v\", err)\n\t}\n\n\tif !bytes.Equal(originalOnWire, paddedOnWire) {\n\t\tt.Errorf(\"AddEdnsPadding tampered with a query that was already padded\")\n\t}\n}", "func TestAddEdnsPaddingUncompressedQuery(t *testing.T) {\n\tif len(uncompressedQueryBytes)%PaddingBlockSize == 0 {\n\t\tt.Errorf(\"uncompressedQueryBytes does not require padding, so this test is invalid\")\n\t}\n\tpadded, err := AddEdnsPadding(uncompressedQueryBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(padded)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad uncompressed query\")\n\t}\n}", "func (p *Packet) PackQuery() []byte {\n\tout := new(bytes.Buffer)\n\n\tp.packHeader(out)\n\tp.Question.pack(out)\n\n\tp.Bytes = out.Bytes() // swap in\n\treturn p.Bytes\n}", "func (v Document) QueryBytes(query string) []byte {\n\tr, ok := v.QueryOne(query).([]byte)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn r\n}", "func CheckQueryPattern(b []byte) bool {\n\n\ttheQuery := string(b)\n\ttheQuery = strings.ToLower(theQuery)\n\ttheQuery = strings.TrimSpace(theQuery)\n\n\t// проверка на первый key_word\n\tif !strings.HasPrefix(theQuery, \"select\") {\n\t\treturn false\n\t}\n\n\tfor _, patt := range QueryPatterns {\n\t\tmatched, _ := regexp.Match(patt, []byte(theQuery))\n\t\tif matched {\n\t\t\treturn true // также надо запомнить, какой паттерн подошел\n\t\t}\n\t}\n\treturn false\n}", "func TestAddEdnsPaddingCompressedOptQuery(t *testing.T) {\n\toptQuery := simpleQuery\n\toptQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(optQuery.Additionals, simpleQuery.Additionals)\n\n\toptQuery.Additionals = append(optQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{},\n\t\t\t},\n\t\t},\n\t)\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&optQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad query with OPT but no padding: %v\", err)\n\t}\n\tif len(paddedOnWire)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad query with OPT but no padding\")\n\t}\n}", "func encodeQuery(rawQuery string) ([]byte, error) {\n\tvar b bytes.Buffer\n\tgz := gzip.NewWriter(&b)\n\tif _, err := gz.Write([]byte(rawQuery)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := gz.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.Bytes(), nil\n}", "func (v Document) QueryAll(query string) []interface{} {\n\tvar results []interface{}\n\tvar err error\n\tif v.table != nil && v.table.keyToCompressed != nil {\n\t\tresults, err = msgpack.NewDecoder(bytes.NewReader(v.data)).\n\t\t\tQueryCompressed(v.table.keyToC, query)\n\t} else {\n\t\tresults, err = msgpack.NewDecoder(bytes.NewReader(v.data)).Query(query)\n\t}\n\n\tif err != nil || len(results) == 0 {\n\t\treturn nil\n\t}\n\treturn results\n}", "func isCompressed(privKey *btcec.PrivateKey, addr string, netParams *btcnet.Params) (bool, error) {\n\tbtcPubKey := (btcec.PublicKey)(privKey.PublicKey)\n\tserCompressed := btcPubKey.SerializeCompressed()\n\tcompressedAddr, err := btcutil.NewAddressPubKey(serCompressed, netParams)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn compressedAddr.EncodeAddress() == addr, nil\n}", "func IsCompressed(msg []byte) bool {\n\treturn msg[0]&compressionMask != 0\n}", "func (b *BloomFilter) ContainsBytes(value []byte) bool {\n\tres := true\n\tfor h := 0; h < b.k; h++ {\n\t\tindex := b.kiMiHash(value, h)\n\t\tif b.bucket.Bit(index) == 0 {\n\t\t\tres = false\n\t\t}\n\t}\n\treturn res\n}", "func IsCompressed(proof *CommitmentProof) bool {\n\treturn proof.GetCompressed() != nil\n}", "func DeSerializeQuery(bytes []byte) Query {\n if len(bytes) != 32 {\n fmt.Println(\"Error : bytes length is not 32. Its \", len(bytes))\n }\n\n return Query {\n action : bytes[0],\n empty : 0,\n replyIp : binary.BigEndian.Uint32(bytes[2:6]),\n replyPort : binary.BigEndian.Uint16(bytes[6:8]),\n key : binary.BigEndian.Uint64(bytes[8:16]),\n value : binary.BigEndian.Uint64(bytes[16:24]),\n timeToLive: binary.BigEndian.Uint32(bytes[24:28]),\n requestId : binary.BigEndian.Uint32(bytes[28:32]),\n }\n}", "func CheckByteLayout(fail func(string, ...interface{})) {\n\tvar b *flatbuffers.Builder\n\n\tvar i int\n\tcheck := func(want []byte) {\n\t\ti++\n\t\tgot := b.Bytes[b.Head():]\n\t\tif !bytes.Equal(want, got) {\n\t\t\tfail(\"case %d: want\\n%v\\nbut got\\n%v\\n\", i, want, got)\n\t\t}\n\t}\n\n\t// test 1: numbers\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.PrependBool(true)\n\tcheck([]byte{1})\n\tb.PrependInt8(-127)\n\tcheck([]byte{129, 1})\n\tb.PrependUint8(255)\n\tcheck([]byte{255, 129, 1})\n\tb.PrependInt16(-32222)\n\tcheck([]byte{0x22, 0x82, 0, 255, 129, 1}) // first pad\n\tb.PrependUint16(0xFEEE)\n\tcheck([]byte{0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) // no pad this time\n\tb.PrependInt32(-53687092)\n\tcheck([]byte{204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\tb.PrependUint32(0x98765432)\n\tcheck([]byte{0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\n\t// test 1b: numbers 2\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.PrependUint64(0x1122334455667788)\n\tcheck([]byte{0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11})\n\n\t// test 2: 1xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartVector(flatbuffers.SizeByte, 1, 1)\n\tcheck([]byte{0, 0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 3: 2xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 2, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0})\n\tb.PrependByte(2)\n\tcheck([]byte{2, 1, 0, 0})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 2, 1, 0, 0}) // padding\n\n\t// test 3b: 11xbyte vector matches builder size\n\n\tb = flatbuffers.NewBuilder(12)\n\tb.StartVector(flatbuffers.SizeByte, 8, 1)\n\tstart := []byte{}\n\tcheck(start)\n\tfor i := 1; i < 12; i++ {\n\t\tb.PrependByte(byte(i))\n\t\tstart = append([]byte{byte(i)}, start...)\n\t\tcheck(start)\n\t}\n\tb.EndVector(8)\n\tcheck(append([]byte{8, 0, 0, 0}, start...))\n\n\t// test 4: 1xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 1, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependUint16(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 5: 2xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 2, 1)\n\tcheck([]byte{}) // align to 4bytes\n\tb.PrependUint16(0xABCD)\n\tcheck([]byte{0xCD, 0xAB})\n\tb.PrependUint16(0xDCBA)\n\tcheck([]byte{0xBA, 0xDC, 0xCD, 0xAB})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB})\n\n\t// test 6: CreateString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateString(\"foo\")\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateString(\"moop\")\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 6b: CreateString unicode\n\n\tb = flatbuffers.NewBuilder(0)\n\t// These characters are chinese from blog.golang.org/strings\n\t// We use escape codes here so that editors without unicode support\n\t// aren't bothered:\n\tuni_str := \"\\u65e5\\u672c\\u8a9e\"\n\tb.CreateString(uni_str)\n\tcheck([]byte{9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad\n\t\t0, 0})\n\n\t// test 6c: CreateByteString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateByteString([]byte(\"foo\"))\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateByteString([]byte(\"moop\"))\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 7: empty vtable\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(0)\n\tcheck([]byte{})\n\tb.EndObject()\n\tcheck([]byte{4, 0, 4, 0, 4, 0, 0, 0})\n\n\t// test 8: vtable with one true bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // length of object including vtable offset\n\t\t7, 0, // start of bool value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, 0, // padded to 4 bytes\n\t\t1, // bool value\n\t})\n\n\t// test 9: vtable with one default bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, false, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t4, 0, // vtable bytes\n\t\t4, 0, // end of object from here\n\t\t// entry 1 is zero and not stored.\n\t\t4, 0, 0, 0, // offset for start of vtable (int32)\n\t})\n\n\t// test 10: vtable with one int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependInt16Slot(0, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding to 4 bytes\n\t\t0x9A, 0x78,\n\t})\n\n\t// test 11: vtable with two int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependInt16Slot(1, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t4, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x9A, 0x78, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with int16 and bool\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependBoolSlot(1, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t5, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t1, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with empty vector\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend := b.EndVector(0)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset to vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0,\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 12b: vtable with empty vector of byte and some scalars\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend = b.EndVector(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0,\n\t\t10, 0, // offset to value 0\n\t\t4, 0, // offset to vector offset\n\t\t8, 0, 0, 0, // vtable loc\n\t\t8, 0, 0, 0, // value 1\n\t\t0, 0, 55, 0, // value 0\n\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 13: vtable with 1 int16 and 2-vector of int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt16, 2, 1)\n\tb.PrependInt16(0x1234)\n\tb.PrependInt16(0x5678)\n\tvecend = b.EndVector(2)\n\tb.StartObject(2)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0, // length of object\n\t\t6, 0, // start of value 0 from end of vtable\n\t\t8, 0, // start of value 1 from end of buffer\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t55, 0, // value 0\n\t\t4, 0, 0, 0, // vector position from here\n\t\t2, 0, 0, 0, // length of vector (uint32)\n\t\t0x78, 0x56, // vector value 1\n\t\t0x34, 0x12, // vector value 0\n\t})\n\n\t// test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.Prep(4+4+4, 0)\n\tb.PrependInt8(55)\n\tb.Pad(3)\n\tb.PrependInt16(0x1234)\n\tb.Pad(2)\n\tb.PrependInt32(0x12345678)\n\tstructStart := b.Offset()\n\tb.PrependStructSlot(0, structStart, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t16, 0, // end of object from here\n\t\t4, 0, // start of struct from here\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x78, 0x56, 0x34, 0x12, // value 2\n\t\t0, 0, // padding\n\t\t0x34, 0x12, // value 1\n\t\t0, 0, 0, // padding\n\t\t55, // value 0\n\t})\n\n\t// test 15: vtable with 1 vector of 2 struct of 2 int8\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt8*2, 2, 1)\n\tb.PrependInt8(33)\n\tb.PrependInt8(44)\n\tb.PrependInt8(55)\n\tb.PrependInt8(66)\n\tvecend = b.EndVector(2)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset of vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0, // vector start offset\n\n\t\t2, 0, 0, 0, // vector length\n\t\t66, // vector value 1,1\n\t\t55, // vector value 1,0\n\t\t44, // vector value 0,1\n\t\t33, // vector value 0,0\n\t})\n\n\t// test 16: table with some elements\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff := b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16b: same as test 16, size prefixed\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixed(off)\n\n\tcheck([]byte{\n\t\t20, 0, 0, 0, // size prefix\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16c: same as test 16, with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16d: same as test 16, size prefixed with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixedWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // size prefix\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 17: one unfinished table and one finished table\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt8Slot(1, 44, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tb.StartObject(3)\n\tb.PrependInt8Slot(0, 55, 0)\n\tb.PrependInt8Slot(1, 66, 0)\n\tb.PrependInt8Slot(2, 77, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to object\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t77, // value 2\n\t\t66, // value 1\n\t\t55, // value 0\n\n\t\t12, 0, 0, 0, // root of table: points to object\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t44, // value 1\n\t\t33, // value 0\n\t})\n\n\t// test 18: a bunch of bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(8)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\tb.PrependBoolSlot(3, true, false)\n\tb.PrependBoolSlot(4, true, false)\n\tb.PrependBoolSlot(5, true, false)\n\tb.PrependBoolSlot(6, true, false)\n\tb.PrependBoolSlot(7, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t20, 0, // vtable bytes\n\t\t12, 0, // size of object\n\t\t11, 0, // start of value 0\n\t\t10, 0, // start of value 1\n\t\t9, 0, // start of value 2\n\t\t8, 0, // start of value 3\n\t\t7, 0, // start of value 4\n\t\t6, 0, // start of value 5\n\t\t5, 0, // start of value 6\n\t\t4, 0, // start of value 7\n\t\t20, 0, 0, 0, // vtable offset\n\n\t\t1, // value 7\n\t\t1, // value 6\n\t\t1, // value 5\n\t\t1, // value 4\n\t\t1, // value 3\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 19: three bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(3)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // vtable offset from here\n\n\t\t0, // padding\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 20: some floats\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependFloat32Slot(0, 1.0, 0.0)\n\toff = b.EndObject()\n\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t4, 0, // start of value 0\n\t\t6, 0, 0, 0, // vtable offset\n\n\t\t0, 0, 128, 63, // value 0\n\t})\n}", "func (ms *memoryStorer) IsCompressed() bool {\n\treturn true\n}", "func TestShortQuery(t *testing.T) {\n\tvar qerr *queryError\n\tdoh, _ := NewTransport(testURL, ips, nil, nil, nil)\n\t_, err := doh.Query([]byte{})\n\tif err == nil {\n\t\tt.Error(\"Empty query should fail\")\n\t} else if !errors.As(err, &qerr) {\n\t\tt.Errorf(\"Wrong error type: %v\", err)\n\t} else if qerr.status != BadQuery {\n\t\tt.Errorf(\"Wrong error status: %d\", qerr.status)\n\t}\n\n\t_, err = doh.Query([]byte{1})\n\tif err == nil {\n\t\tt.Error(\"One byte query should fail\")\n\t} else if !errors.As(err, &qerr) {\n\t\tt.Errorf(\"Wrong error type: %v\", err)\n\t} else if qerr.status != BadQuery {\n\t\tt.Errorf(\"Wrong error status: %d\", qerr.status)\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that packing |uncompressedQueryBytes| constructs a smaller query byteforbyte, since label compression is enabled by default.
func TestDnsMessageUncompressedQueryConfidenceCheck(t *testing.T) { m := mustUnpack(uncompressedQueryBytes) packedBytes := mustPack(m) if len(packedBytes) >= len(uncompressedQueryBytes) { t.Errorf("Compressed query is not smaller than uncompressed query") } }
[ "func TestDnsMessageCompressedQueryConfidenceCheck(t *testing.T) {\n\tm := mustUnpack(compressedQueryBytes)\n\tpackedBytes := mustPack(m)\n\tif len(packedBytes) != len(compressedQueryBytes) {\n\t\tt.Errorf(\"Packed query has different size than original:\\n %v\\n %v\", packedBytes, compressedQueryBytes)\n\t}\n}", "func (idx *Index) QueryBytes(sctx sessionctx.Context, d []byte) (result uint64) {\n\tidx.CheckStats()\n\tif sctx != nil && sctx.GetSessionVars().StmtCtx.EnableOptimizerDebugTrace {\n\t\tdebugtrace.EnterContextCommon(sctx)\n\t\tdefer func() {\n\t\t\tdebugtrace.RecordAnyValuesWithNames(sctx, \"Result\", result)\n\t\t\tdebugtrace.LeaveContextCommon(sctx)\n\t\t}()\n\t}\n\th1, h2 := murmur3.Sum128(d)\n\tif idx.TopN != nil {\n\t\tif count, ok := idx.TopN.QueryTopN(sctx, d); ok {\n\t\t\treturn count\n\t\t}\n\t}\n\tif idx.CMSketch != nil {\n\t\treturn idx.CMSketch.queryHashValue(sctx, h1, h2)\n\t}\n\tv, _ := idx.Histogram.EqualRowCount(sctx, types.NewBytesDatum(d), idx.StatsVer >= Version2)\n\treturn uint64(v)\n}", "func TestAddEdnsPaddingUncompressedQuery(t *testing.T) {\n\tif len(uncompressedQueryBytes)%PaddingBlockSize == 0 {\n\t\tt.Errorf(\"uncompressedQueryBytes does not require padding, so this test is invalid\")\n\t}\n\tpadded, err := AddEdnsPadding(uncompressedQueryBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(padded)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad uncompressed query\")\n\t}\n}", "func CheckByteLayout(fail func(string, ...interface{})) {\n\tvar b *flatbuffers.Builder\n\n\tvar i int\n\tcheck := func(want []byte) {\n\t\ti++\n\t\tgot := b.Bytes[b.Head():]\n\t\tif !bytes.Equal(want, got) {\n\t\t\tfail(\"case %d: want\\n%v\\nbut got\\n%v\\n\", i, want, got)\n\t\t}\n\t}\n\n\t// test 1: numbers\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.PrependBool(true)\n\tcheck([]byte{1})\n\tb.PrependInt8(-127)\n\tcheck([]byte{129, 1})\n\tb.PrependUint8(255)\n\tcheck([]byte{255, 129, 1})\n\tb.PrependInt16(-32222)\n\tcheck([]byte{0x22, 0x82, 0, 255, 129, 1}) // first pad\n\tb.PrependUint16(0xFEEE)\n\tcheck([]byte{0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) // no pad this time\n\tb.PrependInt32(-53687092)\n\tcheck([]byte{204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\tb.PrependUint32(0x98765432)\n\tcheck([]byte{0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\n\t// test 1b: numbers 2\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.PrependUint64(0x1122334455667788)\n\tcheck([]byte{0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11})\n\n\t// test 2: 1xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartVector(flatbuffers.SizeByte, 1, 1)\n\tcheck([]byte{0, 0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 3: 2xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 2, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0})\n\tb.PrependByte(2)\n\tcheck([]byte{2, 1, 0, 0})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 2, 1, 0, 0}) // padding\n\n\t// test 3b: 11xbyte vector matches builder size\n\n\tb = flatbuffers.NewBuilder(12)\n\tb.StartVector(flatbuffers.SizeByte, 8, 1)\n\tstart := []byte{}\n\tcheck(start)\n\tfor i := 1; i < 12; i++ {\n\t\tb.PrependByte(byte(i))\n\t\tstart = append([]byte{byte(i)}, start...)\n\t\tcheck(start)\n\t}\n\tb.EndVector(8)\n\tcheck(append([]byte{8, 0, 0, 0}, start...))\n\n\t// test 4: 1xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 1, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependUint16(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 5: 2xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 2, 1)\n\tcheck([]byte{}) // align to 4bytes\n\tb.PrependUint16(0xABCD)\n\tcheck([]byte{0xCD, 0xAB})\n\tb.PrependUint16(0xDCBA)\n\tcheck([]byte{0xBA, 0xDC, 0xCD, 0xAB})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB})\n\n\t// test 6: CreateString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateString(\"foo\")\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateString(\"moop\")\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 6b: CreateString unicode\n\n\tb = flatbuffers.NewBuilder(0)\n\t// These characters are chinese from blog.golang.org/strings\n\t// We use escape codes here so that editors without unicode support\n\t// aren't bothered:\n\tuni_str := \"\\u65e5\\u672c\\u8a9e\"\n\tb.CreateString(uni_str)\n\tcheck([]byte{9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad\n\t\t0, 0})\n\n\t// test 6c: CreateByteString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateByteString([]byte(\"foo\"))\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateByteString([]byte(\"moop\"))\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 7: empty vtable\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(0)\n\tcheck([]byte{})\n\tb.EndObject()\n\tcheck([]byte{4, 0, 4, 0, 4, 0, 0, 0})\n\n\t// test 8: vtable with one true bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // length of object including vtable offset\n\t\t7, 0, // start of bool value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, 0, // padded to 4 bytes\n\t\t1, // bool value\n\t})\n\n\t// test 9: vtable with one default bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, false, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t4, 0, // vtable bytes\n\t\t4, 0, // end of object from here\n\t\t// entry 1 is zero and not stored.\n\t\t4, 0, 0, 0, // offset for start of vtable (int32)\n\t})\n\n\t// test 10: vtable with one int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependInt16Slot(0, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding to 4 bytes\n\t\t0x9A, 0x78,\n\t})\n\n\t// test 11: vtable with two int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependInt16Slot(1, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t4, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x9A, 0x78, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with int16 and bool\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependBoolSlot(1, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t5, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t1, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with empty vector\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend := b.EndVector(0)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset to vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0,\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 12b: vtable with empty vector of byte and some scalars\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend = b.EndVector(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0,\n\t\t10, 0, // offset to value 0\n\t\t4, 0, // offset to vector offset\n\t\t8, 0, 0, 0, // vtable loc\n\t\t8, 0, 0, 0, // value 1\n\t\t0, 0, 55, 0, // value 0\n\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 13: vtable with 1 int16 and 2-vector of int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt16, 2, 1)\n\tb.PrependInt16(0x1234)\n\tb.PrependInt16(0x5678)\n\tvecend = b.EndVector(2)\n\tb.StartObject(2)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0, // length of object\n\t\t6, 0, // start of value 0 from end of vtable\n\t\t8, 0, // start of value 1 from end of buffer\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t55, 0, // value 0\n\t\t4, 0, 0, 0, // vector position from here\n\t\t2, 0, 0, 0, // length of vector (uint32)\n\t\t0x78, 0x56, // vector value 1\n\t\t0x34, 0x12, // vector value 0\n\t})\n\n\t// test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.Prep(4+4+4, 0)\n\tb.PrependInt8(55)\n\tb.Pad(3)\n\tb.PrependInt16(0x1234)\n\tb.Pad(2)\n\tb.PrependInt32(0x12345678)\n\tstructStart := b.Offset()\n\tb.PrependStructSlot(0, structStart, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t16, 0, // end of object from here\n\t\t4, 0, // start of struct from here\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x78, 0x56, 0x34, 0x12, // value 2\n\t\t0, 0, // padding\n\t\t0x34, 0x12, // value 1\n\t\t0, 0, 0, // padding\n\t\t55, // value 0\n\t})\n\n\t// test 15: vtable with 1 vector of 2 struct of 2 int8\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt8*2, 2, 1)\n\tb.PrependInt8(33)\n\tb.PrependInt8(44)\n\tb.PrependInt8(55)\n\tb.PrependInt8(66)\n\tvecend = b.EndVector(2)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset of vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0, // vector start offset\n\n\t\t2, 0, 0, 0, // vector length\n\t\t66, // vector value 1,1\n\t\t55, // vector value 1,0\n\t\t44, // vector value 0,1\n\t\t33, // vector value 0,0\n\t})\n\n\t// test 16: table with some elements\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff := b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16b: same as test 16, size prefixed\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixed(off)\n\n\tcheck([]byte{\n\t\t20, 0, 0, 0, // size prefix\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16c: same as test 16, with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16d: same as test 16, size prefixed with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixedWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // size prefix\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 17: one unfinished table and one finished table\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt8Slot(1, 44, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tb.StartObject(3)\n\tb.PrependInt8Slot(0, 55, 0)\n\tb.PrependInt8Slot(1, 66, 0)\n\tb.PrependInt8Slot(2, 77, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to object\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t77, // value 2\n\t\t66, // value 1\n\t\t55, // value 0\n\n\t\t12, 0, 0, 0, // root of table: points to object\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t44, // value 1\n\t\t33, // value 0\n\t})\n\n\t// test 18: a bunch of bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(8)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\tb.PrependBoolSlot(3, true, false)\n\tb.PrependBoolSlot(4, true, false)\n\tb.PrependBoolSlot(5, true, false)\n\tb.PrependBoolSlot(6, true, false)\n\tb.PrependBoolSlot(7, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t20, 0, // vtable bytes\n\t\t12, 0, // size of object\n\t\t11, 0, // start of value 0\n\t\t10, 0, // start of value 1\n\t\t9, 0, // start of value 2\n\t\t8, 0, // start of value 3\n\t\t7, 0, // start of value 4\n\t\t6, 0, // start of value 5\n\t\t5, 0, // start of value 6\n\t\t4, 0, // start of value 7\n\t\t20, 0, 0, 0, // vtable offset\n\n\t\t1, // value 7\n\t\t1, // value 6\n\t\t1, // value 5\n\t\t1, // value 4\n\t\t1, // value 3\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 19: three bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(3)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // vtable offset from here\n\n\t\t0, // padding\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 20: some floats\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependFloat32Slot(0, 1.0, 0.0)\n\toff = b.EndObject()\n\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t4, 0, // start of value 0\n\t\t6, 0, 0, 0, // vtable offset\n\n\t\t0, 0, 128, 63, // value 0\n\t})\n}", "func (b *block) uncompressedSizeBytes() uint64 {\n\trowsCount := uint64(b.Len())\n\n\t// Take into account timestamps\n\tn := rowsCount * uint64(len(time.RFC3339Nano))\n\n\t// Take into account columns\n\tcs := b.columns\n\tfor i := range cs {\n\t\tc := &cs[i]\n\t\tnameLen := uint64(len(c.name))\n\t\tif nameLen == 0 {\n\t\t\tnameLen = uint64(len(\"_msg\"))\n\t\t}\n\t\tfor _, v := range c.values {\n\t\t\tif len(v) > 0 {\n\t\t\t\tn += nameLen + 2 + uint64(len(v))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Take into account constColumns\n\tccs := b.constColumns\n\tfor i := range ccs {\n\t\tcc := &ccs[i]\n\t\tnameLen := uint64(len(cc.Name))\n\t\tif nameLen == 0 {\n\t\t\tnameLen = uint64(len(\"_msg\"))\n\t\t}\n\t\tn += rowsCount * (2 + nameLen + uint64(len(cc.Value)))\n\t}\n\n\treturn n\n}", "func DecodeQuery(queryMessageBytes []byte) *QueryMessage {\n\n\tvar queryMessage QueryMessage\n\n\tr, err := gzip.NewReader(bytes.NewBuffer(queryMessageBytes))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjsonQM, err := ioutil.ReadAll(r)\n\terr = r.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(jsonQM, &queryMessage)\n\terr = r.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &queryMessage\n}", "func (q *CompoundQuery) GetCompressedQuery() []byte {\n\treturn flateCompressor.MustCompressString(\n\t\tojson.MarshalJSON(q),\n\t)\n}", "func (p *Packet) PackQuery() []byte {\n\tout := new(bytes.Buffer)\n\n\tp.packHeader(out)\n\tp.Question.pack(out)\n\n\tp.Bytes = out.Bytes() // swap in\n\treturn p.Bytes\n}", "func (s IntegrationSuite) TestCheckSchemaCompression(t *testing.T) {\n\tdir := getDir(t, \"testdata/validcfg\")\n\n\t// Ignore all linters except for the compression one\n\tforceOnlyRulesWarning(dir.Config, \"compression\")\n\topts, err := OptionsForDir(dir)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from OptionsForDir: %v\", err)\n\t}\n\tlogicalSchema := dir.LogicalSchemas[0]\n\twsOpts, err := workspace.OptionsForDir(dir, s.d.Instance)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from workspace.OptionsForDir: %v\", err)\n\t}\n\twsSchema, err := workspace.ExecLogicalSchema(logicalSchema, wsOpts)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error from workspace.ExecLogicalSchema: %v\", err)\n\t}\n\n\t// Count the InnoDB tables in the dir, for use in computing the expected\n\t// warning annotation count below\n\tvar innoTableCount int\n\tfor _, tbl := range wsSchema.Tables {\n\t\tif tbl.Engine == \"InnoDB\" {\n\t\t\tinnoTableCount++\n\t\t}\n\t}\n\n\t// Perform tests with various permutations of allow-list and flavor, and\n\t// confirm the number of annotations matches expectations. Note that the only\n\t// compressed tables in the dir are the two in testdata/validcfg/compression.sql;\n\t// one uses KEY_BLOCK_SIZE=2, and the other effectively uses 8 by way of\n\t// defaulting to half the page size.\n\tcases := []struct {\n\t\tallowList []string\n\t\tflavor tengo.Flavor\n\t\texpectedWarningCount int\n\t}{\n\t\t{[]string{\"8kb\"}, s.d.Flavor(), innoTableCount - 1},\n\t\t{[]string{\"page\", \"8kb\"}, tengo.FlavorMySQL57, innoTableCount - 1},\n\t\t{[]string{\"page\"}, tengo.FlavorMariaDB103, innoTableCount},\n\t\t{[]string{\"none\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"4kb\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"4kb\", \"page\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"none\", \"invalid-value\"}, s.d.Flavor(), 2},\n\t\t{[]string{\"invalid-value\"}, s.d.Flavor(), innoTableCount},\n\t}\n\tfor n, c := range cases {\n\t\topts.RuleConfig[\"compression\"] = c.allowList\n\t\topts.Flavor = c.flavor\n\t\tresult := CheckSchema(wsSchema, opts)\n\t\tif result.WarningCount != c.expectedWarningCount {\n\t\t\tt.Errorf(\"cases[%d] expected warning count %d, instead found %d\", n, c.expectedWarningCount, result.WarningCount)\n\t\t}\n\t}\n\n\t// If the Dockerized test instance's Flavor supports page compression, verify\n\t// that the regexp used by tableCompressionMode() works properly.\n\t// Store a mapping of table name -> expected 2nd return value of tableCompressionMode().\n\tvar tableExpectedClause map[string]string\n\tif s.d.Flavor().Min(tengo.FlavorMySQL57) {\n\t\tdir = getDir(t, \"testdata/pagecomprmysql\")\n\t\ttableExpectedClause = map[string]string{\n\t\t\t\"page_comp_zlib\": \"COMPRESSION='zlib'\",\n\t\t\t\"page_comp_lz4\": \"COMPRESSION='lz4'\",\n\t\t\t\"page_comp_none\": \"\",\n\t\t}\n\t} else if s.d.Flavor().Min(tengo.FlavorMariaDB102) {\n\t\tdir = getDir(t, \"testdata/pagecomprmaria\")\n\t\ttableExpectedClause = map[string]string{\n\t\t\t\"page_comp_1\": \"`PAGE_COMPRESSED`=1\",\n\t\t\t\"page_comp_on\": \"`PAGE_COMPRESSED`='on'\",\n\t\t\t\"page_comp_0\": \"\",\n\t\t\t\"page_comp_off\": \"\",\n\t\t}\n\t}\n\tif tableExpectedClause != nil {\n\t\tlogicalSchema := dir.LogicalSchemas[0]\n\t\twsOpts, err := workspace.OptionsForDir(dir, s.d.Instance)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error from workspace.OptionsForDir: %v\", err)\n\t\t}\n\t\twsSchema, err := workspace.ExecLogicalSchema(logicalSchema, wsOpts)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error from workspace.ExecLogicalSchema: %v\", err)\n\t\t}\n\t\tif len(wsSchema.Failures) > 0 {\n\t\t\tt.Fatalf(\"%d of the CREATEs in %s unexpectedly failed: %+v\", len(wsSchema.Failures), dir, wsSchema.Failures)\n\t\t}\n\t\tfor _, tbl := range wsSchema.Tables {\n\t\t\texpectedClause, ok := tableExpectedClause[tbl.Name]\n\t\t\tif !ok {\n\t\t\t\tt.Fatalf(\"Unexpectedly found table %s in dir %s, not present in tableExpectedClause mapping for flavor %s\", tbl.Name, dir, s.d.Flavor())\n\t\t\t}\n\t\t\tvar expectedMode string\n\t\t\tif expectedClause == \"\" {\n\t\t\t\texpectedMode = \"none\"\n\t\t\t} else {\n\t\t\t\texpectedMode = \"page\"\n\t\t\t}\n\t\t\tactualMode, actualClause := tableCompressionMode(tbl)\n\t\t\tif actualMode != expectedMode || actualClause != expectedClause {\n\t\t\t\tt.Errorf(\"Unexpected return value from tableCompressionMode(%s): got %q,%q; expected %q,%q\", tbl.Name, actualMode, actualClause, expectedMode, expectedClause)\n\t\t\t}\n\t\t}\n\t}\n}", "func CheckQueryPattern(b []byte) bool {\n\n\ttheQuery := string(b)\n\ttheQuery = strings.ToLower(theQuery)\n\ttheQuery = strings.TrimSpace(theQuery)\n\n\t// проверка на первый key_word\n\tif !strings.HasPrefix(theQuery, \"select\") {\n\t\treturn false\n\t}\n\n\tfor _, patt := range QueryPatterns {\n\t\tmatched, _ := regexp.Match(patt, []byte(theQuery))\n\t\tif matched {\n\t\t\treturn true // также надо запомнить, какой паттерн подошел\n\t\t}\n\t}\n\treturn false\n}", "func (o *StorageHyperFlexStorageContainer) HasUnCompressedUsedBytes() bool {\n\tif o != nil && o.UnCompressedUsedBytes != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func DeSerializeQuery(bytes []byte) Query {\n if len(bytes) != 32 {\n fmt.Println(\"Error : bytes length is not 32. Its \", len(bytes))\n }\n\n return Query {\n action : bytes[0],\n empty : 0,\n replyIp : binary.BigEndian.Uint32(bytes[2:6]),\n replyPort : binary.BigEndian.Uint16(bytes[6:8]),\n key : binary.BigEndian.Uint64(bytes[8:16]),\n value : binary.BigEndian.Uint64(bytes[16:24]),\n timeToLive: binary.BigEndian.Uint32(bytes[24:28]),\n requestId : binary.BigEndian.Uint32(bytes[28:32]),\n }\n}", "func MaxEncodedLen(ct CompressionType, srcLen uint64) (uint64, bool) {\n\tif ct == Snappy {\n\t\tif srcLen > MaxBlockLen(ct) {\n\t\t\treturn 0, false\n\t\t}\n\t\tsz := snappy.MaxEncodedLen(int(srcLen))\n\t\tif sz == -1 {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn uint64(sz), true\n\t}\n\tpanic(\"not supported compression type\")\n}", "func isQuery(msg []byte) (greatestCommonVersion int) {\n\tpos := bytes.Index(msg, queryMarker)\n\tif pos == -1 {\n\t\treturn 0\n\t}\n\tfor i, c := range msg[pos+len(queryMarker):] {\n\t\tif i == 0 {\n\t\t\tif c == '?' {\n\t\t\t\t// Indicates support for version 1, but we don't\n\t\t\t\t// implement that.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif c != 'v' {\n\t\t\t\t// Invalid message\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif c == '?' {\n\t\t\t// End of message\n\t\t\treturn\n\t\t}\n\n\t\tif c == ' ' || c == '\\t' {\n\t\t\t// Probably an invalid message\n\t\t\treturn 0\n\t\t}\n\n\t\tif c == '2' {\n\t\t\tgreatestCommonVersion = 2\n\t\t}\n\t}\n\n\treturn 0\n}", "func (qf QFrame) ByteSize() int {\n\ttotalSize := 0\n\tfor k, v := range qf.columnsByName {\n\t\ttotalSize += len(k)\n\t\ttotalSize += 40 // Estimate of map entry overhead\n\t\ttotalSize += 16 // String header map key\n\n\t\t// Column both in map and slice, hence 2 x, but don't double count the space\n\t\t// occupied by the columns itself.\n\t\ttotalSize += 2*v.ByteSize() - v.Column.ByteSize()\n\t}\n\n\ttotalSize += qf.index.ByteSize()\n\ttotalSize += 16 // Error interface\n\treturn totalSize\n}", "func (b *BloomFilter) ContainsBytes(value []byte) bool {\n\tres := true\n\tfor h := 0; h < b.k; h++ {\n\t\tindex := b.kiMiHash(value, h)\n\t\tif b.bucket.Bit(index) == 0 {\n\t\t\tres = false\n\t\t}\n\t}\n\treturn res\n}", "func uncompressedRowsSizeBytes(rows [][]Field) uint64 {\n\tn := uint64(0)\n\tfor _, fields := range rows {\n\t\tn += uncompressedRowSizeBytes(fields)\n\t}\n\treturn n\n}", "func uncompressedRowSizeBytes(fields []Field) uint64 {\n\tn := uint64(len(time.RFC3339Nano)) // log timestamp\n\tfor _, f := range fields {\n\t\tnameLen := len(f.Name)\n\t\tif nameLen == 0 {\n\t\t\tnameLen = len(\"_msg\")\n\t\t}\n\t\tn += uint64(2 + nameLen + len(f.Value))\n\t}\n\treturn n\n}", "func TestAddEdnsPaddingCompressedOptQuery(t *testing.T) {\n\toptQuery := simpleQuery\n\toptQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(optQuery.Additionals, simpleQuery.Additionals)\n\n\toptQuery.Additionals = append(optQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{},\n\t\t\t},\n\t\t},\n\t)\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&optQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad query with OPT but no padding: %v\", err)\n\t}\n\tif len(paddedOnWire)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad query with OPT but no padding\")\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that we correctly pad an uncompressed query to the nearest block.
func TestAddEdnsPaddingUncompressedQuery(t *testing.T) { if len(uncompressedQueryBytes)%PaddingBlockSize == 0 { t.Errorf("uncompressedQueryBytes does not require padding, so this test is invalid") } padded, err := AddEdnsPadding(uncompressedQueryBytes) if err != nil { panic(err) } if len(padded)%PaddingBlockSize != 0 { t.Errorf("AddEdnsPadding failed to correctly pad uncompressed query") } }
[ "func TestDnsMessageUncompressedQueryConfidenceCheck(t *testing.T) {\n\tm := mustUnpack(uncompressedQueryBytes)\n\tpackedBytes := mustPack(m)\n\tif len(packedBytes) >= len(uncompressedQueryBytes) {\n\t\tt.Errorf(\"Compressed query is not smaller than uncompressed query\")\n\t}\n}", "func TestDnsMessageCompressedQueryConfidenceCheck(t *testing.T) {\n\tm := mustUnpack(compressedQueryBytes)\n\tpackedBytes := mustPack(m)\n\tif len(packedBytes) != len(compressedQueryBytes) {\n\t\tt.Errorf(\"Packed query has different size than original:\\n %v\\n %v\", packedBytes, compressedQueryBytes)\n\t}\n}", "func TestAddEdnsPaddingCompressedPaddedQuery(t *testing.T) {\n\tpaddedQuery := simpleQuery\n\tpaddedQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(paddedQuery.Additionals, simpleQuery.Additionals)\n\n\tpaddedQuery.Additionals = append(paddedQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{\n\t\t\t\t\t{\n\t\t\t\t\t\tCode: OptResourcePaddingCode,\n\t\t\t\t\t\tData: make([]byte, 5),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\toriginalOnWire := mustPack(&paddedQuery)\n\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&paddedQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad padded query: %v\", err)\n\t}\n\n\tif !bytes.Equal(originalOnWire, paddedOnWire) {\n\t\tt.Errorf(\"AddEdnsPadding tampered with a query that was already padded\")\n\t}\n}", "func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {\n\t// Check if offset is one of the recent offsets.\n\t// Adjusts the output offset accordingly.\n\t// Gives a tiny bit of compression, typically around 1%.\n\tif true {\n\t\tif lits > 0 {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[0]:\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t} else {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[0] - 1:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t}\n\t} else {\n\t\toffset += 3\n\t}\n\treturn offset\n}", "func checksizeAndPad(plaintext []byte) []byte {\n\n\tmodulus := len(plaintext) % blowfish.BlockSize\n\tif modulus != 0 {\n\t\tpadlen := blowfish.BlockSize - modulus\n\n\t\t// add required padding\n\t\tfor i := 0; i < padlen; i++ {\n\t\t\tplaintext = append(plaintext, 0)\n\t\t}\n\t}\n\n\treturn plaintext\n}", "func blockPadding(offset int64) (n int64) {\n\treturn -offset & (blockSize - 1)\n}", "func checksizeAndPad(plaintext []byte) []byte {\n\n\t// calculate modulus of plaintext to blowfish's cipher block size\n\t// if result is not 0, then we need to pad\n\n\tmodulus := len(plaintext) % blowfish.BlockSize\n\tif modulus != 0 {\n\t\t// calc bytes we need to pad to make plaintext a multiple of block size\n\t\tpadlen := blowfish.BlockSize - modulus\n\n\t\t// add required padding\n\t\tfor i := 0; i < padlen; i++ {\n\t\t\tplaintext = append(plaintext, 0)\n\t\t}\n\t}\n\n\treturn plaintext\n}", "func TestAddEdnsPaddingCompressedOptQuery(t *testing.T) {\n\toptQuery := simpleQuery\n\toptQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(optQuery.Additionals, simpleQuery.Additionals)\n\n\toptQuery.Additionals = append(optQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{},\n\t\t\t},\n\t\t},\n\t)\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&optQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad query with OPT but no padding: %v\", err)\n\t}\n\tif len(paddedOnWire)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad query with OPT but no padding\")\n\t}\n}", "func (f *File) zeroPad(plainSize uint64) syscall.Errno {\n\tlastBlockLen := plainSize % f.contentEnc.PlainBS()\n\tif lastBlockLen == 0 {\n\t\t// Already block-aligned\n\t\treturn 0\n\t}\n\tmissing := f.contentEnc.PlainBS() - lastBlockLen\n\tpad := make([]byte, missing)\n\ttlog.Debug.Printf(\"zeroPad: Writing %d bytes\\n\", missing)\n\t_, errno := f.doWrite(pad, int64(plainSize))\n\treturn errno\n}", "func canonicalPadding(b []byte) error {\n\tswitch {\n\tcase b[0]&0x80 == 0x80:\n\t\treturn errNegativeValue\n\tcase len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80:\n\t\treturn errExcessivelyPaddedValue\n\tdefault:\n\t\treturn nil\n\t}\n}", "func legalSizeSameHeight(ar, _, br, _ int) bool {\n\treturn ar == br\n}", "func matchLenSSE4(a, b []byte, max int) int", "func (uc *Cypher) pkcs7unpad(padded []byte, blockSize int) []byte {\n\n\tdataLen := len(padded)\n\tpaddingCount := int(padded[dataLen-1])\n\n\tif paddingCount > blockSize || paddingCount <= 0 {\n\t\treturn padded //data is not padded (or not padded correctly), return as is\n\t}\n\n\tpadding := padded[dataLen-paddingCount : dataLen-1]\n\n\tfor _, b := range padding {\n\t\tif int(b) != paddingCount {\n\t\t\treturn padded //data is not padded (or not padded correcly), return as is\n\t\t}\n\t}\n\n\treturn padded[:len(padded)-paddingCount] //return data - padding\n}", "func TestHiddenWithPK1(t *testing.T) {\n\tdefer testutils.AfterTest(t)()\n\ttestutils.EnsureNoLeak(t)\n\tctx := context.Background()\n\n\ttae := testutil.InitTestDB(ctx, ModuleName, t, nil)\n\tdefer tae.Close()\n\tschema := catalog.MockSchemaAll(13, 2)\n\tschema.BlockMaxRows = 10\n\tschema.SegmentMaxBlocks = 2\n\tbat := catalog.MockBatch(schema, int(schema.BlockMaxRows*4))\n\tdefer bat.Close()\n\tbats := bat.Split(10)\n\n\ttxn, _, rel := testutil.CreateRelationNoCommit(t, tae, testutil.DefaultTestDB, schema, true)\n\terr := rel.Append(context.Background(), bats[0])\n\t{\n\t\toffsets := make([]uint32, 0)\n\t\tit := rel.MakeBlockIt()\n\t\tfor it.Valid() {\n\t\t\tblk := it.GetBlock()\n\t\t\tview, err := blk.GetColumnDataById(context.Background(), schema.PhyAddrKey.Idx)\n\t\t\tassert.NoError(t, err)\n\t\t\tdefer view.Close()\n\t\t\tfp := blk.Fingerprint()\n\t\t\t_ = view.GetData().Foreach(func(v any, _ bool, _ int) (err error) {\n\t\t\t\trid := v.(types.Rowid)\n\t\t\t\tbid, offset := rid.Decode()\n\t\t\t\tt.Logf(\"bid=%s,offset=%d\", bid.String(), offset)\n\t\t\t\tassert.Equal(t, fp.BlockID, bid)\n\t\t\t\toffsets = append(offsets, offset)\n\t\t\t\treturn\n\t\t\t}, nil)\n\t\t\tit.Next()\n\t\t}\n\t\t// sort.Slice(offsets, func(i, j int) bool { return offsets[i] < offsets[j] })\n\t\t// assert.Equal(t, []uint32{0, 1, 2, 3}, offsets)\n\t}\n\tassert.NoError(t, err)\n\tassert.NoError(t, txn.Commit(context.Background()))\n\n\ttxn, rel = testutil.GetDefaultRelation(t, tae, schema.Name)\n\t{\n\t\tblk := testutil.GetOneBlock(rel)\n\t\tview, err := blk.GetColumnDataByName(context.Background(), catalog.PhyAddrColumnName)\n\t\tassert.NoError(t, err)\n\t\tdefer view.Close()\n\t\toffsets := make([]uint32, 0)\n\t\tfp := blk.Fingerprint()\n\t\tt.Log(fp.String())\n\t\t_ = view.GetData().Foreach(func(v any, _ bool, _ int) (err error) {\n\t\t\trid := v.(types.Rowid)\n\t\t\tbid, offset := rid.Decode()\n\t\t\tt.Logf(\",bid=%s,offset=%d\", bid, offset)\n\t\t\tassert.Equal(t, fp.BlockID, bid)\n\t\t\toffsets = append(offsets, offset)\n\t\t\treturn\n\t\t}, nil)\n\t\tsort.Slice(offsets, func(i, j int) bool { return offsets[i] < offsets[j] })\n\t\tassert.Equal(t, []uint32{0, 1, 2, 3}, offsets)\n\t}\n\n\tassert.NoError(t, err)\n\tassert.NoError(t, txn.Commit(context.Background()))\n\n\ttxn, rel = testutil.GetDefaultRelation(t, tae, schema.Name)\n\terr = rel.Append(context.Background(), bats[1])\n\tassert.NoError(t, err)\n\terr = rel.Append(context.Background(), bats[2])\n\tassert.NoError(t, err)\n\terr = rel.Append(context.Background(), bats[3])\n\tassert.NoError(t, err)\n\terr = rel.Append(context.Background(), bats[4])\n\tassert.NoError(t, err)\n\terr = rel.Append(context.Background(), bats[5])\n\tassert.NoError(t, err)\n\tassert.NoError(t, txn.Commit(context.Background()))\n\n\ttestutil.CompactBlocks(t, 0, tae, \"db\", schema, false)\n\n\ttxn, rel = testutil.GetDefaultRelation(t, tae, schema.Name)\n\tvar segMeta *catalog.SegmentEntry\n\t{\n\t\tit := rel.MakeBlockIt()\n\t\tfor it.Valid() {\n\t\t\tblk := it.GetBlock()\n\t\t\tview, err := blk.GetColumnDataByName(context.Background(), catalog.PhyAddrColumnName)\n\t\t\tassert.NoError(t, err)\n\t\t\tdefer view.Close()\n\t\t\toffsets := make([]uint32, 0)\n\t\t\tmeta := blk.GetMeta().(*catalog.BlockEntry)\n\t\t\tt.Log(meta.String())\n\t\t\t_ = view.GetData().Foreach(func(v any, _ bool, _ int) (err error) {\n\t\t\t\trid := v.(types.Rowid)\n\t\t\t\tbid, offset := rid.Decode()\n\t\t\t\t// t.Logf(\"sid=%d,bid=%d,offset=%d\", sid, bid, offset)\n\t\t\t\tassert.Equal(t, meta.ID, bid)\n\t\t\t\toffsets = append(offsets, offset)\n\t\t\t\treturn\n\t\t\t}, nil)\n\t\t\tsort.Slice(offsets, func(i, j int) bool { return offsets[i] < offsets[j] })\n\t\t\tif meta.IsAppendable() {\n\t\t\t\tassert.Equal(t, []uint32{0, 1, 2, 3}, offsets)\n\t\t\t} else {\n\t\t\t\tsegMeta = meta.GetSegment()\n\t\t\t\tassert.Equal(t, []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, offsets)\n\t\t\t}\n\t\t\tit.Next()\n\t\t}\n\t}\n\n\tassert.NoError(t, txn.Commit(context.Background()))\n\t{\n\t\tseg := segMeta.GetSegmentData()\n\t\tfactory, taskType, scopes, err := seg.BuildCompactionTaskFactory()\n\t\tassert.NoError(t, err)\n\t\ttask, err := tae.Runtime.Scheduler.ScheduleMultiScopedTxnTask(tasks.WaitableCtx, taskType, scopes, factory)\n\t\tassert.NoError(t, err)\n\t\terr = task.WaitDone()\n\t\tassert.NoError(t, err)\n\t}\n\n\ttxn, rel = testutil.GetDefaultRelation(t, tae, schema.Name)\n\t{\n\t\tit := rel.MakeBlockIt()\n\t\tfor it.Valid() {\n\t\t\tblk := it.GetBlock()\n\t\t\tview, err := blk.GetColumnDataByName(context.Background(), catalog.PhyAddrColumnName)\n\t\t\tassert.NoError(t, err)\n\t\t\tdefer view.Close()\n\t\t\toffsets := make([]uint32, 0)\n\t\t\tmeta := blk.GetMeta().(*catalog.BlockEntry)\n\t\t\tt.Log(meta.String())\n\t\t\tt.Log(meta.GetSegment().String())\n\t\t\t_ = view.GetData().Foreach(func(v any, _ bool, _ int) (err error) {\n\t\t\t\trid := v.(types.Rowid)\n\t\t\t\tbid, offset := rid.Decode()\n\t\t\t\t// t.Logf(\"sid=%d,bid=%d,offset=%d\", sid, bid, offset)\n\t\t\t\tassert.Equal(t, meta.ID, bid)\n\t\t\t\toffsets = append(offsets, offset)\n\t\t\t\treturn\n\t\t\t}, nil)\n\t\t\tsort.Slice(offsets, func(i, j int) bool { return offsets[i] < offsets[j] })\n\t\t\tif meta.IsAppendable() {\n\t\t\t\tassert.Equal(t, []uint32{0, 1, 2, 3}, offsets)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, offsets)\n\t\t\t}\n\t\t\tit.Next()\n\t\t}\n\t}\n\n\tassert.NoError(t, txn.Commit(context.Background()))\n\tt.Log(tae.Catalog.SimplePPString(common.PPL1))\n}", "func (enc *encoder) padding(offset, algn int) int {\n\tabs := enc.pos + offset\n\tif abs%algn != 0 {\n\t\tnewabs := (abs + algn - 1) & ^(algn - 1)\n\t\treturn newabs - abs\n\t}\n\treturn 0\n}", "func (t *Table) dynamicPadding(row Row) {\n\tfor i, col := range row.Raw {\n\t\tcolLength := len(col) + 5\n\t\tif len(t.altPadding) < len(row.Raw) {\n\t\t\tt.altPadding = append(t.altPadding, colLength)\n\t\t} else if t.altPadding[i] < colLength {\n\t\t\tt.altPadding[i] = colLength\n\t\t}\n\t}\n}", "func (in *Input) Align() error {\n\tfor (in.ofs%4) != 0 && in.ofs < len(in.data) {\n\t\tin.ofs++\n\t}\n\tif (in.ofs % 4) != 0 {\n\t\treturn ErrTruncatedInput\n\t}\n\treturn nil\n}", "func CheckByteLayout(fail func(string, ...interface{})) {\n\tvar b *flatbuffers.Builder\n\n\tvar i int\n\tcheck := func(want []byte) {\n\t\ti++\n\t\tgot := b.Bytes[b.Head():]\n\t\tif !bytes.Equal(want, got) {\n\t\t\tfail(\"case %d: want\\n%v\\nbut got\\n%v\\n\", i, want, got)\n\t\t}\n\t}\n\n\t// test 1: numbers\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.PrependBool(true)\n\tcheck([]byte{1})\n\tb.PrependInt8(-127)\n\tcheck([]byte{129, 1})\n\tb.PrependUint8(255)\n\tcheck([]byte{255, 129, 1})\n\tb.PrependInt16(-32222)\n\tcheck([]byte{0x22, 0x82, 0, 255, 129, 1}) // first pad\n\tb.PrependUint16(0xFEEE)\n\tcheck([]byte{0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) // no pad this time\n\tb.PrependInt32(-53687092)\n\tcheck([]byte{204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\tb.PrependUint32(0x98765432)\n\tcheck([]byte{0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1})\n\n\t// test 1b: numbers 2\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.PrependUint64(0x1122334455667788)\n\tcheck([]byte{0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11})\n\n\t// test 2: 1xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartVector(flatbuffers.SizeByte, 1, 1)\n\tcheck([]byte{0, 0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 3: 2xbyte vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 2, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependByte(1)\n\tcheck([]byte{1, 0, 0})\n\tb.PrependByte(2)\n\tcheck([]byte{2, 1, 0, 0})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 2, 1, 0, 0}) // padding\n\n\t// test 3b: 11xbyte vector matches builder size\n\n\tb = flatbuffers.NewBuilder(12)\n\tb.StartVector(flatbuffers.SizeByte, 8, 1)\n\tstart := []byte{}\n\tcheck(start)\n\tfor i := 1; i < 12; i++ {\n\t\tb.PrependByte(byte(i))\n\t\tstart = append([]byte{byte(i)}, start...)\n\t\tcheck(start)\n\t}\n\tb.EndVector(8)\n\tcheck(append([]byte{8, 0, 0, 0}, start...))\n\n\t// test 4: 1xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 1, 1)\n\tcheck([]byte{0, 0}) // align to 4bytes\n\tb.PrependUint16(1)\n\tcheck([]byte{1, 0, 0, 0})\n\tb.EndVector(1)\n\tcheck([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding\n\n\t// test 5: 2xuint16 vector\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeUint16, 2, 1)\n\tcheck([]byte{}) // align to 4bytes\n\tb.PrependUint16(0xABCD)\n\tcheck([]byte{0xCD, 0xAB})\n\tb.PrependUint16(0xDCBA)\n\tcheck([]byte{0xBA, 0xDC, 0xCD, 0xAB})\n\tb.EndVector(2)\n\tcheck([]byte{2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB})\n\n\t// test 6: CreateString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateString(\"foo\")\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateString(\"moop\")\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 6b: CreateString unicode\n\n\tb = flatbuffers.NewBuilder(0)\n\t// These characters are chinese from blog.golang.org/strings\n\t// We use escape codes here so that editors without unicode support\n\t// aren't bothered:\n\tuni_str := \"\\u65e5\\u672c\\u8a9e\"\n\tb.CreateString(uni_str)\n\tcheck([]byte{9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad\n\t\t0, 0})\n\n\t// test 6c: CreateByteString\n\n\tb = flatbuffers.NewBuilder(0)\n\tb.CreateByteString([]byte(\"foo\"))\n\tcheck([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad\n\tb.CreateByteString([]byte(\"moop\"))\n\tcheck([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad\n\t\t3, 0, 0, 0, 'f', 'o', 'o', 0})\n\n\t// test 7: empty vtable\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(0)\n\tcheck([]byte{})\n\tb.EndObject()\n\tcheck([]byte{4, 0, 4, 0, 4, 0, 0, 0})\n\n\t// test 8: vtable with one true bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // length of object including vtable offset\n\t\t7, 0, // start of bool value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, 0, // padded to 4 bytes\n\t\t1, // bool value\n\t})\n\n\t// test 9: vtable with one default bool\n\tb = flatbuffers.NewBuilder(0)\n\tcheck([]byte{})\n\tb.StartObject(1)\n\tcheck([]byte{})\n\tb.PrependBoolSlot(0, false, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t4, 0, // vtable bytes\n\t\t4, 0, // end of object from here\n\t\t// entry 1 is zero and not stored.\n\t\t4, 0, 0, 0, // offset for start of vtable (int32)\n\t})\n\n\t// test 10: vtable with one int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependInt16Slot(0, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding to 4 bytes\n\t\t0x9A, 0x78,\n\t})\n\n\t// test 11: vtable with two int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependInt16Slot(1, 0x789A, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t4, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x9A, 0x78, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with int16 and bool\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 0x3456, 0)\n\tb.PrependBoolSlot(1, true, false)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t6, 0, // offset to value 0\n\t\t5, 0, // offset to value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t1, // value 1\n\t\t0x56, 0x34, // value 0\n\t})\n\n\t// test 12: vtable with empty vector\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend := b.EndVector(0)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset to vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0,\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 12b: vtable with empty vector of byte and some scalars\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeByte, 0, 1)\n\tvecend = b.EndVector(0)\n\tb.StartObject(2)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0,\n\t\t10, 0, // offset to value 0\n\t\t4, 0, // offset to vector offset\n\t\t8, 0, 0, 0, // vtable loc\n\t\t8, 0, 0, 0, // value 1\n\t\t0, 0, 55, 0, // value 0\n\n\t\t0, 0, 0, 0, // length of vector (not in struct)\n\t})\n\n\t// test 13: vtable with 1 int16 and 2-vector of int16\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt16, 2, 1)\n\tb.PrependInt16(0x1234)\n\tb.PrependInt16(0x5678)\n\tvecend = b.EndVector(2)\n\tb.StartObject(2)\n\tb.PrependUOffsetTSlot(1, vecend, 0)\n\tb.PrependInt16Slot(0, 55, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t8, 0, // vtable bytes\n\t\t12, 0, // length of object\n\t\t6, 0, // start of value 0 from end of vtable\n\t\t8, 0, // start of value 1 from end of buffer\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t55, 0, // value 0\n\t\t4, 0, 0, 0, // vector position from here\n\t\t2, 0, 0, 0, // length of vector (uint32)\n\t\t0x78, 0x56, // vector value 1\n\t\t0x34, 0x12, // vector value 0\n\t})\n\n\t// test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.Prep(4+4+4, 0)\n\tb.PrependInt8(55)\n\tb.Pad(3)\n\tb.PrependInt16(0x1234)\n\tb.Pad(2)\n\tb.PrependInt32(0x12345678)\n\tstructStart := b.Offset()\n\tb.PrependStructSlot(0, structStart, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t16, 0, // end of object from here\n\t\t4, 0, // start of struct from here\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0x78, 0x56, 0x34, 0x12, // value 2\n\t\t0, 0, // padding\n\t\t0x34, 0x12, // value 1\n\t\t0, 0, 0, // padding\n\t\t55, // value 0\n\t})\n\n\t// test 15: vtable with 1 vector of 2 struct of 2 int8\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartVector(flatbuffers.SizeInt8*2, 2, 1)\n\tb.PrependInt8(33)\n\tb.PrependInt8(44)\n\tb.PrependInt8(55)\n\tb.PrependInt8(66)\n\tvecend = b.EndVector(2)\n\tb.StartObject(1)\n\tb.PrependUOffsetTSlot(0, vecend, 0)\n\tb.EndObject()\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0,\n\t\t4, 0, // offset of vector offset\n\t\t6, 0, 0, 0, // offset for start of vtable (int32)\n\t\t4, 0, 0, 0, // vector start offset\n\n\t\t2, 0, 0, 0, // vector length\n\t\t66, // vector value 1,1\n\t\t55, // vector value 1,0\n\t\t44, // vector value 0,1\n\t\t33, // vector value 0,0\n\t})\n\n\t// test 16: table with some elements\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff := b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16b: same as test 16, size prefixed\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixed(off)\n\n\tcheck([]byte{\n\t\t20, 0, 0, 0, // size prefix\n\t\t12, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16c: same as test 16, with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 16d: same as test 16, size prefixed with file identifier\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt16Slot(1, 66, 0)\n\toff = b.EndObject()\n\tb.FinishSizePrefixedWithFileIdentifier(off, []byte(\"TEST\"))\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // size prefix\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\t\t'T', 'E', 'S', 'T', // file identifier\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // end of object from here\n\t\t7, 0, // start of value 0\n\t\t4, 0, // start of value 1\n\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\n\t\t66, 0, // value 1\n\t\t0, // padding\n\t\t33, // value 0\n\t})\n\n\t// test 17: one unfinished table and one finished table\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(2)\n\tb.PrependInt8Slot(0, 33, 0)\n\tb.PrependInt8Slot(1, 44, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tb.StartObject(3)\n\tb.PrependInt8Slot(0, 55, 0)\n\tb.PrependInt8Slot(1, 66, 0)\n\tb.PrependInt8Slot(2, 77, 0)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to object\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, // padding\n\t\t77, // value 2\n\t\t66, // value 1\n\t\t55, // value 0\n\n\t\t12, 0, 0, 0, // root of table: points to object\n\n\t\t8, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t8, 0, 0, 0, // offset for start of vtable (int32)\n\t\t0, 0, // padding\n\t\t44, // value 1\n\t\t33, // value 0\n\t})\n\n\t// test 18: a bunch of bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(8)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\tb.PrependBoolSlot(3, true, false)\n\tb.PrependBoolSlot(4, true, false)\n\tb.PrependBoolSlot(5, true, false)\n\tb.PrependBoolSlot(6, true, false)\n\tb.PrependBoolSlot(7, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t24, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t20, 0, // vtable bytes\n\t\t12, 0, // size of object\n\t\t11, 0, // start of value 0\n\t\t10, 0, // start of value 1\n\t\t9, 0, // start of value 2\n\t\t8, 0, // start of value 3\n\t\t7, 0, // start of value 4\n\t\t6, 0, // start of value 5\n\t\t5, 0, // start of value 6\n\t\t4, 0, // start of value 7\n\t\t20, 0, 0, 0, // vtable offset\n\n\t\t1, // value 7\n\t\t1, // value 6\n\t\t1, // value 5\n\t\t1, // value 4\n\t\t1, // value 3\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 19: three bools\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(3)\n\tb.PrependBoolSlot(0, true, false)\n\tb.PrependBoolSlot(1, true, false)\n\tb.PrependBoolSlot(2, true, false)\n\toff = b.EndObject()\n\tb.Finish(off)\n\n\tcheck([]byte{\n\t\t16, 0, 0, 0, // root of table: points to vtable offset\n\n\t\t0, 0, // padding\n\n\t\t10, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t7, 0, // start of value 0\n\t\t6, 0, // start of value 1\n\t\t5, 0, // start of value 2\n\t\t10, 0, 0, 0, // vtable offset from here\n\n\t\t0, // padding\n\t\t1, // value 2\n\t\t1, // value 1\n\t\t1, // value 0\n\t})\n\n\t// test 20: some floats\n\tb = flatbuffers.NewBuilder(0)\n\tb.StartObject(1)\n\tb.PrependFloat32Slot(0, 1.0, 0.0)\n\toff = b.EndObject()\n\n\tcheck([]byte{\n\t\t6, 0, // vtable bytes\n\t\t8, 0, // size of object\n\t\t4, 0, // start of value 0\n\t\t6, 0, 0, 0, // vtable offset\n\n\t\t0, 0, 128, 63, // value 0\n\t})\n}", "func isDiffVarintSnappyEncodedPostings(input []byte) bool {\n\treturn bytes.HasPrefix(input, []byte(codecHeaderSnappy))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to pad a query that already contains an OPT record, but no padding option.
func TestAddEdnsPaddingCompressedOptQuery(t *testing.T) { optQuery := simpleQuery optQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals)) copy(optQuery.Additionals, simpleQuery.Additionals) optQuery.Additionals = append(optQuery.Additionals, dnsmessage.Resource{ Header: dnsmessage.ResourceHeader{ Name: dnsmessage.MustNewName("."), Class: dnsmessage.ClassINET, TTL: 0, }, Body: &dnsmessage.OPTResource{ Options: []dnsmessage.Option{}, }, }, ) paddedOnWire, err := AddEdnsPadding(mustPack(&optQuery)) if err != nil { t.Errorf("Failed to pad query with OPT but no padding: %v", err) } if len(paddedOnWire)%PaddingBlockSize != 0 { t.Errorf("AddEdnsPadding failed to correctly pad query with OPT but no padding") } }
[ "func addOptionalPadding(s string) string {\n\tif l := len(s) % 4; l > 0 {\n\t\ts += strings.Repeat(\"=\", 4-l)\n\t}\n\treturn s\n}", "func WithPadding(padding float64) Option {\n\treturn func(m *Margaid) {\n\t\tfactor := padding / 100\n\t\tm.padding = math.Max(0, math.Min(0.20, factor))\n\t}\n}", "func pad(unpadded []byte, desiredLength int) []byte {\n\tif len(unpadded) == desiredLength {\n\t\treturn unpadded\n\t}\n\ttoAppend := desiredLength - len(unpadded)\n\treturn append(unpadded, bytes.Repeat([]byte{byte(0x00)}, toAppend)...)\n}", "func WithPaddingAllowed() ParserOption {\n\treturn func(p *Parser) {\n\t\tp.decodePaddingAllowed = true\n\t}\n}", "func Padding(pixels int) LayoutOption {\r\n\treturn func(p *app.LayoutProps) {\r\n\t\tp.Padding = pixels\r\n\t}\r\n}", "func (o FlipBookOptions) Padding(i Insets) FlipBookOpt {\n\treturn func(f *FlipBook) {\n\t\tf.anchorLayoutOpts = append(f.anchorLayoutOpts, AnchorLayoutOpts.Padding(i))\n\t}\n}", "func padWithSpace(source string, prefix, suffix int) string {\n\tif source == \"\" {\n\t\treturn source\n\t}\n\treturn strings.Repeat(\" \", prefix) + source + strings.Repeat(\" \", suffix)\n}", "func padWithSpace(source string, prefix, suffix int) string {\n\tif source == \"\" {\n\t\treturn source\n\t}\n\n\treturn strings.Repeat(\" \", prefix) + source + strings.Repeat(\" \", suffix)\n}", "func (enc Encoding) WithPadding(padding rune) *Encoding {}", "func TestAddEdnsPaddingCompressedPaddedQuery(t *testing.T) {\n\tpaddedQuery := simpleQuery\n\tpaddedQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(paddedQuery.Additionals, simpleQuery.Additionals)\n\n\tpaddedQuery.Additionals = append(paddedQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{\n\t\t\t\t\t{\n\t\t\t\t\t\tCode: OptResourcePaddingCode,\n\t\t\t\t\t\tData: make([]byte, 5),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\toriginalOnWire := mustPack(&paddedQuery)\n\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&paddedQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad padded query: %v\", err)\n\t}\n\n\tif !bytes.Equal(originalOnWire, paddedOnWire) {\n\t\tt.Errorf(\"AddEdnsPadding tampered with a query that was already padded\")\n\t}\n}", "func PADDB(mx, x operand.Op) { ctx.PADDB(mx, x) }", "func (g *GroupedAVP) Padding() int {\n\treturn 0\n}", "func TestAddEdnsPaddingUncompressedQuery(t *testing.T) {\n\tif len(uncompressedQueryBytes)%PaddingBlockSize == 0 {\n\t\tt.Errorf(\"uncompressedQueryBytes does not require padding, so this test is invalid\")\n\t}\n\tpadded, err := AddEdnsPadding(uncompressedQueryBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(padded)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad uncompressed query\")\n\t}\n}", "func (enc Encoding) WithPadding(padding rune) *Encoding {\n\tswitch {\n\tcase padding < NoPadding || padding == '\\r' || padding == '\\n' || padding > 0xff:\n\t\tpanic(\"invalid padding\")\n\tcase padding != NoPadding && enc.decodeMap[byte(padding)] != invalidIndex:\n\t\tpanic(\"padding contained in alphabet\")\n\t}\n\tenc.padChar = padding\n\treturn &enc\n}", "func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string {\n\n\t// When padded length is less then the current string size\n\tif padLen < utf8.RuneCountInString(str) {\n\t\treturn str\n\t}\n\n\tpadLen -= utf8.RuneCountInString(str)\n\n\ttargetLen := padLen\n\n\ttargetLenLeft := targetLen\n\ttargetLenRight := targetLen\n\tif padLeft && padRight {\n\t\ttargetLenLeft = padLen / 2\n\t\ttargetLenRight = padLen - targetLenLeft\n\t}\n\n\tstrToRepeatLen := utf8.RuneCountInString(padStr)\n\n\trepeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen)))\n\trepeatedString := strings.Repeat(padStr, repeatTimes)\n\n\tleftSide := \"\"\n\tif padLeft {\n\t\tleftSide = repeatedString[0:targetLenLeft]\n\t}\n\n\trightSide := \"\"\n\tif padRight {\n\t\trightSide = repeatedString[0:targetLenRight]\n\t}\n\n\treturn leftSide + str + rightSide\n}", "func UseDataPadding(p uint64) Option {\n\treturn func(o *Options) {\n\t\to.DataPadding = p\n\t}\n}", "func PADDD(mx, x operand.Op) { ctx.PADDD(mx, x) }", "func pad(b *bytes.Buffer, str string) {\n\tif b.Len() == 0 {\n\t\treturn\n\t}\n\tb.WriteString(str)\n}", "func (c *Context) PADDB(mx, x operand.Op) {\n\tc.addinstruction(x86.PADDB(mx, x))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to pad a query that already contains an OPT record with padding. The query should be unmodified by AddEdnsPadding.
func TestAddEdnsPaddingCompressedPaddedQuery(t *testing.T) { paddedQuery := simpleQuery paddedQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals)) copy(paddedQuery.Additionals, simpleQuery.Additionals) paddedQuery.Additionals = append(paddedQuery.Additionals, dnsmessage.Resource{ Header: dnsmessage.ResourceHeader{ Name: dnsmessage.MustNewName("."), Class: dnsmessage.ClassINET, TTL: 0, }, Body: &dnsmessage.OPTResource{ Options: []dnsmessage.Option{ { Code: OptResourcePaddingCode, Data: make([]byte, 5), }, }, }, }, ) originalOnWire := mustPack(&paddedQuery) paddedOnWire, err := AddEdnsPadding(mustPack(&paddedQuery)) if err != nil { t.Errorf("Failed to pad padded query: %v", err) } if !bytes.Equal(originalOnWire, paddedOnWire) { t.Errorf("AddEdnsPadding tampered with a query that was already padded") } }
[ "func TestAddEdnsPaddingCompressedOptQuery(t *testing.T) {\n\toptQuery := simpleQuery\n\toptQuery.Additionals = make([]dnsmessage.Resource, len(simpleQuery.Additionals))\n\tcopy(optQuery.Additionals, simpleQuery.Additionals)\n\n\toptQuery.Additionals = append(optQuery.Additionals,\n\t\tdnsmessage.Resource{\n\t\t\tHeader: dnsmessage.ResourceHeader{\n\t\t\t\tName: dnsmessage.MustNewName(\".\"),\n\t\t\t\tClass: dnsmessage.ClassINET,\n\t\t\t\tTTL: 0,\n\t\t\t},\n\t\t\tBody: &dnsmessage.OPTResource{\n\t\t\t\tOptions: []dnsmessage.Option{},\n\t\t\t},\n\t\t},\n\t)\n\tpaddedOnWire, err := AddEdnsPadding(mustPack(&optQuery))\n\tif err != nil {\n\t\tt.Errorf(\"Failed to pad query with OPT but no padding: %v\", err)\n\t}\n\tif len(paddedOnWire)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad query with OPT but no padding\")\n\t}\n}", "func addOptionalPadding(s string) string {\n\tif l := len(s) % 4; l > 0 {\n\t\ts += strings.Repeat(\"=\", 4-l)\n\t}\n\treturn s\n}", "func TestAddEdnsPaddingUncompressedQuery(t *testing.T) {\n\tif len(uncompressedQueryBytes)%PaddingBlockSize == 0 {\n\t\tt.Errorf(\"uncompressedQueryBytes does not require padding, so this test is invalid\")\n\t}\n\tpadded, err := AddEdnsPadding(uncompressedQueryBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(padded)%PaddingBlockSize != 0 {\n\t\tt.Errorf(\"AddEdnsPadding failed to correctly pad uncompressed query\")\n\t}\n}", "func WithPadding(padding float64) Option {\n\treturn func(m *Margaid) {\n\t\tfactor := padding / 100\n\t\tm.padding = math.Max(0, math.Min(0.20, factor))\n\t}\n}", "func pad(unpadded []byte, desiredLength int) []byte {\n\tif len(unpadded) == desiredLength {\n\t\treturn unpadded\n\t}\n\ttoAppend := desiredLength - len(unpadded)\n\treturn append(unpadded, bytes.Repeat([]byte{byte(0x00)}, toAppend)...)\n}", "func (enc Encoding) WithPadding(padding rune) *Encoding {}", "func Padding(pixels int) LayoutOption {\r\n\treturn func(p *app.LayoutProps) {\r\n\t\tp.Padding = pixels\r\n\t}\r\n}", "func (o FlipBookOptions) Padding(i Insets) FlipBookOpt {\n\treturn func(f *FlipBook) {\n\t\tf.anchorLayoutOpts = append(f.anchorLayoutOpts, AnchorLayoutOpts.Padding(i))\n\t}\n}", "func padWithSpace(source string, prefix, suffix int) string {\n\tif source == \"\" {\n\t\treturn source\n\t}\n\n\treturn strings.Repeat(\" \", prefix) + source + strings.Repeat(\" \", suffix)\n}", "func padWithSpace(source string, prefix, suffix int) string {\n\tif source == \"\" {\n\t\treturn source\n\t}\n\treturn strings.Repeat(\" \", prefix) + source + strings.Repeat(\" \", suffix)\n}", "func WithPaddingAllowed() ParserOption {\n\treturn func(p *Parser) {\n\t\tp.decodePaddingAllowed = true\n\t}\n}", "func PADDB(mx, x operand.Op) { ctx.PADDB(mx, x) }", "func (enc Encoding) WithPadding(padding rune) *Encoding {\n\tswitch {\n\tcase padding < NoPadding || padding == '\\r' || padding == '\\n' || padding > 0xff:\n\t\tpanic(\"invalid padding\")\n\tcase padding != NoPadding && enc.decodeMap[byte(padding)] != invalidIndex:\n\t\tpanic(\"padding contained in alphabet\")\n\t}\n\tenc.padChar = padding\n\treturn &enc\n}", "func PADDD(mx, x operand.Op) { ctx.PADDD(mx, x) }", "func (c *Context) PADDB(mx, x operand.Op) {\n\tc.addinstruction(x86.PADDB(mx, x))\n}", "func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string {\n\n\t// When padded length is less then the current string size\n\tif padLen < utf8.RuneCountInString(str) {\n\t\treturn str\n\t}\n\n\tpadLen -= utf8.RuneCountInString(str)\n\n\ttargetLen := padLen\n\n\ttargetLenLeft := targetLen\n\ttargetLenRight := targetLen\n\tif padLeft && padRight {\n\t\ttargetLenLeft = padLen / 2\n\t\ttargetLenRight = padLen - targetLenLeft\n\t}\n\n\tstrToRepeatLen := utf8.RuneCountInString(padStr)\n\n\trepeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen)))\n\trepeatedString := strings.Repeat(padStr, repeatTimes)\n\n\tleftSide := \"\"\n\tif padLeft {\n\t\tleftSide = repeatedString[0:targetLenLeft]\n\t}\n\n\trightSide := \"\"\n\tif padRight {\n\t\trightSide = repeatedString[0:targetLenRight]\n\t}\n\n\treturn leftSide + str + rightSide\n}", "func (g *GroupedAVP) Padding() int {\n\treturn 0\n}", "func (t *Table) dynamicPadding(row Row) {\n\tfor i, col := range row.Raw {\n\t\tcolLength := len(col) + 5\n\t\tif len(t.altPadding) < len(row.Raw) {\n\t\t\tt.altPadding = append(t.altPadding, colLength)\n\t\t} else if t.altPadding[i] < colLength {\n\t\t\tt.altPadding[i] = colLength\n\t\t}\n\t}\n}", "func UseDataPadding(p uint64) Option {\n\treturn func(o *Options) {\n\t\to.DataPadding = p\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK creates a ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK with default headers values
func NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK() *ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK { return &ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK{} }
[ "func NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity() *ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity {\n\treturn &ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity{}\n}", "func (i *IPlayerService) GetSteamLevel() (*geyser.Request, error) {\n\tsm, err := i.Interface.Methods.Get(schema.MethodKey{\n\t\tName: \"GetSteamLevel\",\n\t\tVersion: 1,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := geyser.NewRequest(i.Interface, sm)\n\n\treturn req, nil\n}", "func (o *GetClockParams) WithDefaults() *GetClockParams {\n\to.SetDefaults()\n\treturn o\n}", "func NewGetClockParams() *GetClockParams {\n\treturn &GetClockParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func New(apikey string) *Steam {\n\tclient := new(http.Client)\n\t//Steam identifier\n\tvar identifier uint64 = 76561197960265728\n\treturn &Steam{apikey, client, identifier}\n}", "func (s *SandboxdDhparams2048) Get(client sophos.ClientInterface, options ...sophos.Option) (err error) {\n\treturn get(client, \"/api/nodes/sandboxd.dhparams_2048\", &s.Value, options...)\n}", "func (c *impl) generateAuthParamGet() string {\n\tts := time.Now().UTC().Unix()\n\tstringToHash := fmt.Sprintf(\"%d%s%s\", ts, c.cfg.Marvel.PrivateKey, c.cfg.Marvel.PublicKey)\n\thash := md5.Sum([]byte(stringToHash))\n\treturn fmt.Sprintf(\"apikey=%s&ts=%d&hash=%s\", c.cfg.Marvel.PublicKey, ts, hex.EncodeToString(hash[:]))\n}", "func NewGetClockParamsWithHTTPClient(client *http.Client) *GetClockParams {\n\treturn &GetClockParams{\n\t\tHTTPClient: client,\n\t}\n}", "func NewGetVCenterUsingGETForbidden() *GetVCenterUsingGETForbidden {\n\treturn &GetVCenterUsingGETForbidden{}\n}", "func (vk VK) GiftsGet(params map[string]string) (response GiftsGetResponse, vkErr Error) {\n\trawResponse, vkErr := vk.Request(\"gifts.get\", params)\n\tif vkErr.Code != 0 {\n\t\treturn\n\t}\n\n\terr := json.Unmarshal(rawResponse, &response)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn\n}", "func NewGetPracticesDefault(code int) *GetPracticesDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &GetPracticesDefault{\n\t\t_statusCode: code,\n\t}\n}", "func GetOwnedGamesByPlayerID(w http.ResponseWriter, r *http.Request) {\n\tapiKey := os.Getenv(\"STEAM_API_KEY\")\n\n\tif apiKey == \"\" {\n\t\tlog.Printf(\"[ERROR] Environment variable STEAM_API_KEY must be specified\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(&ErrorMessage{\"Environment variable STEAM_API_KEY must be specified\"})\n\t\treturn\n\t}\n\n\tvars := mux.Vars(r)\n\tsteamID := vars[\"player-id\"]\n\n\tlog.Printf(\"[INFO] GET /players/%s/games\", steamID)\n\n\t// Build a request\n\treq, _ := http.NewRequest(\"GET\", \"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/\", nil)\n\tq := req.URL.Query()\n\tq.Add(\"key\", apiKey)\n\tq.Add(\"steamid\", steamID)\n\tq.Add(\"include_appinfo\", \"true\")\n\tq.Add(\"format\", \"json\")\n\treq.URL.RawQuery = q.Encode()\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\thttpResp, httpErr := httpClient.Do(req)\n\n\tif httpErr != nil {\n\t\tlog.Printf(\"[ERROR] During get a HTTP response %s\", httpErr.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(&ErrorMessage{httpErr.Error()})\n\t\treturn\n\t}\n\n\tdefer httpResp.Body.Close()\n\n\t// A HTTP response deserialization\n\tbody, readErr := ioutil.ReadAll(httpResp.Body)\n\tif readErr != nil {\n\t\tlog.Printf(\"[ERROR] When reading a HTTP response body: %s\", readErr.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(&ErrorMessage{readErr.Error()})\n\t\treturn\n\t}\n\n\tvar response *Response\n\tjsonErr := json.Unmarshal(body, &response)\n\tif jsonErr != nil {\n\t\tlog.Printf(\"[ERROR] When during unmarshall: %s\", jsonErr.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(&ErrorMessage{jsonErr.Error()})\n\t\treturn\n\t}\n\n\tlog.Printf(\"[INFO] Recieved %d Game elements\", len(response.Body.Games))\n\n\t// Build a response\n\tjson.NewEncoder(w).Encode(&response.Body.Games)\n}", "func (o *Get0Params) WithTimeout(timeout time.Duration) *Get0Params {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func Get(alg string, bits int) ([]byte, error) {\n\tcfg := newJwks(alg, bits)\n\tdata, err := cfg.generateJwksSecret()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to generate key key\")\n\t}\n\n\tpatchContent := []jwksPatchJSON{{\n\t\tOp: \"add\",\n\t\tPath: \"/data\",\n\t\tValue: jwksPatchJSONValue{\n\t\t\tJwks: data,\n\t\t},\n\t}}\n\n\tpatchDataJSON, err := json.Marshal(patchContent)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to marshal key\")\n\t}\n\n\treturn patchDataJSON, nil\n}", "func passThroughGETWithBasicAuthToOpenLaw(w http.ResponseWriter, r *http.Request){\n\t// dashboard: https://console.kaleido.io/dashboard/openlaw/u0vvwcatsl/u0ztgr50os/u0gzl2r9pj/u0flnq9hwd\n\t// TODO: make the auth code modular\n\tresource := \"/app/login\"\n\tur, _ := url.ParseRequestURI(\"kaleidoInstance\")\n\tur.Path = resource\n\turlStr := ur.String()\n\n\tdata := url.Values{}\n\tdata.Set(\"userId\", config.OpenLawUsername)\n\tdata.Set(\"password\", config.OpenLawPassword)\n\n\n\tnewR, _ := http.NewRequest(\"POST\", urlStr, strings.NewReader(data.Encode())) // URL-encoded payload\n\tnewR.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tnewR.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\tnewR.SetBasicAuth(config.BasicAuthUser,config.BasicAuthPass)\n\trespon := OpenlawJWT{}\n\n\tresp, err := netClient.Do(newR)\n\n\t// assign error\n\tif err!= nil {\n\t\trespon.Error = err.Error()\n\t\tlog.Error().Msg(\"openlaw request time out or failure!\")\n\t}\n\n\t// assign jwt and response code\n\tif resp!= nil{\n\t\trespon.Jwt = resp.Header.Get(\"OPENLAW_JWT\")\n\t}\n\n\n\n\t// TODO; support more than just GET\n\n\tnewURL := r.URL.String()\n\tnewURL = strings.Replace(newURL, \"/passThroughGETWithBasicAuthToOpenLaw\", \"\",1)\n\tu, _ := url.ParseRequestURI(\"kaleidoInstance\" + newURL)\n\tlog.Info().Msg(\"new url: \" + u.String())\n\n\treq, _ := http.NewRequest(\"GET\",u.String(), nil)\n\treq.Header.Add(\"OPENLAW_JWT\", respon.Jwt)\n\n\t//req, _ := http.NewRequest(\"GET\",u.String(), nil)\n\treq.SetBasicAuth(config.BasicAuthUser,config.BasicAuthPass)\n\treq.Header.Add(\"Cookie\",\"OPENLAW_SESSION=xx\")\n\tresponse, err := netClient.Do(req)\n\n\tif err!=nil{\n\t\trespondWithError(w,http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tbody, _ := ioutil.ReadAll(response.Body)\n\tw.WriteHeader(response.StatusCode)\n\tw.Write(body)\n\n}", "func NewGetVCenterUsingGETUnauthorized() *GetVCenterUsingGETUnauthorized {\n\treturn &GetVCenterUsingGETUnauthorized{}\n}", "func (o *GetClockParams) WithTimeout(timeout time.Duration) *GetClockParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func NewGetCustomIntegrationVersionsByIDUsingGETUnauthorized() *GetCustomIntegrationVersionsByIDUsingGETUnauthorized {\n\treturn &GetCustomIntegrationVersionsByIDUsingGETUnauthorized{}\n}", "func NewGetCustomIntegrationVersionsByIDUsingGETForbidden() *GetCustomIntegrationVersionsByIDUsingGETForbidden {\n\treturn &GetCustomIntegrationVersionsByIDUsingGETForbidden{}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity creates a ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity with default headers values
func NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity() *ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity { return &ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetUnprocessableEntity{} }
[ "func NewGetTaskDetailsUnprocessableEntity() *GetTaskDetailsUnprocessableEntity {\n\n\treturn &GetTaskDetailsUnprocessableEntity{}\n}", "func NewGetAPIPublicV1TeamUnprocessableEntity() *GetAPIPublicV1TeamUnprocessableEntity {\n\treturn &GetAPIPublicV1TeamUnprocessableEntity{}\n}", "func NewWeaviateKeyCreateUnprocessableEntity() *WeaviateKeyCreateUnprocessableEntity {\n\treturn &WeaviateKeyCreateUnprocessableEntity{}\n}", "func NewGetGroupUnprocessableEntity() *GetGroupUnprocessableEntity {\n\treturn &GetGroupUnprocessableEntity{}\n}", "func NewGetPlacementsUnprocessableEntity() *GetPlacementsUnprocessableEntity {\n\treturn &GetPlacementsUnprocessableEntity{}\n}", "func NewGetWopiDocumentContentUnprocessableEntity() *GetWopiDocumentContentUnprocessableEntity {\n\treturn &GetWopiDocumentContentUnprocessableEntity{}\n}", "func NewGetFlagWorkflowsUnprocessableEntity() *GetFlagWorkflowsUnprocessableEntity {\n\treturn &GetFlagWorkflowsUnprocessableEntity{}\n}", "func NewGetPaymentRequestEDIUnprocessableEntity() *GetPaymentRequestEDIUnprocessableEntity {\n\n\treturn &GetPaymentRequestEDIUnprocessableEntity{}\n}", "func NewGetDeltaUnprocessableEntity() *GetDeltaUnprocessableEntity {\n\treturn &GetDeltaUnprocessableEntity{}\n}", "func NewGetDocumentUnprocessableEntity() *GetDocumentUnprocessableEntity {\n\n\treturn &GetDocumentUnprocessableEntity{}\n}", "func NewGetNodeUnprocessableEntity() *GetNodeUnprocessableEntity {\n\treturn &GetNodeUnprocessableEntity{}\n}", "func NewModifyCryptokeyUnprocessableEntity() *ModifyCryptokeyUnprocessableEntity {\n\treturn &ModifyCryptokeyUnprocessableEntity{}\n}", "func NewGetAttendanceWorkflowsUnprocessableEntity() *GetAttendanceWorkflowsUnprocessableEntity {\n\treturn &GetAttendanceWorkflowsUnprocessableEntity{}\n}", "func NewCreateanewRtcSessionUnprocessableEntity() *CreateanewRtcSessionUnprocessableEntity {\n\treturn &CreateanewRtcSessionUnprocessableEntity{}\n}", "func NewGetKillmailsKillmailIDKillmailHashUnprocessableEntity() *GetKillmailsKillmailIDKillmailHashUnprocessableEntity {\n\treturn &GetKillmailsKillmailIDKillmailHashUnprocessableEntity{}\n}", "func NewProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK() *ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK {\n\treturn &ProtectedGetPlaytimeGameTelemetryV1ProtectedSteamIdsSteamIDPlaytimeGetOK{}\n}", "func NewUpdateDatagroupUnprocessableEntity() *UpdateDatagroupUnprocessableEntity {\n\treturn &UpdateDatagroupUnprocessableEntity{}\n}", "func NewGetUniversitiesUnprocessableEntity() *GetUniversitiesUnprocessableEntity {\n\n\treturn &GetUniversitiesUnprocessableEntity{}\n}", "func NewWeaviateThingsPatchUnprocessableEntity() *WeaviateThingsPatchUnprocessableEntity {\n\treturn &WeaviateThingsPatchUnprocessableEntity{}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewPaddingTLV creates a new padding TLV
func NewPaddingTLV(length uint8) *PaddingTLV { return &PaddingTLV{ TLVType: PaddingType, TLVLength: length, PaddingData: make([]byte, length), } }
[ "func (enc Encoding) WithPadding(padding rune) *Encoding {}", "func (p *PaddingTLV) Length() uint8 {\n\treturn p.TLVLength\n}", "func pad(unpadded []byte, desiredLength int) []byte {\n\tif len(unpadded) == desiredLength {\n\t\treturn unpadded\n\t}\n\ttoAppend := desiredLength - len(unpadded)\n\treturn append(unpadded, bytes.Repeat([]byte{byte(0x00)}, toAppend)...)\n}", "func (t Time) Padding() int {\n\treturn 0\n}", "func (p *PaddingTLV) Serialize(buf *bytes.Buffer) {\n\tbuf.WriteByte(p.TLVType)\n\tbuf.WriteByte(p.TLVLength)\n\tbuf.Write(p.PaddingData)\n}", "func getPadding(packetLen int) int {\n\tif packetLen%4 == 0 {\n\t\treturn 0\n\t}\n\treturn 4 - (packetLen % 4)\n}", "func setupPadding() {\n\n\tpaddingMap[0] = \"10101010101010101010101010101010\"\n\tpaddingMap[1] = \"0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f\"\n\tpaddingMap[2] = \"0e0e0e0e0e0e0e0e0e0e0e0e0e0e\"\n\tpaddingMap[3] = \"0d0d0d0d0d0d0d0d0d0d0d0d0d\"\n\tpaddingMap[4] = \"0c0c0c0c0c0c0c0c0c0c0c0c\"\n\tpaddingMap[5] = \"0b0b0b0b0b0b0b0b0b0b0b\"\n\tpaddingMap[6] = \"0a0a0a0a0a0a0a0a0a0a\"\n\tpaddingMap[7] = \"090909090909090909\"\n\tpaddingMap[8] = \"0808080808080808\"\n\tpaddingMap[9] = \"07070707070707\"\n\tpaddingMap[10] = \"060606060606\"\n\tpaddingMap[11] = \"0505050505\"\n\tpaddingMap[12] = \"04040404\"\n\tpaddingMap[13] = \"030303\"\n\tpaddingMap[14] = \"0202\"\n\tpaddingMap[15] = \"01\"\n}", "func EncodingWithPadding(enc base64.Encoding, padding rune) *base64.Encoding", "func createPad(N uint64, keyPrefix string, valuePrefix []byte, snapLen uint64,\n\tafterCreateCB func(pad *PAD),\n\tafterInsertCB func(iteration uint64, pad *PAD)) (*PAD, error) {\n\tpad, err := NewPAD(TestAd{\"\"}, signKey, vrfKey, snapLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif afterCreateCB != nil {\n\t\tafterCreateCB(pad)\n\t}\n\n\tfor i := uint64(0); i < N; i++ {\n\t\tkey := keyPrefix + strconv.FormatUint(i, 10)\n\t\tvalue := append(valuePrefix, byte(i))\n\t\tif err := pad.Set(key, value); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Couldn't set key=%s and value=%s. Error: %v\",\n\t\t\t\tkey, value, err)\n\t\t}\n\t\tif afterInsertCB != nil {\n\t\t\tafterInsertCB(i, pad)\n\t\t}\n\t}\n\treturn pad, nil\n}", "func (enc Encoding) WithPadding(padding rune) *Encoding {\n\tswitch {\n\tcase padding < NoPadding || padding == '\\r' || padding == '\\n' || padding > 0xff:\n\t\tpanic(\"invalid padding\")\n\tcase padding != NoPadding && enc.decodeMap[byte(padding)] != invalidIndex:\n\t\tpanic(\"padding contained in alphabet\")\n\t}\n\tenc.padChar = padding\n\treturn &enc\n}", "func Padding(source []byte) (dst []byte, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = errors.New(r.(string))\n\t\t\tdst = nil\n\t\t}\n\t}()\n\tdiff := len(source) % aes.BlockSize\n\tpaddingLength := aes.BlockSize - diff\n\tbuffer := bytes.Buffer{}\n\t// this function is not gonna return an error\n\t// it would panic with something going wrong\n\tbuffer.Write(source)\n\tbuffer.Write(make([]byte, paddingLength-1))\n\tbuffer.WriteByte(byte(int8(paddingLength)))\n\tdst = buffer.Bytes()\n\treturn\n}", "func (g *GroupedAVP) Padding() int {\n\treturn 0\n}", "func append_padding_bytes(data []byte) []byte {\n\tpadLen := 16 - len(data)%16\n\tvar padding = make([]byte, padLen)\n\n\t// \"i\" bytes of value \"i\" are appended to the message\n\tfor i := 0; i < padLen; i++ {\n\t\tpadding[i] = byte(padLen)\n\t}\n\n\treturn append(data, padding[:]...)\n}", "func add_pkcs7_padding(input []byte, blocksize int) []byte {\n\tdata := input\n\t// Calculate pad number\n\tn := blocksize - (len(data) % blocksize)\n\t// Fill rest with n\n\tfor i := 0; i < n; i++ {\n\t\tdata = append(data, byte(n))\n\t}\n\treturn data\n}", "func (p *PaddingTLV) Value() interface{} {\n\treturn p\n}", "func padding(b []byte) []byte {\n\tl := uint16(len(b))\n\treturn append(b, make([]byte, align(l)-l)...)\n}", "func WithPadding(padding float64) Option {\n\treturn func(m *Margaid) {\n\t\tfactor := padding / 100\n\t\tm.padding = math.Max(0, math.Min(0.20, factor))\n\t}\n}", "func (enc *encoder) padding(offset, algn int) int {\n\tabs := enc.pos + offset\n\tif abs%algn != 0 {\n\t\tnewabs := (abs + algn - 1) & ^(algn - 1)\n\t\treturn newabs - abs\n\t}\n\treturn 0\n}", "func padding(message []byte, identifier string) []byte {\n\t// create padding for the strings email, firstname, lastname - RFC6234 multiple of 512\n\n\t// calculate length\n\tmessageSize := binary.Size(message) * 8\n\tlog.Printf(\"%s size: %dBit\\n\", identifier, messageSize)\n\t// ( L + 1 + K ) mod 512 = 448 -> calculate k\n\tmessageL := (messageSize % 512) + 1\n\n\tmessageK := messageL\n\tif messageL > 448 {\n\t\tmessageK = 448 + (512 - messageL)\n\t} else {\n\t\tmessageK = 448 - messageL\n\t}\n\n\t// create buffer to add bytewise\n\tmessageBuffer := bytes.NewBuffer(make([]byte, 0, 512))\n\tbinary.Write(messageBuffer, binary.BigEndian, message)\n\n\t// add 1 - add k - Work with bytes 8bit - add: 1000 0000 | k-7 * 0 - all Strings: string % 8 = 0\n\tbinary.Write(messageBuffer, binary.BigEndian, uint8(0x80))\n\n\t// itearate through the String length K and fill the buffer with 0s\n\tmessageK -= 7\n\n\t// error Handling - if the padding failed\n\tif messageK < 0 || messageK%8 != 0 {\n\t\tlog.Fatalf(\"%s Length of Bits is to long: %d\", identifier, messageK)\n\t}\n\n\t// iteration\n\tfor i := 0; i < messageK/8; i++ {\n\t\tbinary.Write(messageBuffer, binary.BigEndian, uint8(0x00))\n\t}\n\n\t// 64-bit/8Byte block that is L in binary -> L original length\n\tbinary.Write(messageBuffer, binary.BigEndian, uint64(messageSize))\n\n\tlog.Printf(\"Padding for %s: %x(%dBytes|%dBits)\\n\", identifier, messageBuffer.Bytes(), binary.Size(messageBuffer.Bytes()), binary.Size(messageBuffer.Bytes())*8)\n\treturn messageBuffer.Bytes()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Length gets the length of the TLV
func (p *PaddingTLV) Length() uint8 { return p.TLVLength }
[ "func (a *MobileIdentity5GS) GetLen() (len uint16) {}", "func (c OscillatingControl) GetLength() int {\n\treturn len(c.bits)\n}", "func (vn *JSONValueNode) Length() (l int, e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tl = 0\n\t\t\te = fmt.Errorf(\"can not get the length of value other than string, map, array/slice or object\")\n\t\t}\n\t}()\n\n\treturn vn.data.Len(), nil\n}", "func (a *TMSI5GS) GetLen() (len uint16) {}", "func (p Packet) Length() int {\n\tresult := EapPacketHeaderLength + len(p.Data)\n\tif p.Code.IsRequestOrResponse() {\n\t\tresult += EapPacketTypeFieldLength\n\t}\n\treturn result\n}", "func (vp *baseVectorParty) GetLength() int {\n\treturn vp.length\n}", "func (com *hornComponent) Length() int {\n\treturn 222\n}", "func (packet *RadiusPacket) GetLength() uint16 {\n\n\treturn packet.length\n\n}", "func (c *Certificate) Length() (length int) {\n\tlength = c.leng.Int()\n\treturn\n}", "func (sd *PrivateDescriptor) length() int {\n\tlength := 32 // identifier\n\tlength += len(sd.PrivateBytes) * 8 // private_bytes\n\treturn length / 8\n}", "func (a *AvroEncoder) Length() int {\n\treturn 5 + len(a.Content)\n}", "func (p *decoded) Length() int64 {\n\treturn 0\n}", "func (d NSData) Length() uint64 {\n\treturn uint64(d.gen_NSData.Length())\n}", "func (p IPPacket) Length() (int, error) {\n\tswitch p.Version() {\n\tcase 4:\n\t\t{\n\t\t\tif len(p) < 4 {\n\t\t\t\treturn -1, ErrTooShort\n\t\t\t}\n\t\t\treturn int(p[2])<<4 + int(p[3]), nil\n\t\t}\n\tcase 6:\n\t\t{\n\t\t\tif len(p) < 6 {\n\t\t\t\treturn -1, ErrTooShort\n\t\t\t}\n\t\t\treturn int(p[4])<<4 + int(p[5]) + IPv6PacketHeadLen, nil\n\t\t}\n\tdefault:\n\t\t{\n\t\t\treturn -1, ErrIPPacketBadVersion\n\t\t}\n\t}\n\treturn -1, nil\n}", "func (h *Header) GetLength(pers protocol.Perspective, version protocol.VersionNumber) (protocol.ByteCount, error) {\n\tif !version.UsesTLS() {\n\t\treturn h.getPublicHeaderLength(pers)\n\t}\n\treturn h.getHeaderLength()\n}", "func (r *Reader) Length(name string) (int, error) {\n\trec, err := r.parseRecord(name, false)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn int(rec.dnaSize), nil\n}", "func (a *ReplayedS1UESecurityCapabilities) GetLen() (len uint8) {\n\treturn a.Len\n}", "func (e *ExtensionField) Len() uint8 {\n\treturn uint8(len(e.Value))\n}", "func (s *Server) Length(ctx context.Context, key *Key) (*IntValue, error) {\n\tbv, err := s.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IntValue{Value: int64(len(bv.Value))}, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Value gets the TLV itself
func (p *PaddingTLV) Value() interface{} { return p }
[ "func (b *baseSemanticUTF8String) Value() interface{} {\n\treturn b.V\n}", "func (i VkIdentifier) Value() string {\n\treturn string(i)\n}", "func (f EncodedField) Value() string {\n\treturn f[1]\n}", "func (f *TagField) Value() string {\n\treturn f.value\n}", "func (t *Token) Value() string {\n\treturn t.strBuilder.String()\n}", "func (v Uint) Value() interface{} {\n\tif !v.Valid() {\n\t\treturn nil\n\t}\n\treturn v.Uint\n}", "func (d NodeDecoder) Value() (c []byte, done bool, err error) {\n\tt, e := d.Decoder.Token()\n\tif e != nil {\n\t\treturn c, done, e\n\t}\n\n\t// check if token is of type charData\n\tif ev, ok := t.(xml.CharData); ok {\n\t\treturn ev, done, err\n\t}\n\n\tif ev, ok := t.(xml.EndElement); ok {\n\t\tif ev == d.StartEl.End() {\n\t\t\treturn c, true, err\n\t\t}\n\t}\n\n\treturn c, done, fmt.Errorf(\"expected value for %v element, got %T type %v instead\", d.StartEl.Name.Local, t, t)\n}", "func (f *Title) Value() string {\n\ts := decode.UTF16(f.data)\n\treturn trim.Nil(s)\n}", "func (decoder *berDecoder) decodeValue() (snmpBlockType, interface{}, error) {\n\tvalueType, valueLength, err := decoder.decodeHeader()\n\tif err != nil {\n\t\treturn 0, nil, fmt.Errorf(\"Unable to decode value header at pos %d - err: %s\", decoder.pos, err)\n\t}\n\tvar value interface{}\n\tswitch valueType {\n\tcase snmpBlockType_INTEGER:\n\t\tvalue, err = decoder.decodeInteger(valueLength)\n\tcase snmpBlockType_BIT_STRING:\n\t\tvalue, err = decoder.decodeBitString(valueLength)\n\tcase snmpBlockType_OCTET_STRING:\n\t\tvalue, err = decoder.decodeOctetString(valueLength)\n\tcase snmpBlockType_NULL, snmpBlockType_NO_SUCH_OBJECT, snmpBlockType_NO_SUCH_INSTANCE, snmpBlockType_END_OF_MIB_VIEW:\n\t\tvalue = nil\n\tcase snmpBlockType_OBJECT_IDENTIFIER:\n\t\tvalue, err = decoder.decodeObjectIdentifier(valueLength)\n\tcase snmpBlockType_SEQUENCE:\n\t\treturn 0, nil, fmt.Errorf(\"Unexpected value type snmpBlockType_SEQUENCE 0x%x at pos %d\", valueType, decoder.pos)\n\tcase snmpBlockType_IP_ADDRESS:\n\t\tvalue, err = decoder.decodeIPv4Address(valueLength)\n\tcase snmpBlockType_COUNTER_32:\n\t\t// value, err = decoder.decodeCounter32(valueLength)\n\tcase snmpBlockType_GAUGE_32:\n\t\t// value, err = decoder.decodeGauge32(valueLength)\n\tcase snmpBlockType_TIME_TICKS:\n\t\t// value, err = decoder.decodeTimeTicks(valueLength)\n\tcase snmpBlockType_OPAQUE:\n\t\t// value, err = decoder.decodeOpaque(valueLength)\n\tcase snmpBlockType_COUNTER_64:\n\t\t// value, err = decoder.decodeCounter64(valueLength)\n\tcase snmpBlockType_UINT_32:\n\t\t// value, err = decoder.decodeUint32(valueLength)\n\tdefault:\n\t\treturn 0, nil, fmt.Errorf(\"Unknown value type 0x%x\", valueType)\n\t}\n\treturn valueType, value, nil\n}", "func (ite *IfdTagEntry) Value(addressableData []byte, byteOrder binary.ByteOrder) (value interface{}, err error) {\n\tdefer func() {\n\t\tif state := recover(); state != nil {\n\t\t\terr = log.Wrap(state.(error))\n\t\t}\n\t}()\n\n\tvalueContext :=\n\t\tnewValueContextFromTag(\n\t\t\tite,\n\t\t\taddressableData,\n\t\t\tbyteOrder)\n\n\tif ite.TagType == TypeUndefined {\n\t\tvalue, err = valueContext.Undefined()\n\t\tlog.PanicIf(err)\n\t} else {\n\t\ttt := NewTagType(ite.TagType, byteOrder)\n\n\t\tvalue, err = tt.Resolve(valueContext)\n\t\tlog.PanicIf(err)\n\t}\n\n\treturn value, nil\n}", "func (recv *VariantType) Value() *VariantType {\n\tretC := C.g_variant_type_value((*C.GVariantType)(recv.native))\n\tretGo := VariantTypeNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (b *baseSemanticUTF8Base64) Value() interface{} {\n\treturn b.encoded\n}", "func (r *ReflowletVersion) Value() string {\n\treturn string(*r)\n}", "func (this *record) Value() interface{} {\n\tswitch this._Type {\n\tcase sensors.OT_DATATYPE_UDEC_0:\n\t\tif value, err := this.UintValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_UDEC_4, sensors.OT_DATATYPE_UDEC_8, sensors.OT_DATATYPE_UDEC_12, sensors.OT_DATATYPE_UDEC_16, sensors.OT_DATATYPE_UDEC_20, sensors.OT_DATATYPE_UDEC_24:\n\t\tif value, err := this.FloatValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_STRING:\n\t\tif value, err := this.StringValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_DEC_0:\n\t\tif value, err := this.IntValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_DEC_8, sensors.OT_DATATYPE_DEC_16, sensors.OT_DATATYPE_DEC_24:\n\t\tif value, err := this.FloatValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tdefault:\n\t\tif value, err := this.Data(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\t}\n}", "func (h *Header) Value() string {\n\tif h == nil {\n\t\treturn \"\"\n\t}\n\n\treturn h.value\n}", "func (value *Value) Value() interface{} {\n\treturn value.value\n}", "func (b *Block) Value() []byte {\n\treturn b.value\n}", "func (l *listNode) Value() string {\n\treturn \"\"\n}", "func (t *Tag) Value() string {\n\toptions := strings.Join(t.Options, \",\")\n\tif options != \"\" {\n\t\treturn fmt.Sprintf(`%s,%s`, t.Name, options)\n\t}\n\treturn t.Name\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize serializes a padding TLV
func (p *PaddingTLV) Serialize(buf *bytes.Buffer) { buf.WriteByte(p.TLVType) buf.WriteByte(p.TLVLength) buf.Write(p.PaddingData) }
[ "func (enc Encoding) WithPadding(padding rune) *Encoding {}", "func (p *PaddingTLV) Length() uint8 {\n\treturn p.TLVLength\n}", "func (t Time) Padding() int {\n\treturn 0\n}", "func padding(b []byte) []byte {\n\tl := uint16(len(b))\n\treturn append(b, make([]byte, align(l)-l)...)\n}", "func NewPaddingTLV(length uint8) *PaddingTLV {\n\treturn &PaddingTLV{\n\t\tTLVType: PaddingType,\n\t\tTLVLength: length,\n\t\tPaddingData: make([]byte, length),\n\t}\n}", "func (g *GroupedAVP) Padding() int {\n\treturn 0\n}", "func append_padding_bytes(data []byte) []byte {\n\tpadLen := 16 - len(data)%16\n\tvar padding = make([]byte, padLen)\n\n\t// \"i\" bytes of value \"i\" are appended to the message\n\tfor i := 0; i < padLen; i++ {\n\t\tpadding[i] = byte(padLen)\n\t}\n\n\treturn append(data, padding[:]...)\n}", "func EncodingWithPadding(enc base64.Encoding, padding rune) *base64.Encoding", "func getPadding(packetLen int) int {\n\tif packetLen%4 == 0 {\n\t\treturn 0\n\t}\n\treturn 4 - (packetLen % 4)\n}", "func pad(unpadded []byte, desiredLength int) []byte {\n\tif len(unpadded) == desiredLength {\n\t\treturn unpadded\n\t}\n\ttoAppend := desiredLength - len(unpadded)\n\treturn append(unpadded, bytes.Repeat([]byte{byte(0x00)}, toAppend)...)\n}", "func (vb *VarBytes) Serialize(w io.Writer) error {\n\tvar varlen = VarUint{UintType: GetUintTypeByValue(vb.Len), Value: vb.Len}\n\tif err := varlen.Serialize(w); err != nil {\n\t\treturn err\n\t}\n\treturn binary.Write(w, binary.LittleEndian, vb.Bytes)\n}", "func encode(p *Packet, verbose bool, logger *log.Logger) []byte {\n\tb := make([]byte, 1024)\n\tb[0] = uint8(p.Code)\n\tb[1] = p.Identifier\n\t// Skip Len for now 2+3\n\tcopy(b[4:20], p.Auth)\n\twritten := 20\n\n\tbb := b[20:]\n\tfor _, attr := range p.Attrs {\n\t\taLen := len(attr.Bytes()) + 2 // add type+len fields\n\t\tif aLen > 255 || aLen < 2 {\n\t\t\tpanic(\"Value too big for attr\")\n\t\t}\n\t\tbb[0] = uint8(attr.Type())\n\t\tbb[1] = uint8(aLen)\n\t\tcopy(bb[2:], attr.Bytes())\n\n\t\twritten += aLen\n\t\tbb = bb[aLen:]\n\t}\n\n\t// Now set Len\n\tbinary.BigEndian.PutUint16(b[2:4], uint16(written))\n\tif verbose {\n\t\tlogger.Printf(\"packet.send: \" + debug(p))\n\t}\n\treturn b[:written]\n}", "func (enc *encoder) padding(offset, algn int) int {\n\tabs := enc.pos + offset\n\tif abs%algn != 0 {\n\t\tnewabs := (abs + algn - 1) & ^(algn - 1)\n\t\treturn newabs - abs\n\t}\n\treturn 0\n}", "func setupPadding() {\n\n\tpaddingMap[0] = \"10101010101010101010101010101010\"\n\tpaddingMap[1] = \"0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f\"\n\tpaddingMap[2] = \"0e0e0e0e0e0e0e0e0e0e0e0e0e0e\"\n\tpaddingMap[3] = \"0d0d0d0d0d0d0d0d0d0d0d0d0d\"\n\tpaddingMap[4] = \"0c0c0c0c0c0c0c0c0c0c0c0c\"\n\tpaddingMap[5] = \"0b0b0b0b0b0b0b0b0b0b0b\"\n\tpaddingMap[6] = \"0a0a0a0a0a0a0a0a0a0a\"\n\tpaddingMap[7] = \"090909090909090909\"\n\tpaddingMap[8] = \"0808080808080808\"\n\tpaddingMap[9] = \"07070707070707\"\n\tpaddingMap[10] = \"060606060606\"\n\tpaddingMap[11] = \"0505050505\"\n\tpaddingMap[12] = \"04040404\"\n\tpaddingMap[13] = \"030303\"\n\tpaddingMap[14] = \"0202\"\n\tpaddingMap[15] = \"01\"\n}", "func padding(message []byte, identifier string) []byte {\n\t// create padding for the strings email, firstname, lastname - RFC6234 multiple of 512\n\n\t// calculate length\n\tmessageSize := binary.Size(message) * 8\n\tlog.Printf(\"%s size: %dBit\\n\", identifier, messageSize)\n\t// ( L + 1 + K ) mod 512 = 448 -> calculate k\n\tmessageL := (messageSize % 512) + 1\n\n\tmessageK := messageL\n\tif messageL > 448 {\n\t\tmessageK = 448 + (512 - messageL)\n\t} else {\n\t\tmessageK = 448 - messageL\n\t}\n\n\t// create buffer to add bytewise\n\tmessageBuffer := bytes.NewBuffer(make([]byte, 0, 512))\n\tbinary.Write(messageBuffer, binary.BigEndian, message)\n\n\t// add 1 - add k - Work with bytes 8bit - add: 1000 0000 | k-7 * 0 - all Strings: string % 8 = 0\n\tbinary.Write(messageBuffer, binary.BigEndian, uint8(0x80))\n\n\t// itearate through the String length K and fill the buffer with 0s\n\tmessageK -= 7\n\n\t// error Handling - if the padding failed\n\tif messageK < 0 || messageK%8 != 0 {\n\t\tlog.Fatalf(\"%s Length of Bits is to long: %d\", identifier, messageK)\n\t}\n\n\t// iteration\n\tfor i := 0; i < messageK/8; i++ {\n\t\tbinary.Write(messageBuffer, binary.BigEndian, uint8(0x00))\n\t}\n\n\t// 64-bit/8Byte block that is L in binary -> L original length\n\tbinary.Write(messageBuffer, binary.BigEndian, uint64(messageSize))\n\n\tlog.Printf(\"Padding for %s: %x(%dBytes|%dBits)\\n\", identifier, messageBuffer.Bytes(), binary.Size(messageBuffer.Bytes()), binary.Size(messageBuffer.Bytes())*8)\n\treturn messageBuffer.Bytes()\n}", "func (p *PaddingTLV) Value() interface{} {\n\treturn p\n}", "func (t *TLV) MarshalBinary() []byte {\n\treturn nil\n}", "func PaddingData(method string, params ...string) string {\n\tvar res string\n\tif !strings.HasPrefix(method, HexPrefix) {\n\t\tres = HexPrefix + method\n\t}\n\tfor _, item := range params {\n\t\tif strings.HasPrefix(item, HexPrefix) {\n\t\t\titem = item[2:]\n\t\t}\n\t\tpaddingString := paddingstr[:64-len(item)]\n\t\ttmp := string(paddingString) + item\n\t\tres += tmp\n\t}\n\treturn res\n}", "func (pkt *Packet) MarshalTlv() (typ uint32, value []byte, e error) {\n\tpayload, e := pkt.encodeL3()\n\tif e != nil {\n\t\treturn 0, nil, e\n\t}\n\treturn tlv.EncodeTlv(an.TtLpPacket, tlv.MakeElement(an.TtLpFragment, payload))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AFunc1In calls the stored function 'a_bit_of_everything.a_func_1_in(number) number' on db.
func AFunc1In(ctx context.Context, db DB, aParam int64) (int64, error) { // call a_bit_of_everything.a_func_1_in const sqlstr = `SELECT a_bit_of_everything.a_func_1_in(:1) FROM dual` // run var r0 int64 logf(sqlstr, aParam) if err := db.QueryRowContext(ctx, sqlstr, aParam).Scan(&r0); err != nil { return 0, logerror(err) } return r0, nil }
[ "func A1In1Out(ctx context.Context, db DB, aParam int) (int, error) {\n\t// At the moment, the Go MySQL driver does not support stored procedures\n\t// with out parameters\n\treturn 0, fmt.Errorf(\"unsupported\")\n}", "func FuncIn() {\n\tsimlog.FuncIn()\n}", "func (l *logger) FuncIn() {\n\tif !l.isDebug {\n\t\treturn\n\t}\n\tl.printLog(\"[DEBUG]\", \"%s\", \"IN\")\n}", "func ArfcnIn(vs ...int) predicate.SurveyCellScan {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.SurveyCellScan(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldArfcn), v...))\n\t},\n\t)\n}", "func inFunc(signal uint32) *volatile.Register32 {\n\treturn (*volatile.Register32)(unsafe.Add(unsafe.Pointer(&esp.GPIO.FUNC0_IN_SEL_CFG), uintptr(signal)*4))\n}", "func (m *Message) IN1() (*IN1, error) {\n\tps, err := m.Parse(\"IN1\")\n\tpst, ok := ps.(*IN1)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func GetFuncIn(name string, i int) interface{} {\n\treturn DefalutFuncs.GetFuncIn(name, i)\n}", "func (s *BasevhdlListener) EnterFunction_call_or_indexed_name_part(ctx *Function_call_or_indexed_name_partContext) {\n}", "func (f *Funcs) GetFuncIn(name string, i int) interface{} {\n\tindex := i + 1\n\tF := f.GetFunc(name)\n\tif F == nil || index < 1 || index > F.NumIn() {\n\t\treturn nil\n\t}\n\tindex += F.withContext\n\treturn reflect.New(F.methodType.In(index).Elem()).Interface()\n}", "func UarfcnIn(vs ...int) predicate.SurveyCellScan {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.SurveyCellScan(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldUarfcn), v...))\n\t},\n\t)\n}", "func F1(n int) int {\n\treturn 2 * n\n}", "func f1(key, sqn, rand, opc, amf []byte) ([]byte, []byte, error) {\n\t// TEMP = E_K(RAND XOR OP_C)\n\ttemp, err := encrypt(key, xor(rand, opc))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// IN1 = SQN || AMF || SQN || AMF\n\tvar in1 = make([]byte, 0, ExpectedOpcBytes)\n\tin1 = append(in1, sqn...)\n\tin1 = append(in1, amf...)\n\tin1 = append(in1, in1...)\n\n\tconst rotationBytes = 8 // Constant from 3GPP 35.206 4.1\n\n\t// OUT1 = E_K(TEMP XOR rotate(IN1 XOR OP_C, r1) XOR c1) XOR OP_C\n\tout1, err := encrypt(key, xor(temp, rotate(xor(in1, opc), rotationBytes)))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tout1 = xor(out1, opc)\n\n\t// MAC-A = f1 = OUT1[0] .. OUT1[63]\n\t// MAC-S = f1* = OUT1[64] .. OUT1[127]\n\treturn out1[:8], out1[8:], nil\n}", "func Function8x1[I0, I1, I2, I3, I4, I5, I6, I7, R0 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7) R0) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7) R0)\n\t\treturn &caller8x1[I0, I1, I2, I3, I4, I5, I6, I7, R0]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7) R0)(nil)).Elem(), caller)\n}", "func (self *State)Asin(a any)any{\n self.IncOperations(self.coeff[\"asin\"]+self.off[\"asin\"])\n return wrap1(a,math.Asin)\n}", "func (s *BasePlSqlParserListener) EnterFunction_call(ctx *Function_callContext) {}", "func (f *Funcs) GetFuncValueIn(name string, i int) Value {\n\tindex := i + 1\n\tF := f.GetFunc(name)\n\tif F == nil || index < 1 || index > F.NumIn() {\n\t\treturn ZeroValue\n\t}\n\tindex += F.withContext\n\treturn Value(reflect.New(F.methodType.In(index).Elem()))\n}", "func (s *BasePlSqlParserListener) EnterInto_clause1(ctx *Into_clause1Context) {}", "func inlcalls(fn *Node) {\n\tsavefn := Curfn\n\tCurfn = fn\n\tmaxCost := int32(inlineMaxBudget)\n\tif countNodes(fn) >= inlineBigFunctionNodes {\n\t\tmaxCost = inlineBigFunctionMaxCost\n\t}\n\tfn = inlnode(fn, maxCost)\n\tif fn != Curfn {\n\t\tFatalf(\"inlnode replaced curfn\")\n\t}\n\tCurfn = savefn\n}", "func INCB(mr operand.Op) { ctx.INCB(mr) }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
XXH64 returns new hash.Hash64
func XXH64(seed uint64) hash.Hash64 { d := &digest64{seed: seed, buf: new(bytes.Buffer)} d.Reset() return d }
[ "func New64() *XXHash64 {\n\treturn NewS64(0)\n}", "func New64() hash.Hash64 { return New64WithSeed(0) }", "func NewXXHash64(seed uint64) (*XXHash64, error) {\n\tthis := new(XXHash64)\n\tthis.seed = seed\n\treturn this, nil\n}", "func HashXXH3_64(input []byte, seed uint64) (result uint64) {\n\treturn parser.HashXXH3_64(input, seed)\n}", "func hash64(key, mask uint64) uint64 {\n\tkey = (^key + (key << 21)) & mask\n\tkey = key ^ key>>24\n\tkey = ((key + (key << 3)) + (key << 8)) & mask\n\tkey = key ^ key>>14\n\tkey = ((key + (key << 2)) + (key << 4)) & mask\n\tkey = key ^ key>>28\n\tkey = (key + (key << 31)) & mask\n\treturn key\n}", "func New64(key []byte) (hash.Hash64, error) {\n\tif k := len(key); k != KeySize {\n\t\treturn nil, KeySizeError(k)\n\t}\n\th := new(digest64)\n\th.key[0] = binary.LittleEndian.Uint64(key)\n\th.key[1] = binary.LittleEndian.Uint64(key[8:])\n\th.Reset()\n\treturn h, nil\n}", "func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}", "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func NewIEEE() hash.Hash32 {}", "func hash4x64(u uint64, h uint8) uint32 {\n\treturn (uint32(u) * prime4bytes) >> ((32 - h) & 31)\n}", "func HashNew(h crypto.Hash,) hash.Hash", "func (c Coord) fastHash64() uint64 {\n\t// Coefficients are random (keyboard mashed).\n\treturn math.Float64bits(0.78378384728594870293*c.X + 0.12938729312040294193*c.Y)\n}", "func NewS64(seed uint64) *XXHash64 {\n\th := &XXHash64{\n\t\tseed: seed,\n\t}\n\th.Reset()\n\treturn h\n}", "func DoubleHashH(b []byte) HashType {\n\tfirst := sha256.Sum256(b)\n\treturn HashType(sha256.Sum256(first[:]))\n}", "func Hash64(p []byte) uint64 {\n\treturn crc64.Checksum(p, table)\n}", "func hash128to64(x Uint128) uint64 {\n\t// Murmur-inspired hashing.\n\tconst kMul uint64 = 0x9ddfea08eb382d69\n\ta := (x.First ^ x.Second) * kMul\n\ta ^= (a >> 47)\n\tb := (x.Second ^ a) * kMul\n\tb ^= (b >> 47)\n\tb *= kMul\n\treturn b\n}", "func combineHash(left *crypto.HashType, right *crypto.HashType) *crypto.HashType {\n\tvar hash [crypto.HashSize * 2]byte\n\tcopy(hash[:crypto.HashSize], left[:])\n\tcopy(hash[crypto.HashSize:], right[:])\n\n\tnewHash := crypto.DoubleHashH(hash[:])\n\treturn &newHash\n}", "func New64(seed uint32) Hash128 {\n\tseed64 := uint64(seed)\n\treturn &sum64_128{seed64, seed64, 0, 0, 0, 0}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attack implements the brokenrsa method against ciphertext in multiple keys.
func Attack(ks []*keys.RSA, ch chan error) { k := ks[0] if k.CipherText == nil { ch <- fmt.Errorf("invalid arguments for attack %s: this attack requires the ciphertext", name) return } d, u, _ := ln.XGCD(k.Key.PublicKey.E, k.Key.N) if !d.Equals(ln.BigOne) { ch <- fmt.Errorf("n and e were not coprime so %s attack will not work: GCE(e,n) == %v", name, d) return } ct := ln.BytesToNumber(k.CipherText) pt := new(fmp.Fmpz).Mul(ct, u) k.PlainText = ln.NumberToBytes(pt.Mod(pt, k.Key.N)) ch <- nil }
[ "func (evaluator *Evaluator) SwitchKeys(cIn *Ciphertext, switchingKey *SwitchingKey, cOut *Ciphertext) error {\n\n\tif cIn.Degree() != 1 {\n\t\treturn errors.New(\"error : ciphertext must be of degree 1 to allow key switching\")\n\t}\n\n\tif cOut.Degree() != 1 {\n\t\treturn errors.New(\"error : receiver ciphertext must be of degree 1 to allow key switching\")\n\t}\n\n\tswitchKeys(evaluator, cIn.value[0], cIn.value[1], cIn.value[1], switchingKey, cOut)\n\n\treturn nil\n}", "func ImportKeys(from io.Reader, to []Importer, fallbackRole string, fallbackGUN string, passRet notary.PassRetriever) error {\n\t// importLogic.md contains a small flowchart I made to clear up my understand while writing the cases in this function\n\t// it is very rough, but it may help while reading this piece of code\n\tdata, err := ioutil.ReadAll(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar (\n\t\twriteTo string\n\t\ttoWrite []byte\n\t\terrBlocks []string\n\t)\n\tfor block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {\n\t\thandleLegacyPath(block)\n\t\tsetFallbacks(block, fallbackGUN, fallbackRole)\n\n\t\tloc, err := checkValidity(block)\n\t\tif err != nil {\n\t\t\t// already logged in checkValidity\n\t\t\terrBlocks = append(errBlocks, err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\t// the path header is not of any use once we've imported the key so strip it away\n\t\tdelete(block.Headers, \"path\")\n\n\t\t// we are now all set for import but let's first encrypt the key\n\t\tblockBytes := pem.EncodeToMemory(block)\n\t\t// check if key is encrypted, note: if it is encrypted at this point, it will have had a path header\n\t\tif privKey, err := utils.ParsePEMPrivateKey(blockBytes, \"\"); err == nil {\n\t\t\t// Key is not encrypted- ask for a passphrase and encrypt this key\n\t\t\tvar chosenPassphrase string\n\t\t\tfor attempts := 0; ; attempts++ {\n\t\t\t\tvar giveup bool\n\t\t\t\tchosenPassphrase, giveup, err = passRet(loc, block.Headers[\"role\"], true, attempts)\n\t\t\t\tif err == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif giveup || attempts > 10 {\n\t\t\t\t\treturn errors.New(\"maximum number of passphrase attempts exceeded\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tblockBytes, err = utils.ConvertPrivateKeyToPKCS8(privKey, tufdata.RoleName(block.Headers[\"role\"]), tufdata.GUN(block.Headers[\"gun\"]), chosenPassphrase)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(\"failed to encrypt key with given passphrase\")\n\t\t\t}\n\t\t}\n\n\t\tif loc != writeTo {\n\t\t\t// next location is different from previous one. We've finished aggregating\n\t\t\t// data for the previous file. If we have data, write the previous file,\n\t\t\t// clear toWrite and set writeTo to the next path we're going to write\n\t\t\tif toWrite != nil {\n\t\t\t\tif err = importToStores(to, writeTo, toWrite); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// set up for aggregating next file's data\n\t\t\ttoWrite = nil\n\t\t\twriteTo = loc\n\t\t}\n\n\t\ttoWrite = append(toWrite, blockBytes...)\n\t}\n\tif toWrite != nil { // close out final iteration if there's data left\n\t\treturn importToStores(to, writeTo, toWrite)\n\t}\n\tif len(errBlocks) > 0 {\n\t\treturn fmt.Errorf(\"failed to import all keys: %s\", strings.Join(errBlocks, \", \"))\n\t}\n\treturn nil\n}", "func paddingOracleAttack() []byte {\n\tkey = randBytes(16)\n\tciphertext, iv := encryptLine(\"\")\n\tplaintext := make([]byte, len(ciphertext))\n\t// C_1, C_1'\n\tprevblock := iv\n\tprevblockMut := make([]byte, len(prevblock))\n\tcopy(prevblockMut, prevblock)\n\t//block iteration\n\tfor bs, be := 0, 16; bs < len(ciphertext); bs, be = bs+16, be+16 {\n\t\tvar decryptedBlock [16]byte\n\t\tcipherblock := ciphertext[bs:be]\n\t\t//character iteration\n\t\tfor blockIdx := 15; blockIdx >= 0; blockIdx-- {\n\t\t\tXORtarget := 16 - blockIdx\n\t\t\tvar hackedVal byte\n\t\t\t/*filling out prevblock with appropriate values to lay ground for padding validation\n\t\t\ti.e. suppose XORtarget is \\x02, then we're changing C_1'[14],[15] with values s.t. P_2'[14],\n\t\t\t[15] = \\x02. Such values determined by XORing against previous char decryptions.\n\t\t\t*/\n\t\t\tfor j := XORtarget - 1; j >= 1; j-- {\n\t\t\t\tprevblockMut[16-j] = decryptedBlock[16-j] ^ byte(XORtarget)\n\t\t\t}\n\t\t\tfor ascii := 0; ascii < 256; ascii++ {\n\t\t\t\tprevblockMut[blockIdx] = byte(ascii)\n\t\t\t\tif checkLine(cipherblock, prevblockMut) == true {\n\t\t\t\t\t//hackedVal = D(C_2)[n]\n\t\t\t\t\thackedVal = byte(ascii) ^ byte(XORtarget)\n\t\t\t\t\t//mad hackz... explainer above\n\t\t\t\t\tif bs+16 == len(ciphertext) {\n\t\t\t\t\t\tif blockIdx == 15 && prevblockMut[blockIdx] == prevblock[blockIdx] {\n\t\t\t\t\t\t\tprevblockMut[14] = prevblockMut[14] + 1\n\t\t\t\t\t\t\t//padding doesn't organically terminate with 1\n\t\t\t\t\t\t\tif checkLine(cipherblock, prevblockMut) == false {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tdecryptedBlock[blockIdx] = hackedVal\n\t\t\tplaintext[bs+blockIdx] = hackedVal ^ prevblock[blockIdx]\n\t\t}\n\t\tprevblock = cipherblock\n\t\tcopy(prevblockMut, cipherblock)\n\t}\n\tfmt.Println(plaintext)\n\tplaintext = removePKCS7Pad(plaintext)\n\treturn plaintext\n}", "func BreakRepeatingKeyXOR(cipher []byte) (mostProbableKey []byte, plaintext []byte) {\n\t// You have to play with the max keysize, it might be bigger than you thought\n\tmaxKeysize := 200\n\tkeyAnalysis := make(map[int]float32, maxKeysize-2)\n\tkeySizes := make([]int, maxKeysize-2)\n\tfor keysize := 2; keysize < maxKeysize; keysize++ {\n\t\tdist, _ := HammingDistance(cipher[:keysize], cipher[keysize:keysize*2])\n\t\tkeyAnalysis[keysize] = float32(dist) / float32(keysize)\n\t\tkeySizes[keysize-2] = keysize\n\t}\n\n\t// Sort key sizes according to normalized hamming distance in ascending order (insertion sort)\n\tfor i := 0; i < (maxKeysize - 2); i++ {\n\t\tj := i\n\t\tfor j > 0 && keyAnalysis[keySizes[j-1]] > keyAnalysis[keySizes[j]] {\n\t\t\tkeySizes[j-1], keySizes[j] = keySizes[j], keySizes[j-1]\n\t\t\tj--\n\t\t}\n\t}\n\n\t// Keep only the 5 most probable key sizes (i.e. with the smallest normalized hamming distance)\n\t// You might need to play with this parameter as well\n\tprobableKeySizes := keySizes[:5]\n\n\t// Cut the ciphertext to solve as many 'single-byte XOR' encryption\n\t// as there are bytes in the key\n\tvar bestNormalizedScore float64 = 0\n\tfor _, probableKeySize := range probableKeySizes {\n\t\tcipherBlocks := SplitBytesByMod(cipher, probableKeySize)\n\t\t// Solve each block as if it was a single-character XOR\n\t\tlocalScore := 0\n\t\tprobableKey := make([]byte, probableKeySize)\n\t\tfor i := 0; i < probableKeySize; i++ {\n\t\t\tscore, repeatingKey, _ := SingleByteXorCrackFromByte(cipherBlocks[i])\n\t\t\tprobableKey[i] = repeatingKey\n\t\t\tlocalScore += score\n\t\t}\n\t\tnormalizedScore := float64(localScore) / float64(probableKeySize)\n\t\tif normalizedScore > bestNormalizedScore {\n\t\t\tmostProbableKey = probableKey\n\t\t}\n\t}\n\n\t// Decrypt the cipher with the most probable key\n\tplaintext = RepeatingXOR(mostProbableKey, cipher)\n\n\treturn mostProbableKey, plaintext\n}", "func validateAndDecryptKeys(rawPubKeys, rawPrivKeys [][]byte, p *Pool) (pubKeys, privKeys []*hdkeychain.ExtendedKey, err error) {\n\tpubKeys = make([]*hdkeychain.ExtendedKey, len(rawPubKeys))\n\tprivKeys = make([]*hdkeychain.ExtendedKey, len(rawPrivKeys))\n\tif len(pubKeys) != len(privKeys) {\n\t\treturn nil, nil, newError(ErrKeysPrivatePublicMismatch,\n\t\t\t\"the pub key and priv key arrays should have the same number of elements\",\n\t\t\tnil)\n\t}\n\n\tfor i, encryptedPub := range rawPubKeys {\n\t\tpubKey, err := p.decryptExtendedKey(waddrmgr.CKTPublic, encryptedPub)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tpubKeys[i] = pubKey\n\n\t\tencryptedPriv := rawPrivKeys[i]\n\t\tvar privKey *hdkeychain.ExtendedKey\n\t\tif encryptedPriv == nil {\n\t\t\tprivKey = nil\n\t\t} else {\n\t\t\tprivKey, err = p.decryptExtendedKey(waddrmgr.CKTPrivate, encryptedPriv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t\tprivKeys[i] = privKey\n\n\t\tif privKey != nil {\n\t\t\tcheckPubKey, err := privKey.Neuter()\n\t\t\tif err != nil {\n\t\t\t\tstr := fmt.Sprintf(\"cannot neuter key %v\", privKey)\n\t\t\t\treturn nil, nil, newError(ErrKeyNeuter, str, err)\n\t\t\t}\n\t\t\tif pubKey.String() != checkPubKey.String() {\n\t\t\t\tstr := fmt.Sprintf(\"public key %v different than expected %v\",\n\t\t\t\t\tpubKey, checkPubKey)\n\t\t\t\treturn nil, nil, newError(ErrKeyMismatch, str, nil)\n\t\t\t}\n\t\t}\n\t}\n\treturn pubKeys, privKeys, nil\n}", "func BruteAttack(charset, cipher string) (guesses []string, err error) {\n\tcsLen := len(charset)\n\tfor i := 0; i < csLen; i++ {\n\t\tnewCipher, err := broken.Caesar(charset, cipher, i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tguesses = append(guesses, newCipher)\n\t}\n\n\treturn guesses, nil\n}", "func verifyXorKeys(r *bufio.Reader, key1, key2 []byte) (bool, error) {\n\td, err := r.Peek(3)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// decrypt the first 3 bytes\n\txorBuff(3, 0, d, key1, key2)\n\tvalid := false\n\tif d[0] == 0 && d[1] == 0 && d[2] == 0 {\n\t\tvalid = true\n\t}\n\t// reverse the previous decryption\n\txorBuff(3, 0, d, key1, key2)\n\treturn valid, nil\n}", "func (c *seedCipher) subkeys(key []byte) {\n\n\tkey0 := binary.BigEndian.Uint32(key)\n\tkey1 := binary.BigEndian.Uint32(key[4:])\n\tkey2 := binary.BigEndian.Uint32(key[8:])\n\tkey3 := binary.BigEndian.Uint32(key[12:])\n\n\tfor i := 0; i < 16; i++ {\n\t\tc.k0[i] = g(key0 + key2 - kc[i])\n\t\tc.k1[i] = g(key1 - key3 + kc[i])\n\t\tif i&1 == 0 {\n\t\t\tkey0, key1 = rotrbyte32(key0, key1)\n\t\t} else {\n\t\t\tkey2, key3 = rotlbyte32(key2, key3)\n\t\t}\n\t}\n}", "func TestAuthenticationKeyRequest(t *testing.T) {\n\ttestKeys := MakeTestKeys(3)\n\n\t// Give sish a temp directory to generate a server ssh host key\n\tdir, err := os.MkdirTemp(\"\", \"sish_keys\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tviper.Set(\"private-keys-directory\", dir)\n\tviper.Set(\"authentication\", true)\n\n\ttestCases := []struct {\n\t\tclientPrivateKey *rsa.PrivateKey\n\t\tclientUser string\n\t\tvalidPublicKeys []rsa.PublicKey\n\t\tvalidUsernames []string\n\t\texpectSuccessAuth bool\n\t\toverrideHttpUrl string\n\t}{\n\t\t// valid key, should succeed auth\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: true,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// invalid key, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[1].PublicKey, testKeys[2].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// invalid username, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"windows\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// no http service listening on server url, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"http://localhost:61234\",\n\t\t},\n\t\t// invalid http url, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"notarealurl\",\n\t\t},\n\t}\n\n\tfor caseIdx, c := range testCases {\n\t\tif c.overrideHttpUrl == \"\" {\n\t\t\t// start an http server that will validate against the specified public keys\n\t\t\thttpSrv := httptest.NewServer(http.HandlerFunc(PubKeyHttpHandler(&c.validPublicKeys, &c.validUsernames)))\n\t\t\tdefer httpSrv.Close()\n\n\t\t\t// set viper to this http server URL as the auth request url it will\n\t\t\t// send public keys to for auth validation\n\t\t\tviper.Set(\"authentication-key-request-url\", httpSrv.URL)\n\t\t} else {\n\t\t\tviper.Set(\"authentication-key-request-url\", c.overrideHttpUrl)\n\t\t}\n\n\t\tsshListener, err := net.Listen(\"tcp\", \"localhost:0\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tdefer sshListener.Close()\n\n\t\tsuccessAuth := make(chan bool)\n\t\tgo HandleSSHConn(sshListener, &successAuth)\n\n\t\t// attempt to connect to the ssh server using the specified private key\n\t\tsigner, err := ssh.NewSignerFromKey(c.clientPrivateKey)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tclientConfig := &ssh.ClientConfig{\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.PublicKeys(signer),\n\t\t\t},\n\t\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\t\tUser: c.clientUser,\n\t\t}\n\t\tt.Log(clientConfig)\n\n\t\tclient, err := ssh.Dial(\"tcp\", sshListener.Addr().String(), clientConfig)\n\t\tif err != nil {\n\t\t\tt.Log(\"ssh client rejected\", err)\n\t\t} else {\n\t\t\tt.Log(\"ssh client connected\")\n\t\t\tclient.Close()\n\t\t}\n\n\t\tdidAuth := <-successAuth\n\n\t\tif didAuth != c.expectSuccessAuth {\n\t\t\tt.Errorf(\"Auth %t when should have been %t for case %d\", didAuth, c.expectSuccessAuth, caseIdx)\n\t\t}\n\t}\n}", "func RunChallenge10() {\n\tutil.PrintChallengeHeader(2, 10)\n\n\t// The same key is used throughout this challenge\n\tkey := []byte(\"YELLOW SUBMARINE\")\n\n\t// Test ECB Encryption\n\tecbPlainText := \"This test really contains at exactly (3) blocks.\"\n\n\tecbCipher := aes.NewAesEcbCipher(key)\n\tecbCipherText, err := ecbCipher.Encrypt([]byte(ecbPlainText))\n\tif err != nil {\n\t\tfmt.Println(\"error encrypting with ecb:\", err.Error())\n\t\treturn\n\t}\n\tpaddedPlaintext, err := ecbCipher.Decrypt(ecbCipherText)\n\tif err != nil {\n\t\tfmt.Println(\"error decrypting with ecb:\", err.Error())\n\t\treturn\n\t}\n\tfinalEcb, err := util.RemovePkcs7Padding(paddedPlaintext, 16)\n\tif err != nil {\n\t\tfmt.Println(\"error removing padding from ecb:\", err.Error())\n\t\treturn\n\t}\n\tutil.PrintResults(ecbPlainText, string(finalEcb))\n\n\t// Test CBC Encryption\n\tcbcPlainText := \"This is not a block aligned\"\n\tcbcIv := \"DEFINITELYSECRET\"\n\n\tcbcCipher := aes.NewAesCbcCipher(key)\n\tcbcCipherText, err := cbcCipher.Encrypt([]byte(cbcPlainText), []byte(cbcIv))\n\tif err != nil {\n\t\tfmt.Println(\"error encrypting with cbc:\", err.Error())\n\t\treturn\n\t}\n\tfinalCbc, err := cbcCipher.Decrypt(cbcCipherText, []byte(cbcIv))\n\tif err != nil {\n\t\tfmt.Println(\"error decrypting with cbc:\", err.Error())\n\t\treturn\n\t}\n\tutil.PrintResults(cbcPlainText, string(finalCbc))\n\n\t// Load Data\n\tinput, err := util.ReadFileRemoveNewline(\"set2/resources/challenge10.txt\")\n\tif err != nil {\n\t\tfmt.Println(\"error reading filedata\", err.Error())\n\t\treturn\n\t}\n\tdata, _ := base64.StdEncoding.DecodeString(input)\n\tiv := make([]byte, 16)\n\n\t// Decrypt\n\tcbcCipher = aes.NewAesCbcCipher(key)\n\tplaintext, err := cbcCipher.Decrypt(data, iv)\n\tfmt.Println(string(plaintext))\n}", "func AESKEYGENASSIST(i, mx, x operand.Op) { ctx.AESKEYGENASSIST(i, mx, x) }", "func encrypt(sk, dst, src []byte) {\n\n}", "func replacementAttack(domain string) []string {\n\tresults := []string{}\n\tkeyboards := make([]map[rune]string, 0)\n\tcount := make(map[string]int)\n\tkeyboardEn := map[rune]string{'q': \"12wa\", '2': \"3wq1\", '3': \"4ew2\", '4': \"5re3\", '5': \"6tr4\", '6': \"7yt5\", '7': \"8uy6\", '8': \"9iu7\", '9': \"0oi8\", '0': \"po9\",\n\t\t'w': \"3esaq2\", 'e': \"4rdsw3\", 'r': \"5tfde4\", 't': \"6ygfr5\", 'y': \"7uhgt6\", 'u': \"8ijhy7\", 'i': \"9okju8\", 'o': \"0plki9\", 'p': \"lo0\",\n\t\t'a': \"qwsz\", 's': \"edxzaw\", 'd': \"rfcxse\", 'f': \"tgvcdr\", 'g': \"yhbvft\", 'h': \"ujnbgy\", 'j': \"ikmnhu\", 'k': \"olmji\", 'l': \"kop\",\n\t\t'z': \"asx\", 'x': \"zsdc\", 'c': \"xdfv\", 'v': \"cfgb\", 'b': \"vghn\", 'n': \"bhjm\", 'm': \"njk\"}\n\tkeyboardDe := map[rune]string{'q': \"12wa\", 'w': \"23esaq\", 'e': \"34rdsw\", 'r': \"45tfde\", 't': \"56zgfr\", 'z': \"67uhgt\", 'u': \"78ijhz\", 'i': \"89okju\",\n\t\t'o': \"90plki\", 'p': \"0ßüölo\", 'ü': \"ß+äöp\", 'a': \"qwsy\", 's': \"wedxya\", 'd': \"erfcxs\", 'f': \"rtgvcd\", 'g': \"tzhbvf\", 'h': \"zujnbg\", 'j': \"uikmnh\",\n\t\t'k': \"iolmj\", 'l': \"opök\", 'ö': \"püäl-\", 'ä': \"ü-ö\", 'y': \"asx\", 'x': \"sdcy\", 'c': \"dfvx\", 'v': \"fgbc\", 'b': \"ghnv\", 'n': \"hjmb\", 'm': \"jkn\",\n\t\t'1': \"2q\", '2': \"13wq\", '3': \"24ew\", '4': \"35re\", '5': \"46tr\", '6': \"57zt\", '7': \"68uz\", '8': \"79iu\", '9': \"80oi\", '0': \"9ßpo\", 'ß': \"0üp\"}\n\tkeyboardEs := map[rune]string{'q': \"12wa\", 'w': \"23esaq\", 'e': \"34rdsw\", 'r': \"45tfde\", 't': \"56ygfr\", 'y': \"67uhgt\", 'u': \"78ijhy\", 'i': \"89okju\",\n\t\t'o': \"90plki\", 'p': \"0loñ\", 'a': \"qwsz\", 's': \"wedxza\", 'd': \"erfcxs\", 'f': \"rtgvcd\", 'g': \"tyhbvf\", 'h': \"yujnbg\", 'j': \"uikmnh\", 'k': \"iolmj\",\n\t\t'l': \"opkñ\", 'ñ': \"pl\", 'z': \"asx\", 'x': \"sdcz\", 'c': \"dfvx\", 'v': \"fgbc\", 'b': \"ghnv\", 'n': \"hjmb\", 'm': \"jkn\", '1': \"2q\", '2': \"13wq\",\n\t\t'3': \"24ew\", '4': \"35re\", '5': \"46tr\", '6': \"57yt\", '7': \"68uy\", '8': \"79iu\", '9': \"80oi\", '0': \"9po\"}\n\tkeyboardFr := map[rune]string{'a': \"12zqé\", 'z': \"23eésaq\", 'e': \"34rdsz\", 'r': \"45tfde\", 't': \"56ygfr-\", 'y': \"67uhgtè-\", 'u': \"78ijhyè\",\n\t\t'i': \"89okjuç\", 'o': \"90plkiçà\", 'p': \"0àlo\", 'q': \"azsw\", 's': \"zedxwq\", 'd': \"erfcxs\", 'f': \"rtgvcd\", 'g': \"tzhbvf\", 'h': \"zujnbg\",\n\t\t'j': \"uikmnh\", 'k': \"iolmj\", 'l': \"opmk\", 'm': \"pùl\", 'w': \"qsx\", 'x': \"sdcw\", 'c': \"dfvx\", 'v': \"fgbc\", 'b': \"ghnv\", 'n': \"hjb\",\n\t\t'1': \"2aé\", '2': \"13azé\", '3': \"24ewé\", '4': \"35re\", '5': \"46tr\", '6': \"57ytè\", '7': \"68uyè\", '8': \"79iuèç\", '9': \"80oiçà\", '0': \"9àçpo\"}\n\tkeyboards = append(keyboards, keyboardEn, keyboardDe, keyboardEs, keyboardFr)\n\tfor i, c := range domain {\n\t\tfor _, keyboard := range keyboards {\n\t\t\tfor _, char := range []rune(keyboard[c]) {\n\t\t\t\tresult := fmt.Sprintf(\"%s%c%s\", domain[:i], char, domain[i+1:])\n\t\t\t\t// remove duplicates\n\t\t\t\tcount[result]++\n\t\t\t\tif count[result] < 2 {\n\t\t\t\t\tresults = append(results, result)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func SubgroupConfinementAttack(bob *C57Bob, p, g, q *big.Int) (*big.Int, error) {\n\tvar pairs []crt.Pair // Remainder/divisor pairs for the CRT step.\n\n\tvar j big.Int // j = (p - 1) // q\n\tj.Sub(p, big1)\n\tj.Div(&j, q)\n\n\tfor _, r := range PrimeFactorsLessThan(&j, big65536) {\n\t\tvar h big.Int // Holds an invalid public key.\n\n\t\t// Find an invalid public key that's an element of order r.\n\t\tfor {\n\t\t\trnd, err := RandInt(big1, p) // rnd in [1, p)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\th.Exp(rnd, h.Div(h.Sub(p, big1), r), p) // h = rnd^((p-1)/r) mod p\n\n\t\t\t// Try until h != 1.\n\t\t\tif h.Cmp(big1) != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Query Bob.\n\t\tmsg, tag, err := bob.Respond(&h)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Brute-force Bob's secret key mod f.\n\t\tfor a := big.NewInt(0); a.Cmp(r) < 0; a.Add(a, big1) {\n\t\t\t// Reuse j to save memory.\n\t\t\tj.Exp(&h, a, p) // j = h^a mod p\n\n\t\t\tguess, err := HMACSHA256(j.Bytes(), msg)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// No need for hmac.Equal since we're the attacker.\n\t\t\tif bytes.Equal(guess, tag) {\n\t\t\t\tpairs = append(pairs, crt.Pair{\n\t\t\t\t\tRemainder: new(big.Int).Set(a),\n\t\t\t\t\tDivisor: new(big.Int).Set(r),\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn crt.Do(pairs)\n}", "func CheckKey(A, B *SimSsl) bool {\n\tif A.ClientID != B.ClientID {\n\t\treturn false\n\t}\n\tif A.ExpirationTime != B.ExpirationTime {\n\t\treturn false\n\t}\n\ttemp, err := AesDecrypt(A.RandomInit[:], A.EncryptKey[:])\n\tif err != nil {\n\t\treturn false\n\t}\n\tvar originInital [32]byte\n\tcopy(originInital[:], temp[:32])\n\tif originInital != B.RandomInit {\n\t\treturn false\n\t}\n\treturn true\n}", "func (kw *pkcs7KeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte) ([]byte, error) {\n\tx509Certs, err := collectX509s(ec.Parameters[\"x509s\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// no recipients is not an error...\n\tif len(x509Certs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tpkcs7.ContentEncryptionAlgorithm = pkcs7.EncryptionAlgorithmAES128GCM\n\treturn pkcs7.Encrypt(optsData, x509Certs)\n}", "func Cipher(msg string, key string) string {\n\tvar ciphered string \n\tvar keylen int = len(key)\n\tif (keylen == 0) { return msg } // No key provided\n\tfor i := 0; i < len(msg); i++ {\n\t\tvar keyIndex int = i % keylen // Calculate the key index e.g. (i=10, keylen=4, keyIndex 2), (i=11, keylen=4, keyIndex=3)\n\t\tciphered += string(msg[i] ^ key[keyIndex])\n\t}\n\treturn ciphered\n}", "func genKeyAndSendCipher(kx *KX, pk *[sntrup4591761.PublicKeySize]byte, ek *[32]byte) (*[32]byte, error) {\n\tc, k, err := sntrup4591761.Encapsulate(rand.Reader, pk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ek != nil {\n\t\terr = kx.writeWithKey(c[:], ek)\n\t} else {\n\t\t_, err = xdr.Marshal(kx.Conn, c)\n\t}\n\treturn k, err\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewConfig returns an empty ServerConfigBuilder.
func NewConfig() ServerConfigBuilder { return &serverConfig{} }
[ "func newConfigServer() *ConfigServer {\n\treturn &ConfigServer{}\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func newSrvConfig(objAPI ObjectLayer) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfig()\n\n\t// hold the mutex lock before a new config is assigned.\n\tglobalServerConfigMu.Lock()\n\tglobalServerConfig = srvCfg\n\tglobalServerConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn saveServerConfig(GlobalContext, objAPI, globalServerConfig)\n}", "func NewServerConfig(hbInfo *HeartbeatInfo, opc, dpc, aspID, tmt, nwApr, corrID uint32, rtCtxs []uint32, si, ni, mp, sls uint8) *Config {\n\treturn &Config{\n\t\tHeartbeatInfo: hbInfo,\n\t\tAspIdentifier: params.NewAspIdentifier(aspID),\n\t\tTrafficModeType: params.NewTrafficModeType(tmt),\n\t\tNetworkAppearance: params.NewNetworkAppearance(nwApr),\n\t\tRoutingContexts: params.NewRoutingContext(rtCtxs...),\n\t\tCorrelationID: params.NewCorrelationID(corrID),\n\t\tOriginatingPointCode: opc,\n\t\tDestinationPointCode: dpc,\n\t\tServiceIndicator: si,\n\t\tNetworkIndicator: ni,\n\t\tMessagePriority: mp,\n\t\tSignalingLinkSelection: sls,\n\t}\n}", "func NewConfig() *MainConfig {\n\treturn &MainConfig{\n\t\tBindAddr: \":8000\",\n\t}\n}", "func NewServerConfig() ServerConfig {\n\treturn ServerConfig{Locked: false}\n}", "func (c completedConfig) New() (*GardenerServer, error) {\n\tgenericServer, err := c.GenericConfig.New(\"gardener-apiserver\", genericapiserver.NewEmptyDelegate())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\ts = &GardenerServer{GenericAPIServer: genericServer}\n\n\t\tcoreAPIGroupInfo = (corerest.StorageProvider{}).NewRESTStorage(c.GenericConfig.RESTOptionsGetter)\n\t\tsettingsAPIGroupInfo = (settingsrest.StorageProvider{}).NewRESTStorage(c.GenericConfig.RESTOptionsGetter)\n\t)\n\n\tif err := s.GenericAPIServer.InstallAPIGroups(&coreAPIGroupInfo, &settingsAPIGroupInfo); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func (c CompletedConfig) New() (*GenericAPIServer, error) {\n\ts := &GenericAPIServer{\n\t\t//SecureServingInfo: c.SecureServing,\n\t\t//InsecureServingInfo: c.InsecureServing,\n\t\tmode: c.Mode,\n\t\thealthz: c.Healthz,\n\t\t//enableMetrics: c.EnableMetrics,\n\t\t//enableProfiling: c.EnableProfiling,\n\t\tmiddlewares: c.Middlewares,\n\t\tEngine: gin.New(),\n\t}\n\n\tinitGenericAPIServer(s)\n\n\treturn s, nil\n}", "func newServerConfig(fname, id, name, passWord, serverKey string) (err error) {\n\tconfig := Config{\n\t\tid,\n\t\tname,\n\t\t\"server\",\n\t\tpassWord,\n\t\tserverKey,\n\t\tDEFAULT_SERVER_URL,\n\t\tDEFAULT_PROCESS_USER,\n\t\tDEFAULT_PROCESS_LOCK,\n\t\tDEFAULT_PROCESS_LOG,\n\t\tDEFAULT_BASE_DIR,\n\t\tDEFAULT_DATA_DIR,\n\t\tDEFAULT_HTTP_LISTEN,\n\t\tfname,\n\t}\n\n\treturn SaveConfig(config)\n}", "func NewConfig(newServices []services.ServiceConfig, newGroups []services.ServiceGroupConfig) Config {\n\tlog.Printf(\"Creating new config with %d services and %d groups.\\n\", len(newServices), len(newGroups))\n\n\t// Find Env settings common to all services\n\tvar allEnvSlices [][]string\n\tfor _, s := range newServices {\n\t\tallEnvSlices = append(allEnvSlices, s.Env)\n\t}\n\tenv := stringSliceIntersect(allEnvSlices)\n\n\t// Remove common settings from services\n\tvar svcs []services.ServiceConfig\n\tfor _, s := range newServices {\n\t\ts.Env = stringSliceRemoveCommon(env, s.Env)\n\t\tsvcs = append(svcs, s)\n\t}\n\n\tcfg := Config{\n\t\tEnv: env,\n\t\tServices: svcs,\n\t\tGroups: []GroupDef{},\n\t}\n\n\tcfg.AddGroups(newGroups)\n\n\tlog.Printf(\"Config created: %v\", cfg)\n\n\treturn cfg\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tType: TypeNone,\n\t\tJaeger: NewJaegerConfig(),\n\t\tNone: struct{}{},\n\t}\n}", "func ConfigNew() *Config {\n\tc := Config{\n\t\tHosts: map[string]*ConfigHost{},\n\t}\n\treturn &c\n}", "func NewConfig() {\n\t appConfig = &AppConfig{}\n}", "func (client *HTTPClient) NewConfig(config *Config) {\n\tclient.sendRequest(\"POST\", config, nil, &HTTPClientMetrics{NewConfig: true})\n}", "func New() *Config {\n\treturn &Config{}\n}", "func NewConfig() Config {\n\treturn Config{}\n}", "func NewServerConfig(host string, port int) *ServerConfig {\n\treturn &ServerConfig{Port: port, Host: host}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SetRetryWaitTime accepts an int and sets retry wait time in seconds.
func (co *serverConfig) SetRetryWaitTime(t int) ServerConfigBuilder { co.RetryWaitTime = time.Duration(t) * time.Second return co }
[ "func (c *Client) SetMaxRetryWait(retryWait time.Duration) {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\tc.config.modifyLock.Lock()\n\tdefer c.config.modifyLock.Unlock()\n\n\tc.config.MaxRetryWait = retryWait\n}", "func SetRetryInterval(val uint16) {\n\tretryInterval = val\n}", "func SetRetrySeconds(retrySeconds int8) Option {\n\treturn func(s *Scraper) Option {\n\t\tprev := s.retrySeconds\n\t\tif retrySeconds > 0 {\n\t\t\ts.retrySeconds = retrySeconds\n\t\t}\n\t\treturn SetRetrySeconds(prev)\n\t}\n}", "func (jc *JobCreate) SetRetry(i int) *JobCreate {\n\tjc.mutation.SetRetry(i)\n\treturn jc\n}", "func (c *Client) SetMinRetryWait(retryWait time.Duration) {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\tc.config.modifyLock.Lock()\n\tdefer c.config.modifyLock.Unlock()\n\n\tc.config.MinRetryWait = retryWait\n}", "func (a *Animator) SetRetryInterval(retryInterval time.Duration) {\n\ta.RetryInterval = RetryIntervalDefault\n\tif retryInterval > 0 {\n\t\ta.RetryInterval = retryInterval\n\t}\n}", "func (sshConfig *SSHConfig) SetSleepBtwRetries(sleepMS int64) (result *SSHConfig) {\n\tsshConfig.sleepBtwRetries = sleepMS\n\tresult = sshConfig\n\treturn\n}", "func (r *Retry) MaxWaitTime(maxWaitTime time.Duration) dataflow.Retry {\n\tr.maxWaitTime = maxWaitTime\n\treturn r\n}", "func SetServerRetryTime(f func(uint32) time.Time) func() {\n\top := ftime.ServerRetryTime\n\tftime.ServerRetryTime = f\n\treturn func() {\n\t\tftime.ServerRetryTime = op\n\t}\n}", "func SetRetryParameters(maxAttempts int, maxGap int) {\n\tif maxAttempts > 0 {\n\t\tmaxRetryAttempt = maxAttempts\n\t}\n\n\tif maxGap > 0 {\n\t\tmaxRetryGap = maxGap\n\t}\n}", "func SetClientRetryTime(f func() time.Time) func() {\n\top := ftime.ClientRetryTime\n\tftime.ClientRetryTime = f\n\treturn func() {\n\t\tftime.ClientRetryTime = op\n\t}\n}", "func (c *TCPClient) SetRetryInterval(retryInterval time.Duration) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.retryInterval = retryInterval\n}", "func (r *Retry) WaitTime(waitTime time.Duration) dataflow.Retry {\n\tr.waitTime = waitTime\n\treturn r\n}", "func RetryTimes(n uint) Option {\n\treturn func(rc *RetryConfig) {\n\t\trc.retryTimes = n\n\t}\n}", "func SetMaxRetries(val int) {\n\tmaxRetries = val\n}", "func (object *Config) SetDBRetryTimes(times int) *Config {\n\tobject.dbRetryTimes = times\n\treturn object\n}", "func (c *Client) SetMaxRetries(retries uint8, timeBetweenRetries int64) {\n\tc.MaxRetriesOnError = retries\n\tif timeBetweenRetries == 0 {\n\t\tc.TimeBetweenRetries = 1\n\t} else {\n\t\tc.TimeBetweenRetries = timeBetweenRetries\n\t}\n}", "func (c *Client) SetMaxRetries(retries int) {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\tc.config.modifyLock.Lock()\n\tdefer c.config.modifyLock.Unlock()\n\n\tc.config.MaxRetries = retries\n}", "func (m *WindowsWifiEnterpriseEAPConfiguration) SetAuthenticationRetryDelayPeriodInSeconds(value *int32)() {\n err := m.GetBackingStore().Set(\"authenticationRetryDelayPeriodInSeconds\", value)\n if err != nil {\n panic(err)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build method returns a serverConfig struct.
func (co *serverConfig) Build() serverConfig { return serverConfig{ URL: co.URL, Retry: co.Retry, RetryWaitTime: co.RetryWaitTime, } }
[ "func (c *TLSConfig) BuildServerConfig(host string) *tls.Config {\n\tif c == nil {\n\t\t// use default TLS settings, if config is empty.\n\t\treturn &tls.Config{\n\t\t\tServerName: host,\n\t\t\tInsecureSkipVerify: true,\n\t\t\tVerifyConnection: makeVerifyServerConnection(&TLSConfig{\n\t\t\t\tVerification: VerifyFull,\n\t\t\t}),\n\t\t}\n\t}\n\n\tconfig := c.ToConfig()\n\tconfig.ServerName = host\n\tconfig.VerifyConnection = makeVerifyServerConnection(c)\n\treturn config\n}", "func (b *ServerBuilder) Build() (srvr *Server, err error) {\n\t// Check parameters:\n\tif b.token == \"\" {\n\t\terr = fmt.Errorf(\"work directory is mandatory\")\n\t\treturn\n\t}\n\n\t// Check that the working directory exists:\n\twork := b.work\n\tif work == \"\" {\n\t\twork = os.TempDir()\n\t}\n\t_, err = os.Stat(work)\n\tif os.IsNotExist(err) {\n\t\terr = fmt.Errorf(\"working directory '%s' doesn't exist\", work)\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't check if working directory '%s' exists: %v\", work, err)\n\t\treturn\n\t}\n\n\t// Create and populate the object:\n\tsrvr = &Server{\n\t\tlisten: b.listen,\n\t\ttoken: b.token,\n\t\twork: work,\n\t}\n\n\treturn\n}", "func (serv *Server) Config() Config {\n return serv.config\n}", "func NewConfig() ServerConfigBuilder {\n\treturn &serverConfig{}\n}", "func (b *SecurityBuilder) Build() (*tls.Config, error) {\n\treturn b.config.Build()\n}", "func newConfigServer() *ConfigServer {\n\treturn &ConfigServer{}\n}", "func BuildConfig(opt ClientOptions) (*rest.Config, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tmaster := opt.Master\n\tkubeconfig := opt.KubeConfig\n\tcfg, err = clientcmd.BuildConfigFromFlags(master, kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.QPS = opt.QPS\n\tcfg.Burst = opt.Burst\n\n\treturn cfg, nil\n}", "func Config() ServerConfig {\n\treturn defaultServerConfig\n}", "func (o EventsAdapterServerOptions) Config() (*apiserver.Config, error) {\n\t// TODO have a \"real\" external address (have an AdvertiseAddress?)\n\tif err := o.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{net.ParseIP(\"127.0.0.1\")}); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tserverConfig := genericapiserver.NewConfig(apiserver.Codecs)\n\tif err := o.SecureServing.ApplyTo(serverConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := o.Authentication.ApplyTo(serverConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := o.Authorization.ApplyTo(serverConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: we can't currently serve swagger because we don't have a good way to dynamically update it\n\t// serverConfig.SwaggerConfig = genericapiserver.DefaultSwaggerConfig()\n\n\tconfig := &apiserver.Config{\n\t\tGenericConfig: serverConfig,\n\t}\n\treturn config, nil\n}", "func (c *Config) Build() {\n\tc.Interval = viper.GetDuration(configInterval)\n\tc.MaxKeepedImageFiles = viper.GetInt(configMaxKeepedImageFiles)\n\tc.CameraURL = viper.GetString(configCameraURL)\n\tc.ImagePath = viper.GetString(configImagePath)\n\tc.AlertImagePath = viper.GetString(configAlertImagePath)\n\tc.Treshold = viper.GetInt(configTreshold)\n\tc.AlertHandlers = viper.GetStringSlice(configAlertHandlers)\n\tc.HTTPEnabled = viper.GetBool(configHTTPEnabled)\n\tc.HTTPAddr = viper.GetString(configHTTPAddr)\n\tc.MetricsEnabled = viper.GetBool(configMetricsEnabled)\n\tc.MetricsAddr = viper.GetString(configMetricsAddr)\n\n\tif viper.GetBool(configVerbose) {\n\t\tc.LogLevel = log.DebugLevel\n\t} else {\n\t\tc.LogLevel = log.InfoLevel\n\t}\n}", "func (cb *ConfigBuilder) Build() *gojmx.JMXConfig {\n\treturn cb.config\n}", "func (s *Server) Config() ServerConfig {\n\treturn s.cfg\n}", "func (c CompletedConfig) New() (*GenericAPIServer, error) {\n\ts := &GenericAPIServer{\n\t\t//SecureServingInfo: c.SecureServing,\n\t\t//InsecureServingInfo: c.InsecureServing,\n\t\tmode: c.Mode,\n\t\thealthz: c.Healthz,\n\t\t//enableMetrics: c.EnableMetrics,\n\t\t//enableProfiling: c.EnableProfiling,\n\t\tmiddlewares: c.Middlewares,\n\t\tEngine: gin.New(),\n\t}\n\n\tinitGenericAPIServer(s)\n\n\treturn s, nil\n}", "func buildConfig(opts []Option) (*Config, error) {\n\tcfg := &Config{\n\t\tkeyPrefix: DefKeyPrefix,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func serverConfig() (http.ServerConfig, error) {\n\tconfig := http.ServerConfig{}\n\tvar err error\n\tconfig.Port, err = os.GetIntFromEnvVar(\"RECEIVER_PORT\", 8080)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tconfig.TLSEnabled, err = os.GetBoolFromEnvVar(\"TLS_ENABLED\", false)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tif config.TLSEnabled {\n\t\tconfig.TLSCertPath, err = os.GetRequiredEnvVar(\"TLS_CERT_PATH\")\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t\tconfig.TLSKeyPath, err = os.GetRequiredEnvVar(\"TLS_KEY_PATH\")\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t}\n\treturn config, nil\n}", "func (c *Config) Build() weather.Provider {\n\tu := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"aviationweather.gov\",\n\t\tPath: \"/adds/dataserver_current/httpparam\",\n\t}\n\tq := u.Query()\n\tq.Set(\"dataSource\", \"metars\")\n\tq.Set(\"requestType\", \"retrieve\")\n\tq.Set(\"format\", \"xml\")\n\tq.Set(\"stationString\", c.station)\n\tq.Set(\"hoursBeforeNow\", \"3\")\n\tq.Set(\"mostRecent\", \"true\")\n\tu.RawQuery = q.Encode()\n\n\treturn &provider{\n\t\turl: u.String(),\n\t\tstripRemarks: c.stripRemarks,\n\t\tincludeFlightCat: c.includeFlightCat,\n\t}\n}", "func NewServerConfig(hbInfo *HeartbeatInfo, opc, dpc, aspID, tmt, nwApr, corrID uint32, rtCtxs []uint32, si, ni, mp, sls uint8) *Config {\n\treturn &Config{\n\t\tHeartbeatInfo: hbInfo,\n\t\tAspIdentifier: params.NewAspIdentifier(aspID),\n\t\tTrafficModeType: params.NewTrafficModeType(tmt),\n\t\tNetworkAppearance: params.NewNetworkAppearance(nwApr),\n\t\tRoutingContexts: params.NewRoutingContext(rtCtxs...),\n\t\tCorrelationID: params.NewCorrelationID(corrID),\n\t\tOriginatingPointCode: opc,\n\t\tDestinationPointCode: dpc,\n\t\tServiceIndicator: si,\n\t\tNetworkIndicator: ni,\n\t\tMessagePriority: mp,\n\t\tSignalingLinkSelection: sls,\n\t}\n}", "func (kp *KeyPair) AsServerConfig() *tls.Config {\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{kp.AsX509KeyPair()},\n\t\tClientCAs: kp.authority.CertPool(),\n\t}\n}", "func serverConfig() (http.ServerConfig, error) {\n\tconfig := http.ServerConfig{}\n\tvar err error\n\tconfig.Port, err = os.GetIntFromEnvVar(\"PORT\", 8080)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tconfig.TLSEnabled, err = os.GetBoolFromEnvVar(\"TLS_ENABLED\", false)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tif config.TLSEnabled {\n\t\tconfig.TLSCertPath, err = os.GetRequiredEnvVar(\"TLS_CERT_PATH\")\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t\tconfig.TLSKeyPath, err = os.GetRequiredEnvVar(\"TLS_KEY_PATH\")\n\t\tif err != nil {\n\t\t\treturn config, err\n\t\t}\n\t}\n\treturn config, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Get ProtectedEntity for Persistent Volume referenced by this PVC ProtectedEntity. Candidates are, IVD ProtectedEntity(nonGuestCluster) and ParaVirt ProtectedEntity(GuestCluster).
func (this PVCProtectedEntity) getProtectedEntityForPV(ctx context.Context, pv *core_v1.PersistentVolume) (astrolabe.ProtectedEntity, error) { if pv.Spec.CSI != nil { if pv.Spec.CSI.Driver == VSphereCSIProvisioner { if pv.Spec.AccessModes[0] == core_v1.ReadWriteOnce { var pvIDstr string if this.ppetm.isGuest { pvIDstr = pv.Name // use pv name rather than pv volume handle as the ID of paravirt PE, since it is easier to retrieve pv volume handle from pv name } else { pvIDstr = pv.Spec.CSI.VolumeHandle } pvPEType := this.getComponentPEType() pvPEID := astrolabe.NewProtectedEntityIDWithSnapshotID(pvPEType, pvIDstr, this.id.GetSnapshotID()) pvPE, err := this.ppetm.pem.GetProtectedEntity(ctx, pvPEID) if err != nil { return nil, errors.Wrapf(err, "Could not get Protected Entity for PV %s", pvPEID.String()) } return pvPE, nil } else { return nil, errors.Errorf("Unexpected access mode, %v, for Persistent Volume %s", pv.Spec.AccessModes[0], pv.Name) } } } return nil, errors.Errorf("Could not find PE for Persistent Volume %s", pv.Name) }
[ "func (client VolumesClient) Get(ctx context.Context, location string, storageSubSystem string, storagePool string, volume string) (result Volume, err error) {\n\treq, err := client.GetPreparer(ctx, location, storageSubSystem, storagePool, volume)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (d *Data) GetVolume(v dvid.VersionID, vox *Labels, supervoxels bool, scale uint8, roiname dvid.InstanceName) ([]byte, error) {\n\tr, err := imageblk.GetROI(v, roiname, vox)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := d.GetLabels(v, supervoxels, scale, vox, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn vox.Data(), nil\n}", "func (b *DownloadBuilder) ProtectedEntityID(id string) *DownloadBuilder {\n\tb.object.Spec.ProtectedEntityID = id\n\treturn b\n}", "func (x SecureCredentialEntity) GetNerdStorage() NerdStorageEntityScope {\n\treturn x.NerdStorage\n}", "func getBoundPV(client kubernetes.Interface, pvc *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error) {\n\t// Get new copy of the claim\n\tclaim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(context.TODO(), pvc.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the bound PV\n\tpv, err := client.CoreV1().PersistentVolumes().Get(context.TODO(), claim.Spec.VolumeName, metav1.GetOptions{})\n\treturn pv, err\n}", "func (a *Client) GetProtectedEntityInfo(params *GetProtectedEntityInfoParams, opts ...ClientOption) (*GetProtectedEntityInfoOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetProtectedEntityInfoParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getProtectedEntityInfo\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/astrolabe/{service}/{protectedEntityID}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetProtectedEntityInfoReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetProtectedEntityInfoOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getProtectedEntityInfo: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *doCloudImplementation) VolumeService() godo.StorageService {\n\treturn c.Client.Storage\n}", "func (s *Server) Volume(id string) *Volume {\n\tif vol, ok := s.volumes[id]; ok {\n\t\treturn vol\n\t}\n\n\treturn nil\n}", "func (vs VoteStorage) GetVoter(ctx sdk.Context, accKey types.AccountKey) (*Voter, sdk.Error) {\n\tstore := ctx.KVStore(vs.key)\n\tvoterByte := store.Get(GetVoterKey(accKey))\n\tif voterByte == nil {\n\t\treturn nil, ErrVoterNotFound()\n\t}\n\tvoter := new(Voter)\n\tif err := vs.cdc.UnmarshalBinaryLengthPrefixed(voterByte, voter); err != nil {\n\t\treturn nil, ErrFailedToUnmarshalVoter(err)\n\t}\n\treturn voter, nil\n}", "func (srv *VolumeService) Get(ref string) (*api.Volume, error) {\n\tvolumes, err := srv.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, volume := range volumes {\n\t\tif volume.ID == ref || volume.Name == ref {\n\t\t\treturn &volume, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Volume '%s' does not exists\", ref)\n}", "func (e *Entity) GetEntity() *Entity { return e }", "func (o *SparseCloudSnapshotAccount) GetProtected() (out bool) {\n\n\tif o.Protected == nil {\n\t\treturn\n\t}\n\n\treturn *o.Protected\n}", "func (a *HyperflexApiService) GetHyperflexProtectedClusterByMoid(ctx context.Context, moid string) ApiGetHyperflexProtectedClusterByMoidRequest {\n\treturn ApiGetHyperflexProtectedClusterByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (c *vmClient) Get(uid meta.UID) (*api.VM, error) {\n\tlog.Debugf(\"Client.Get; UID: %q, Kind: %s\", uid, api.KindVM)\n\tobject, err := c.storage.GetByID(api.KindVM, uid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn object.(*api.VM), nil\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetProtectedVm() bool {\n\tif o == nil || o.ProtectedVm == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.ProtectedVm\n}", "func (p *cinderProvisioner) Delete(pv *v1.PersistentVolume) error {\n\tann, ok := pv.Annotations[provisionerIDAnn]\n\tif !ok {\n\t\treturn errors.New(\"identity annotation not found on PV\")\n\t}\n\tif ann != p.identity {\n\t\treturn &controller.IgnoredError{\n\t\t\tReason: \"identity annotation on PV does not match ours\",\n\t\t}\n\t}\n\t// TODO when beta is removed, have to check kube version and pick v1/beta\n\t// accordingly: maybe the controller lib should offer a function for that\n\n\tvolumeID, ok := pv.Annotations[cinderVolumeID]\n\tif !ok {\n\t\treturn errors.New(cinderVolumeID + \" annotation not found on PV\")\n\t}\n\n\tctx := deleteCtx{p, pv}\n\tmapper, err := newVolumeMapperFromPV(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmapper.AuthTeardown(ctx)\n\n\terr = disconnectCinderVolume(p, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = unreserveCinderVolume(p, volumeID)\n\tif err != nil {\n\t\t// TODO: Create placeholder PV?\n\t\tglog.Errorf(\"Failed to unreserve volume: %v\", err)\n\t\treturn err\n\t}\n\n\terr = deleteCinderVolume(p, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.V(2).Infof(\"Successfully deleted cinder volume %s\", volumeID)\n\treturn nil\n}", "func findMatchingVolume(\n\tclaim *v1.PersistentVolumeClaim,\n\tvolumes []*v1.PersistentVolume,\n\tnode *v1.Node,\n\texcludedVolumes map[string]*v1.PersistentVolume,\n\tdelayBinding bool) ([]*v1.PersistentVolume, error) {\n\n\tresult := []*v1.PersistentVolume{}\n\n\trequestedQty := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\trequestedClass := v1helper.GetPersistentVolumeClaimClass(claim)\n\n\tvar selector labels.Selector\n\tif claim.Spec.Selector != nil {\n\t\tinternalSelector, err := metav1.LabelSelectorAsSelector(claim.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// should be unreachable code due to validation\n\t\t\treturn nil, fmt.Errorf(\"error creating internal label selector for claim: %v: %v\", claimToClaimKey(claim), err)\n\t\t}\n\t\tselector = internalSelector\n\t}\n\n\t// Go through all available volumes with two goals:\n\t// - find a volume that is either pre-bound by user or dynamically\n\t// provisioned for this claim. Because of this we need to loop through\n\t// all volumes.\n\t// - find the smallest matching one if there is no volume pre-bound to\n\t// the claim.\n\tfor _, volume := range volumes {\n\t\tif _, ok := excludedVolumes[volume.Name]; ok {\n\t\t\t// Skip volumes in the excluded list\n\t\t\tcontinue\n\t\t}\n\n\t\tvolumeQty := volume.Spec.Capacity[v1.ResourceStorage]\n\n\t\t// check if volumeModes do not match (Alpha and feature gate protected)\n\t\tisMisMatch, err := checkVolumeModeMisMatches(&claim.Spec, &volume.Spec)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error checking if volumeMode was a mismatch: %v\", err)\n\t\t}\n\t\t// filter out mismatching volumeModes\n\t\tif isMisMatch {\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if PV's DeletionTimeStamp is set, if so, skip this volume.\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.StorageObjectInUseProtection) {\n\t\t\tif volume.ObjectMeta.DeletionTimestamp != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tnodeAffinityValid := true\n\t\tif node != nil {\n\t\t\t// Scheduler path, check that the PV NodeAffinity\n\t\t\t// is satisfied by the node\n\t\t\terr := volumeutil.CheckNodeAffinity(volume, node.Labels)\n\t\t\tif err != nil {\n\t\t\t\tnodeAffinityValid = false\n\t\t\t}\n\t\t}\n\n\t\tif isVolumeBoundToClaim(volume, claim) {\n\t\t\t// this claim and volume are pre-bound; return\n\t\t\t// the volume if the size request is satisfied,\n\t\t\t// otherwise continue searching for a match\n\t\t\tif volumeQty.Cmp(requestedQty) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If PV node affinity is invalid, return no match.\n\t\t\t// This means the prebound PV (and therefore PVC)\n\t\t\t// is not suitable for this node.\n\t\t\tif !nodeAffinityValid {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\t// find one\n\t\t\tresult = append(result, volume)\n\t\t\tcontinue\n\t\t}\n\n\t\tif node == nil && delayBinding {\n\t\t\t// PV controller does not bind this claim.\n\t\t\t// Scheduler will handle binding unbound volumes\n\t\t\t// Scheduler path will have node != nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// filter out:\n\t\t// - volumes bound to another claim\n\t\t// - volumes whose labels don't match the claim's selector, if specified\n\t\t// - volumes in Class that is not requested\n\t\t// - volumes whose NodeAffinity does not match the node\n\t\tif volume.Spec.ClaimRef != nil {\n\t\t\tcontinue\n\t\t} else if selector != nil && !selector.Matches(labels.Set(volume.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tif v1helper.GetPersistentVolumeClass(volume) != requestedClass {\n\t\t\tcontinue\n\t\t}\n\t\tif !nodeAffinityValid {\n\t\t\tcontinue\n\t\t}\n\n\t\t//if node != nil {\n\t\t//\t// Scheduler path\n\t\t//\t// Check that the access modes match\n\t\t//\tif !checkAccessModes(claim, volume) {\n\t\t//\t\tcontinue\n\t\t//\t}\n\t\t//}\n\t\t// CHANGED: always check for local PV\n\t\tif !checkAccessModes(claim, volume) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// find one\n\t\tresult = append(result, volume)\n\t}\n\n\treturn result, nil\n}", "func (a *Client) DeleteProtectedEntity(params *DeleteProtectedEntityParams, opts ...ClientOption) (*DeleteProtectedEntityOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteProtectedEntityParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"deleteProtectedEntity\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/astrolabe/{service}/{protectedEntityID}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteProtectedEntityReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*DeleteProtectedEntityOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for deleteProtectedEntity: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (x InfrastructureHostEntity) GetNerdStorage() NerdStorageEntityScope {\n\treturn x.NerdStorage\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RunTests executes the scorecard tests as configured
func (o Scorecard) RunTests(ctx context.Context) (testOutput v1alpha3.Test, err error) { err = o.TestRunner.Initialize(ctx) if err != nil { return testOutput, err } tests := o.selectTests() if len(tests) == 0 { return testOutput, nil } for _, test := range tests { result, err := o.TestRunner.RunTest(ctx, test) if err != nil { result = convertErrorToStatus(test.Name, err) } testOutput.Status.Results = append(testOutput.Status.Results, result.Results...) } if !o.SkipCleanup { err = o.TestRunner.Cleanup(ctx) if err != nil { return testOutput, err } } return testOutput, nil }
[ "func (o Scorecard) RunTests() (testOutput v1alpha2.ScorecardOutput, err error) {\n\ttests := selectTests(o.Selector, o.Config.Tests)\n\tif len(tests) == 0 {\n\t\tfmt.Println(\"no tests selected\")\n\t\treturn testOutput, err\n\t}\n\n\tbundleData, err := getBundleData(o.BundlePath)\n\tif err != nil {\n\t\treturn testOutput, fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\t// create a ConfigMap holding the bundle contents\n\to.bundleConfigMap, err = createConfigMap(o, bundleData)\n\tif err != nil {\n\t\treturn testOutput, fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\n\tfor i, test := range tests {\n\t\tvar err error\n\t\ttests[i].TestPod, err = o.runTest(test)\n\t\tif err != nil {\n\t\t\treturn testOutput, fmt.Errorf(\"test %s failed %w\", test.Name, err)\n\t\t}\n\t}\n\n\tif !o.SkipCleanup {\n\t\tdefer deletePods(o.Client, tests)\n\t\tdefer deleteConfigMap(o.Client, o.bundleConfigMap)\n\t}\n\n\terr = o.waitForTestsToComplete(tests)\n\tif err != nil {\n\t\treturn testOutput, err\n\t}\n\n\ttestOutput = getTestResults(o.Client, tests)\n\n\treturn testOutput, err\n}", "func (o Scorecard) Run(ctx context.Context) (testOutput v1alpha3.TestList, err error) {\n\ttestOutput = v1alpha3.NewTestList()\n\n\tif err := o.TestRunner.Initialize(ctx); err != nil {\n\t\treturn testOutput, err\n\t}\n\n\tfor _, stage := range o.Config.Stages {\n\t\ttests := o.selectTests(stage)\n\t\tif len(tests) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttests = o.setTestDefaults(tests)\n\n\t\toutput := make(chan v1alpha3.Test, len(tests))\n\t\tif stage.Parallel {\n\t\t\to.runStageParallel(ctx, tests, output)\n\t\t} else {\n\t\t\to.runStageSequential(ctx, tests, output)\n\t\t}\n\t\tclose(output)\n\t\tfor o := range output {\n\t\t\ttestOutput.Items = append(testOutput.Items, o)\n\t\t}\n\t}\n\n\t// Get timeout error, if any, before calling Cleanup() so deletes don't cause a timeout.\n\tselect {\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\tdefault:\n\t}\n\n\tif !o.SkipCleanup {\n\t\t// Use a separate context for cleanup, which needs to run regardless of a prior timeout.\n\t\tclctx, cancel := context.WithTimeout(context.Background(), cleanupTimeout)\n\t\tdefer cancel()\n\t\tif err := o.TestRunner.Cleanup(clctx); err != nil {\n\t\t\treturn testOutput, err\n\t\t}\n\t}\n\n\treturn testOutput, err\n}", "func (ts *TestSuite) RunTests() {\n\n\tif len(ts.Tests) == 0 {\n\t\tout.Printf(\"No tests to run\\n\")\n\t\treturn\n\t}\n\n\tstartTime := time.Now()\n\n\t// setup search\n\ts := search.NewSearch()\n\tsl := search.NewSearchLimits()\n\tsl.MoveTime = ts.Time\n\tsl.Depth = ts.Depth\n\tif sl.MoveTime > 0 {\n\t\tsl.TimeControl = true\n\t}\n\n\tout.Printf(\"Running Test Suite\\n\")\n\tout.Printf(\"==================================================================\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"No of tests: %d\\n\", len(ts.Tests))\n\tout.Println()\n\n\t// execute all tests and store results in the\n\t// test instance\n\tfor i, t := range ts.Tests {\n\t\tout.Printf(\"Test %d of %d\\nTest: %s -- Target Result %s\\n\", i+1, len(ts.Tests), t.line, t.targetMoves.StringUci())\n\t\tstartTime2 := time.Now()\n\t\trunSingleTest(s, sl, t)\n\t\telapsedTime := time.Since(startTime2)\n\t\tt.nodes = s.NodesVisited()\n\t\tt.time = s.LastSearchResult().SearchTime\n\t\tt.nps = util.Nps(s.NodesVisited(), s.LastSearchResult().SearchTime)\n\t\tout.Printf(\"Test finished in %d ms with result %s (%s) - nps: %d\\n\\n\",\n\t\t\telapsedTime.Milliseconds(), t.rType.String(), t.actual.StringUci(), t.nps)\n\t}\n\n\t// sum up result for report\n\ttr := &SuiteResult{}\n\tfor _, t := range ts.Tests {\n\t\ttr.Counter++\n\t\tswitch t.rType {\n\t\tcase NotTested:\n\t\t\ttr.NotTestedCounter++\n\t\tcase Skipped:\n\t\t\ttr.SkippedCounter++\n\t\tcase Failed:\n\t\t\ttr.FailedCounter++\n\t\tcase Success:\n\t\t\ttr.SuccessCounter++\n\t\t}\n\t\ttr.Nodes += t.nodes\n\t\ttr.Time += t.time\n\t}\n\tts.LastResult = tr\n\n\telapsed := time.Since(startTime)\n\n\t// print report\n\tout.Printf(\"Results for Test Suite\\n\", ts.FilePath)\n\tout.Printf(\"------------------------------------------------------------------------------------------------------------------------------------\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\" %-4s | %-10s | %-8s | %-8s | %-15s | %s | %s\\n\", \" Nr.\", \"Result\", \"Move\", \"Value\", \"Expected Result\", \"Fen\", \"Id\")\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tfor i, t := range ts.Tests {\n\t\tif t.tType == DM {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s%-15d | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), \"dm \", t.mateDepth, t.fen, t.id)\n\t\t} else {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s %-15s | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), t.tType.String(), t.targetMoves.StringUci(), t.fen, t.id)\n\t\t}\n\t}\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\"Summary:\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"Successful: %-3d (%d %%)\\n\", tr.SuccessCounter, 100*tr.SuccessCounter/tr.Counter)\n\tout.Printf(\"Failed: %-3d (%d %%)\\n\", tr.FailedCounter, 100*tr.FailedCounter/tr.Counter)\n\tout.Printf(\"Skipped: %-3d (%d %%)\\n\", tr.SkippedCounter, 100*tr.SkippedCounter/tr.Counter)\n\tout.Printf(\"Not tested: %-3d (%d %%)\\n\", tr.NotTestedCounter, 100*tr.NotTestedCounter/tr.Counter)\n\tout.Printf(\"Test time: %s\\n\", elapsed)\n\tout.Printf(\"Configuration: %s\\n\", config.Settings.String())\n}", "func (tests Tests) Run() (results *Results) {\n\tresults = NewResults()\n\tfor _, test := range tests {\n\t\tresult := test.Run()\n\t\tresults.Add(result)\n\t}\n\tresults.End()\n\treturn\n}", "func RunSubtests(ctx *Context) {\n\tfor name, fn := range tests {\n\t\tctx.Run(name, fn)\n\t}\n}", "func RunTests(opts Options) {\n\tif opts.Cleanup {\n\t\terr := CleanupTests(opts.Driver, opts.DSN, opts.Verbose)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Cleanup failed: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\t_ = flag.Set(\"test.run\", opts.Match)\n\tif opts.Verbose {\n\t\t_ = flag.Set(\"test.v\", \"true\")\n\t}\n\ttests := []testing.InternalTest{\n\t\t{\n\t\t\tName: \"MainTest\",\n\t\t\tF: func(t *testing.T) {\n\t\t\t\tTest(t, opts.Driver, opts.DSN, opts.Suites, opts.RW)\n\t\t\t},\n\t\t},\n\t}\n\n\tmainStart(tests)\n}", "func (runner TestSuiteRunner) RunTests(testNamesToRun map[string]bool, testParallelism uint) (allTestsPassed bool, executionErr error) {\n\tallTests := runner.testSuite.GetTests()\n\n\t// If the user doesn't specify any test names to run, run all of them\n\tif len(testNamesToRun) == 0 {\n\t\ttestNamesToRun = map[string]bool{}\n\t\tfor testName, _ := range allTests {\n\t\t\ttestNamesToRun[testName] = true\n\t\t}\n\t}\n\n\t// Validate all the requested tests exist\n\ttestsToRun := make(map[string]testsuite.Test)\n\tfor testName, _ := range testNamesToRun {\n\t\ttest, found := allTests[testName]\n\t\tif !found {\n\t\t\treturn false, stacktrace.NewError(\"No test registered with name '%v'\", testName)\n\t\t}\n\t\ttestsToRun[testName] = test\n\t}\n\n\texecutionInstanceId := uuid.Generate()\n\ttestParams, err := buildTestParams(executionInstanceId, testsToRun, runner.networkWidthBits)\n\tif err != nil {\n\t\treturn false, stacktrace.Propagate(err, \"An error occurred building the test params map\")\n\t}\n\n\t// Initialize a Docker client\n\tdockerClient, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\treturn false, stacktrace.Propagate(err,\"Failed to initialize Docker client from environment.\")\n\t}\n\n\ttestExecutor := parallelism.NewTestExecutorParallelizer(\n\t\texecutionInstanceId,\n\t\tdockerClient,\n\t\trunner.testControllerImageName,\n\t\trunner.testControllerLogLevel,\n\t\trunner.customTestControllerEnvVars,\n\t\ttestParallelism)\n\n\tlogrus.Infof(\"Running %v tests with execution ID %v...\", len(testsToRun), executionInstanceId.String())\n\tallTestsPassed = testExecutor.RunInParallelAndPrintResults(testParams)\n\treturn allTestsPassed, nil\n}", "func main() {\n\ttest_plain_background()\n\ttest_cloud()\n\ttest_enemy()\n\ttest_move_background()\n\ttest_display_score()\n}", "func RunTests() {\n\tresults := make([]searchResult, 0)\n\n\tresp, err := http.Get(\"http://0.0.0.0:50005/search?s=\" + url.QueryEscape(\"interesting and amazing facts\") + \"&size=1\")\n\tif err != nil {\n\t\tlogrus.Fatalf(\"search %s failed with %s\", \"interesting and amazing facts\", err)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"search %s failed with %s\", \"interesting and amazing facts\", err)\n\t}\n\terr = json.Unmarshal(body, &results)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"search %s failed with %s\", \"interesting and amazing facts\", err)\n\t}\n\tlogrus.Info(results)\n\n}", "func executeTests(k8s *Kubernetes, testList []*TestCase) []*TestCase {\n\terr := bootstrap(k8s)\n\tfailOnError(err)\n\n\t//make a copy and append the tests with CIDRs\n\tcidrTests := []*TestCase{\n\t\t{\"IngressOverlapCIDRBlocks\", testIngressOverlapCIDRBlocks()},\n\t}\n\tmodifiedTestList := append(testList, cidrTests...)\n\n\tfor _, testCase := range modifiedTestList {\n\t\tlog.Infof(\"running test case %s\", testCase.Name)\n\t\tlog.Debugf(\"cleaning-up previous policies and sleeping for %v\", networkPolicyDelay)\n\t\terr = k8s.CleanNetworkPolicies(namespaces)\n\t\ttime.Sleep(networkPolicyDelay)\n\t\tfailOnError(err)\n\t\tfor _, step := range testCase.Steps {\n\t\t\tlog.Infof(\"running step %s of test case %s\", step.Name, testCase.Name)\n\t\t\treachability := step.Reachability\n\t\t\tpolicy := step.NetworkPolicy\n\t\t\tif policy != nil {\n\t\t\t\tlog.Debugf(\"creating policy and sleeping for %v\", networkPolicyDelay)\n\t\t\t\t_, err := k8s.CreateOrUpdateNetworkPolicy(policy.Namespace, policy)\n\t\t\t\tfailOnError(err)\n\t\t\t\ttime.Sleep(networkPolicyDelay)\n\t\t\t}\n\t\t\tstart := time.Now()\n\t\t\tvalidate(k8s, reachability, step.Port)\n\t\t\tstep.Duration = time.Now().Sub(start)\n\t\t\treachability.PrintSummary(true, true, true)\n\t\t}\n\t}\n\treturn modifiedTestList\n}", "func (ss *Sim) RunTestAll() {\n\tss.StopNow = false\n\tss.TestAll(&ss.TestEnv)\n\tss.Stopped()\n\n\tif ss.NoGui {\n\t\tos.Exit(0)\n\t}\n}", "func (t *TestBehaviour) RunAllTests() {\n\t// Need our authentication tokens for each persona/user\n\tt.RunGetCLAProjectManagerToken()\n\t// do an initial get query\n\tt.RunGetProtectedBranch(nil)\n\t// first enable it\n\tt.RunUpdateProtectionBranch(\"Enable Protections\", &models.GithubRepositoryBranchProtectionInput{\n\t\tEnforceAdmin: swag.Bool(true),\n\t\tStatusChecks: []*models.GithubRepositoryBranchProtectionStatusChecks{\n\t\t\t{Name: swag.String(\"EasyCLA\"), Enabled: swag.Bool(true)},\n\t\t},\n\t})\n\t//then disable it again\n\tt.RunUpdateProtectionBranch(\"Disable Protections\", &models.GithubRepositoryBranchProtectionInput{\n\t\tEnforceAdmin: swag.Bool(false),\n\t\tStatusChecks: []*models.GithubRepositoryBranchProtectionStatusChecks{\n\t\t\t{Name: swag.String(\"EasyCLA\"), Enabled: swag.Bool(false)},\n\t\t},\n\t})\n}", "func (suite FeatureTestSuite) Run(t *testing.T, buildFunc feature.BuildFunc) {\n\tfor _, test := range suite {\n\t\trunTest(t, test, buildFunc)\n\t}\n}", "func RunTests(t *testing.T, tests map[string]SubTest) {\n\tfor name, test := range tests {\n\t\tdomainKeeper, ctx, mocks := NewTestKeeper(t, true)\n\t\t// set default mock.Supply not to fail\n\t\tmocks.Supply.SetSendCoinsFromAccountToModule(func(ctx types.Context, addr types.AccAddress, moduleName string, coins types.Coins) error {\n\t\t\treturn nil\n\t\t})\n\t\t// set default fees\n\t\tsetFees := domainKeeper.ConfigurationKeeper.(ConfigurationSetter).SetFees\n\t\tfees := configuration.NewFees()\n\t\tfees.SetDefaults(\"testcoin\")\n\t\tsetFees(ctx, fees)\n\t\t// run sub SubTest\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// run before SubTest\n\t\t\tif test.BeforeTest != nil {\n\t\t\t\tif test.BeforeTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.BeforeTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.BeforeTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\n\t\t\tif test.TestBlockTime != 0 {\n\t\t\t\tt := time.Unix(test.TestBlockTime, 0)\n\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t}\n\t\t\t// run actual SubTest\n\t\t\ttest.Test(t, domainKeeper, ctx, mocks)\n\n\t\t\t// run after SubTest\n\t\t\tif test.AfterTest != nil {\n\t\t\t\tif test.AfterTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.AfterTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.AfterTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\t\t})\n\t}\n}", "func (o Scorecard) ListTests() (output v1alpha3.Test, err error) {\n\ttests := o.selectTests()\n\tif len(tests) == 0 {\n\t\treturn output, err\n\t}\n\n\tfor _, test := range tests {\n\t\toutput.Status.Results = append(output.Status.Results, v1alpha3.TestResult{Name: test.Name})\n\t}\n\n\treturn output, err\n}", "func RunBuiltinTests(t *testing.T, resourceType string) {\n\t// Get a list of all test cases\n\tbox := packr.NewBox(\"./assets/\" + resourceType)\n\tfilesInBox := box.List()\n\tfor _, file := range filesInBox {\n\t\tif isTestCase(file) {\n\t\t\tabsolutePath, _ := filepath.Abs(\"./assets/\" + resourceType + \"/\" + file)\n\t\t\tts, err := loadTestSuite(absolutePath)\n\t\t\tif err != nil {\n\t\t\t\tassert.Nil(t, err, \"Cannot load test case\")\n\t\t\t}\n\t\t\trunTestSuite(t, ts)\n\t\t}\n\t}\n}", "func (sfs *SuiteFS) RunTests(t *testing.T, userName string, stFuncs ...SuiteTestFunc) {\n\tvfs := sfs.vfsSetup\n\n\t_, _ = sfs.User(t, userName)\n\tdefer sfs.User(t, sfs.initUser.Name())\n\n\tfor _, stFunc := range stFuncs {\n\t\tfuncName := runtime.FuncForPC(reflect.ValueOf(stFunc).Pointer()).Name()\n\t\tfuncName = funcName[strings.LastIndex(funcName, \".\")+1 : strings.LastIndex(funcName, \"-\")]\n\t\ttestDir := vfs.Join(sfs.rootDir, funcName)\n\n\t\tsfs.CreateTestDir(t, testDir)\n\n\t\tt.Run(funcName, func(t *testing.T) {\n\t\t\tstFunc(t, testDir)\n\t\t})\n\n\t\tsfs.RemoveTestDir(t, testDir)\n\t}\n}", "func (tr *TestRunner) RunTests(ctx context.Context, testInfo TestInfo) error {\n\n\ttestStartedAt := time.Now()\n\n\tjmeterConfig, err := getJMeterConf(testInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tr.sendTestsStartedEvent(testInfo); err != nil {\n\t\tlogger.Errorf(\"Could not send test '.started' event: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := tr.runHealthCheck(testInfo, testStartedAt, jmeterConfig); err != nil {\n\t\treturn err\n\t}\n\n\tval := ctx.Value(gracefulShutdownKey)\n\tif val != nil {\n\t\tif wg, ok := val.(*sync.WaitGroup); ok {\n\t\t\twg.Add(1)\n\t\t}\n\t}\n\n\tresChan := make(chan TestResult, 1)\n\tgo tr.runTests(testInfo, jmeterConfig, resChan)\n\tgo tr.sendTestResult(ctx, testInfo, resChan, testStartedAt)\n\n\treturn nil\n}", "func (app *interpreter) Tests(testable linkers.Testable) error {\n\treturn app.testable.Execute(testable)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
selectTests applies an optionally passed selector expression against the configured set of tests, returning the selected tests
func (o Scorecard) selectTests() []Test { selected := make([]Test, 0) for _, test := range o.Config.Tests { if o.Selector.String() == "" || o.Selector.Matches(labels.Set(test.Labels)) { // TODO olm manifests check selected = append(selected, test) } } return selected }
[ "func selectTests(selector labels.Selector, tests []Test) []Test {\n\n\tselected := make([]Test, 0)\n\n\tfor _, test := range tests {\n\t\tif selector.String() == \"\" || selector.Matches(labels.Set(test.Labels)) {\n\t\t\t// TODO olm manifests check\n\t\t\tselected = append(selected, test)\n\t\t}\n\t}\n\treturn selected\n}", "func selectTests(suite string, tests []string) string {\n\tif len(tests) == 0 {\n\t\treturn suite\n\t}\n\treturn \"--file=-\"\n}", "func SupportSelectors(flagSet *pflag.FlagSet, p *[]string) {\n\tflagSet.StringArrayVarP(p, \"selector\", \"l\", []string{}, \"filter results by a set of comma-separated label selectors\")\n}", "func Select(N int, dirs ...string) []string {\n\treturn MatchSelect(\"\", N, dirs...)\n}", "func HasSelector(labelKeysAndValues []string, fieldKeysAndValue []string) func(t *testing.T, a interface{}) {\n\treturn func(t *testing.T, a interface{}) {\n\t\tHasLabelSelector(labelKeysAndValues...)(t, a)\n\t\tHasFieldSelector(fieldKeysAndValue...)(t, a)\n\t}\n}", "func (tse *taskSelectorEvaluator) evalSelector(s Selector) ([]string, error) {\n\t// keep a slice of results per criterion\n\tresults := []string{}\n\tif len(s) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot evaluate selector with no criteria\")\n\t}\n\tfor i, sc := range s {\n\t\ttaskNames, err := tse.evalCriterion(sc)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error evaluating '%v' selector: %v\", s, err)\n\t\t}\n\t\tif i == 0 {\n\t\t\tresults = taskNames\n\t\t} else {\n\t\t\t// intersect all evaluated criteria\n\t\t\tresults = util.StringSliceIntersection(results, taskNames)\n\t\t}\n\t}\n\tif len(results) == 0 {\n\t\treturn nil, fmt.Errorf(\"no tasks satisfy selector '%v'\", s)\n\t}\n\treturn results, nil\n}", "func Sel(a ...any) []any {\n\treturn a\n}", "func SelectorFromProviderSpec(providerspec *machinev1beta1.ProviderSpec) (labels.Selector, error) {\n\tconfig, err := configFromProviderSpec(*providerspec)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading ProviderSpec: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tselector := labels.NewSelector()\n\tvar reqs labels.Requirements\n\tfor labelKey, labelVal := range config.HostSelector.MatchLabels {\n\t\tr, err := labels.NewRequirement(labelKey, selection.Equals, []string{labelVal})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create MatchLabel requirement: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\treqs = append(reqs, *r)\n\t}\n\tfor _, req := range config.HostSelector.MatchExpressions {\n\t\tlowercaseOperator := selection.Operator(strings.ToLower(string(req.Operator)))\n\t\tr, err := labels.NewRequirement(req.Key, lowercaseOperator, req.Values)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create MatchExpression requirement: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\treqs = append(reqs, *r)\n\t}\n\tselector = selector.Add(reqs...)\n\treturn selector, nil\n}", "func (conn *Conn) SelectTestResults() []Metrics {\n\tdb := conn.db\n\tsqlStr := \"SELECT result_type, x_axis, y_axis FROM test_results\"\n\trows, err := db.Query(sqlStr)\n\tif err != nil {\n\t\tlog.Printf(\"Error query: %v\\n\", err)\n\t}\n\n\tvar resultType string\n\tvar x float64\n\tvar y float64\n\tresult := make([]Metrics, 0)\n\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\terr = rows.Scan(&resultType, &x, &y)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error scanning row: %v\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t\tresult = append(result, Metrics{resultType, x, y})\n\t}\n\treturn result\n}", "func MatchSelect(pattern string, N int, dirs ...string) []string {\n\tw := &walk{pattern: pattern}\n\tfor _, p := range dirs {\n\t\tif e := filepath.Walk(p, w.Walk); e != nil {\n\t\t\tlog.Printf(\"couldn't walk %s: %s, skipping.\\n\", p, e)\n\t\t}\n\t}\n\tn := 0\n\torgLen := len(w.Collect)\n\tinsts := make([]string, 0, N)\n\tfor n < N {\n\t\tif len(w.Collect) == 0 {\n\t\t\tlog.Printf(\"couldn't select %d, only %d choices.\\n\", N, orgLen)\n\t\t\tbreak\n\t\t}\n\t\te := len(w.Collect)\n\t\tc := rand.Intn(e)\n\t\te--\n\t\tw.Collect[c], w.Collect[e] = w.Collect[e], w.Collect[c]\n\t\tinsts = append(insts, w.Collect[e])\n\t\tn++\n\t\tw.Collect = w.Collect[:e]\n\t}\n\treturn insts\n}", "func (suite *PouchVolumeSuite) TestVolumeCreateWithSelector(c *check.C) {\n\tpc, _, _, _ := runtime.Caller(0)\n\ttmpname := strings.Split(runtime.FuncForPC(pc).Name(), \".\")\n\tvar funcname string\n\tfor i := range tmpname {\n\t\tfuncname = tmpname[i]\n\t}\n\n\tcommand.PouchRun(\"volume\", \"create\", \"--name\", funcname, \"--selector\", \"test=foo\").Assert(c, icmd.Success)\n\tdefer command.PouchRun(\"volume\", \"remove\", funcname)\n}", "func (r *Render) selectFiles(withRE, withoutRE *regexp.Regexp) []*File {\n\tselected := []*File{}\n\tfor _, f := range r.files {\n\t\tif withRE == nil && withoutRE == nil {\n\t\t\tselected = append(selected, f)\n\t\t\tcontinue\n\t\t}\n\n\t\tname := f.Name()\n\t\tif withRE != nil && !withRE.MatchString(name) {\n\t\t\tr.logger.Debugf(\"Skipping file '%s' by not matching with clause ('%s')\",\n\t\t\t\tname, withRE.String())\n\t\t\tcontinue\n\t\t} else if withoutRE != nil && withoutRE.MatchString(name) {\n\t\t\tr.logger.Debugf(\"Skipping file '%s' by matching without clause ('%s')\",\n\t\t\t\tname, withoutRE.String())\n\t\t\tcontinue\n\t\t}\n\t\tselected = append(selected, f)\n\t}\n\treturn selected\n}", "func (e *Evaluator) Select(expr string) ([]ast.Node, error) {\n\tn := e.n.Copy()\n\t_expr, err := xpath.Compile(expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"expr cannot compile: %w\", err)\n\t}\n\n\treturn nodes(_expr.Select(n)), nil\n}", "func doTests(t *testing.T, tests []string) {\n\tdoTestsParam(t, tests, TestParams{\n\t\textensions: parser.CommonExtensions,\n\t\tRendererOptions: html.RendererOptions{\n\t\t\tFlags: html.CommonFlags,\n\t\t},\n\t})\n}", "func (m *MockUI) Select(arg0 string, arg1 []string) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Select\", arg0, arg1)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Run(\n\tdao DAO,\n\tstatements, setupStatements, teardownStatements, solutions []Statement,\n\tselectedQuestions []string,\n) ([]TestResult, error) {\n\tvar testResult = []TestResult{}\n\n\ti := 0\n\tresults, errs, err := dao.ExecuteStatements(setupStatements, teardownStatements, statements)\n\tsolutionResults, _, err := dao.ExecuteStatements(setupStatements, teardownStatements, solutions)\n\ttestcases := ConvertTablesToTestCases(solutionResults)\n\n\tif err != nil {\n\t\treturn testResult, err\n\t}\n\n\tfor _, expected := range testcases {\n\t\tif !stringInSlice(expected.Index, selectedQuestions) && len(selectedQuestions) > 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif i >= len(results) {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: Result{},\n\t\t\t\t\tPass: false,\n\t\t\t\t},\n\t\t\t)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\ttable := results[i]\n\t\terr := errs[i]\n\t\t// Query has syntax error\n\t\tif err != nil {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: false,\n\t\t\t\t\tError: err,\n\t\t\t\t},\n\t\t\t)\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(table.Content, expected.Content) {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: false,\n\t\t\t\t},\n\t\t\t)\n\t\t} else {\n\t\t\ttestResult = append(\n\t\t\t\ttestResult,\n\t\t\t\tTestResult{\n\t\t\t\t\tExpected: expected,\n\t\t\t\t\tActual: table,\n\t\t\t\t\tPass: true,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\ti++\n\t}\n\n\treturn testResult, nil\n}", "func (c *Configuration) TestsForSuites(names ...string) <-chan JobWithError {\n\toutput := make(chan JobWithError)\n\tgo func() {\n\t\tc.mutex.RLock()\n\t\tdefer c.mutex.RUnlock()\n\n\t\tseen := make(map[string]struct{})\n\t\tfor _, suite := range names {\n\t\t\ttests, ok := c.suites[suite]\n\t\t\tif !ok {\n\t\t\t\toutput <- JobWithError{\n\t\t\t\t\tJob: nil,\n\t\t\t\t\tErr: errors.Errorf(\"suite named '%s' does not exist\", suite),\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, test := range tests {\n\t\t\t\tj, ok := c.tests[test]\n\n\t\t\t\tvar err error\n\t\t\t\tif !ok {\n\t\t\t\t\terr = errors.Errorf(\"test name %s is specified in suite %s\"+\n\t\t\t\t\t\t\"but does not exist\", test, suite)\n\t\t\t\t}\n\n\t\t\t\tif _, ok := seen[test]; ok {\n\t\t\t\t\t// this means a test is specified in more than one suite,\n\t\t\t\t\t// and we only want to dispatch it once.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tseen[test] = struct{}{}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\toutput <- JobWithError{Job: nil, Err: err}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\toutput <- JobWithError{Job: j, Err: nil}\n\t\t\t}\n\t\t}\n\n\t\tclose(output)\n\t}()\n\n\treturn output\n}", "func (c *Configuration) GetAllTests(tests, suites []string) <-chan JobWithError {\n\toutput := make(chan JobWithError)\n\tgo func() {\n\t\tfor check := range c.TestsByName(tests...) {\n\t\t\toutput <- check\n\t\t}\n\n\t\tfor check := range c.TestsForSuites(suites...) {\n\t\t\toutput <- check\n\t\t}\n\t\tclose(output)\n\t}()\n\n\treturn output\n}", "func (m *MockFullNode) MpoolSelects(arg0 context.Context, arg1 types0.TipSetKey, arg2 []float64) ([][]*types.SignedMessage, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MpoolSelects\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([][]*types.SignedMessage)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize sets up the bundle configmap for tests
func (r *PodTestRunner) Initialize(ctx context.Context) error { bundleData, err := r.getBundleData() if err != nil { return fmt.Errorf("error getting bundle data %w", err) } r.configMapName, err = r.CreateConfigMap(ctx, bundleData) if err != nil { return fmt.Errorf("error creating ConfigMap %w", err) } return nil }
[ "func (r *PodTestRunner) Initialize(ctx context.Context) error {\n\tbundleData, err := r.getBundleData()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting bundle data %w\", err)\n\t}\n\n\tr.configMapName, err = r.CreateConfigMap(ctx, bundleData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating ConfigMap %w\", err)\n\t}\n\n\treturn nil\n\n}", "func init() {\n\tinitconf(configLocation)\n}", "func (c *ConfigMapSpec) Initialize(qserv *qservv1beta1.Qserv) client.Object {\n\tc.qserv = qserv\n\tvar object client.Object = &v1.ConfigMap{}\n\treturn object\n}", "func init() {\n\t// bootstrap cosmos-sdk config for kava chain\n\tkavaConfig := sdk.GetConfig()\n\tapp.SetBech32AddressPrefixes(kavaConfig)\n\tapp.SetBip44CoinType(kavaConfig)\n\tkavaConfig.Seal()\n}", "func init() {\n\tcallbacks = make(map[ModuleType]*ConfigCallback, 8)\n\tmodules = make(map[string]ModuleType, 32)\n}", "func init() {\n\tcore.RegisterConfigGroup(defaultConfigs)\n\tcore.RegisterServiceWithConfig(\"api\", &api.ApiServiceFactory{}, api.Configs)\n\tcore.RegisterServiceWithConfig(\"collector\", &collector.CollectorServiceFactory{}, collector.Configs)\n}", "func init() {\n\tfor group, values := range defaultConfigs {\n\t\tcore.RegisterConfig(group, values)\n\t}\n\tcore.RegisterService(\"indicator\", indicator.Configs, &indicator.IndicatorServiceFactory{})\n\tcore.RegisterService(\"executor\", executor.Configs, &executor.ExecutorServiceFactory{})\n}", "func init() {\n\tRegistry.Add(eksinfo.New())\n\tRegistry.Add(vpcinfo.New())\n\tRegistry.Add(iamresourceusage.New())\n}", "func TestInit(t *testing.T) {\n\tinitConfig()\n\tinitMesherConfig()\n\tskywalking.Init()\n\tassert.NotEqual(t, gcconfig.MicroserviceDefinition, nil)\n}", "func init() {\n\tenv.Load()\n\tdatabase.Build()\n\trouter.Build()\n\tinitializeServiceModules()\n}", "func (c *Configurations) Init() error {\n\tc.Version = Version\n\tc.Location = \"Local\"\n\tc.Debug = Debug\n\n\t// server\n\tc.Server = &Server{}\n\tc.Server.Init()\n\n\t// redis init\n\tc.RedisConf = &RedisConf{}\n\tc.RedisConf.Init()\n\n\treturn nil\n}", "func init() {\n\tinitCfgDir()\n\tinitCreds()\n}", "func (aMan *AvroDescManager) Init() {\n\taMan.Amap = make(AvroPackageDescMap)\n}", "func iamTestSuiteInitialize(ctx *godog.TestSuiteContext) {\n\tctx.BeforeSuite(func() {\n\t\t//check dependancies ...\n\t\tif iam == nil {\n\t\t\t// not been given one so set default\n\t\t\tiam = kubernetes.NewDefaultIAM()\n\t\t}\n\t\t//setup AzureIdentity stuff ..?? Or should this be a pre-test setup\n\t\t// psp.CreateConfigMap()\n\t})\n\n\tctx.AfterSuite(func() {\n\t\t//tear down AzureIdentity stuff?\n\t\t// psp.DeleteConfigMap()\n\t})\n}", "func (o *CommonObjectProperties) InitBundle() error {\n\to.SetObjectType(\"bundle\")\n\to.SetNewSTIXID(\"bundle\")\n\treturn nil\n}", "func (rc *RootConfig) Init() error {\n\tregisterPOJO()\n\tif err := rc.Logger.Init(); err != nil { // init default logger\n\t\treturn err\n\t}\n\tif err := rc.ConfigCenter.Init(rc); err != nil {\n\t\tlogger.Infof(\"[Config Center] Config center doesn't start\")\n\t\tlogger.Debugf(\"config center doesn't start because %s\", err)\n\t} else {\n\t\tif err = rc.Logger.Init(); err != nil { // init logger using config from config center again\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := rc.Application.Init(); err != nil {\n\t\treturn err\n\t}\n\n\t// init user define\n\tif err := rc.Custom.Init(); err != nil {\n\t\treturn err\n\t}\n\n\t// init protocol\n\tprotocols := rc.Protocols\n\tif len(protocols) <= 0 {\n\t\tprotocol := &ProtocolConfig{}\n\t\tprotocols = make(map[string]*ProtocolConfig, 1)\n\t\tprotocols[constant.Dubbo] = protocol\n\t\trc.Protocols = protocols\n\t}\n\tfor _, protocol := range protocols {\n\t\tif err := protocol.Init(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// init registry\n\tregistries := rc.Registries\n\tif registries != nil {\n\t\tfor _, reg := range registries {\n\t\t\tif err := reg.Init(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := rc.MetadataReport.Init(rc); err != nil {\n\t\treturn err\n\t}\n\tif err := rc.Otel.Init(rc.Application); err != nil {\n\t\treturn err\n\t}\n\tif err := rc.Metric.Init(); err != nil {\n\t\treturn err\n\t}\n\tfor _, t := range rc.Tracing {\n\t\tif err := t.Init(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := initRouterConfig(rc); err != nil {\n\t\treturn err\n\t}\n\t// provider、consumer must last init\n\tif err := rc.Provider.Init(rc); err != nil {\n\t\treturn err\n\t}\n\tif err := rc.Consumer.Init(rc); err != nil {\n\t\treturn err\n\t}\n\tif err := rc.Shutdown.Init(); err != nil {\n\t\treturn err\n\t}\n\tSetRootConfig(*rc)\n\t// todo if we can remove this from Init in the future?\n\trc.Start()\n\treturn nil\n}", "func init() {\n\t// Clear the air and set some stock testing values\n\tos.Setenv(\"TEST_VAULT_SKIP_VERIFY\", \"\")\n\tos.Setenv(\"TEST_VAULT_TOKEN\", \"\")\n\tviper.SetEnvPrefix(\"test_vault\")\n\tviper.BindEnv(\"token\")\n\tviper.BindEnv(\"skip_verify\")\n\n\tviper.SetConfigName(\"vaultVisualizeConfig\") // name of config file (without extension)\n\tviper.AddConfigPath(\"../test\") // path to look for the config file in\n\terr := viper.ReadInConfig() // Find and read the config file\n\tif err != nil { // Handle errors reading the config file\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n}", "func init() {\n\t// set reasonable defaults\n\tsetDefaults()\n\n\t// override defaults with configuration read from configuration file\n\tviper.AddConfigPath(\"$GOPATH/src/github.com/xlab-si/emmy/config\")\n\terr := loadConfig(\"defaults\", \"yml\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Initialize(context *clusterd.Context, config *Config) error {\n\tlogger.Infof(\"Creating config for MGR %s with keyring %s\", config.Name, config.Keyring)\n\tconfig.ClusterInfo.Log(logger)\n\tif err := generateConfigFiles(context, config); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate mgr config files. %+v\", err)\n\t}\n\n\tutil.WriteFileToLog(logger, cephconfig.DefaultConfigFilePath())\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleanup deletes pods and configmap resources from this test run
func (r PodTestRunner) Cleanup(ctx context.Context) (err error) { err = r.deletePods(ctx, r.configMapName) if err != nil { return err } err = r.deleteConfigMap(ctx, r.configMapName) if err != nil { return err } return nil }
[ "func (r PodTestRunner) Cleanup(ctx context.Context) (err error) {\n\n\terr = r.deletePods(ctx, r.configMapName)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = r.deleteConfigMap(ctx, r.configMapName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *PodCheck) Cleanup() {}", "func (f *Framework) CleanUp(ns string) error {\n\tlogrus.Info(\"Cleaning up now.\")\n\tdefer logrus.Info(\"Finished cleanup.\")\n\tagonesV1 := f.AgonesClient.AgonesV1()\n\tdeleteOptions := metav1.DeleteOptions{}\n\tlistOptions := metav1.ListOptions{}\n\n\t// find and delete pods created by tests and labeled with our special label\n\tpods := f.KubeClient.CoreV1().Pods(ns)\n\tctx := context.Background()\n\tpodList, err := pods.List(ctx, metav1.ListOptions{\n\t\tLabelSelector: AutoCleanupLabelKey + \"=\" + AutoCleanupLabelValue,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range podList.Items {\n\t\tp := &podList.Items[i]\n\t\tif err := pods.Delete(ctx, p.ObjectMeta.Name, deleteOptions); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = agonesV1.Fleets(ns).DeleteCollection(ctx, deleteOptions, listOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = f.AgonesClient.AutoscalingV1().FleetAutoscalers(ns).DeleteCollection(ctx, deleteOptions, listOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn agonesV1.GameServers(ns).\n\t\tDeleteCollection(ctx, deleteOptions, listOptions)\n}", "func (p *PodmanTestIntegration) CleanupPod() {\n\t// TODO\n}", "func CleanupLandscaperResources(ctx context.Context, kubeClient client.Client, ns string) error {\n\tinstList := &lsv1alpha1.InstallationList{}\n\tif err := kubeClient.List(ctx, instList, client.InNamespace(ns)); err != nil {\n\t\treturn err\n\t}\n\tfor _, obj := range instList.Items {\n\t\tif err := envtest.CleanupForObject(ctx, kubeClient, &obj, time.Minute); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\texecList := &lsv1alpha1.ExecutionList{}\n\tif err := kubeClient.List(ctx, execList, client.InNamespace(ns)); err != nil {\n\t\treturn err\n\t}\n\tfor _, obj := range execList.Items {\n\t\tif err := envtest.CleanupForObject(ctx, kubeClient, &obj, time.Minute); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdiList := &lsv1alpha1.DeployItemList{}\n\tif err := kubeClient.List(ctx, diList, client.InNamespace(ns)); err != nil {\n\t\treturn err\n\t}\n\tfor _, obj := range diList.Items {\n\t\tif err := envtest.CleanupForObject(ctx, kubeClient, &obj, time.Minute); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcmList := &corev1.ConfigMapList{}\n\tif err := kubeClient.List(ctx, instList, client.InNamespace(ns)); err != nil {\n\t\treturn err\n\t}\n\tfor _, obj := range cmList.Items {\n\t\tif err := envtest.CleanupForObject(ctx, kubeClient, &obj, time.Second); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestServerCleanup(ctx context.Context, f *framework.Framework, config TestConfig) {\n\tginkgo.By(fmt.Sprint(\"cleaning the environment after \", config.Prefix))\n\tdefer ginkgo.GinkgoRecover()\n\n\tif config.ServerImage == \"\" {\n\t\treturn\n\t}\n\n\terr := e2epod.DeletePodWithWaitByName(ctx, f.ClientSet, config.Prefix+\"-server\", config.Namespace)\n\tframework.ExpectNoError(err, \"delete pod %v in namespace %v\", config.Prefix+\"-server\", config.Namespace)\n}", "func (s *executor) cleanupResources(ctx context.Context) {\n\tif s.pod != nil {\n\t\tr := retry.WithBuildLog(\n\t\t\t&retryableKubeAPICall{\n\t\t\t\tmaxTries: defaultTries,\n\t\t\t\tfn: func() error {\n\t\t\t\t\treturn s.kubeClient.CoreV1().\n\t\t\t\t\t\tPods(s.pod.Namespace).\n\t\t\t\t\t\tDelete(ctx, s.pod.Name, metav1.DeleteOptions{\n\t\t\t\t\t\t\tGracePeriodSeconds: s.Config.Kubernetes.GetCleanupGracePeriodSeconds(),\n\t\t\t\t\t\t\tPropagationPolicy: &PropagationPolicy,\n\t\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t},\n\t\t\t&s.BuildLogger,\n\t\t)\n\t\tretryable := retry.NewWithBackoffDuration(r, defaultRetryMinBackoff, defaultRetryMaxBackoff)\n\t\terr := retryable.Run()\n\t\tif err != nil {\n\t\t\ts.Errorln(fmt.Sprintf(\"Error cleaning up pod: %s\", err.Error()))\n\t\t}\n\t}\n\n\tif s.credentials != nil && len(s.credentials.OwnerReferences) == 0 {\n\t\tr := retry.WithBuildLog(\n\t\t\t&retryableKubeAPICall{\n\t\t\t\tmaxTries: defaultTries,\n\t\t\t\tfn: func() error {\n\t\t\t\t\treturn s.kubeClient.CoreV1().\n\t\t\t\t\t\tSecrets(s.configurationOverwrites.namespace).\n\t\t\t\t\t\tDelete(ctx, s.credentials.Name, metav1.DeleteOptions{\n\t\t\t\t\t\t\tGracePeriodSeconds: s.Config.Kubernetes.GetCleanupGracePeriodSeconds(),\n\t\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t},\n\t\t\t&s.BuildLogger,\n\t\t)\n\t\tretryable := retry.NewWithBackoffDuration(r, defaultRetryMinBackoff, defaultRetryMaxBackoff)\n\t\terr := retryable.Run()\n\t\tif err != nil {\n\t\t\ts.Errorln(fmt.Sprintf(\"Error cleaning up secrets: %s\", err.Error()))\n\t\t}\n\t}\n}", "func DumpSpecResourcesAndCleanup(ctx context.Context, specName string, namespace *corev1.Namespace, e2eCtx *E2EContext) {\n\tLogf(\"Running DumpSpecResourcesAndCleanup for namespace %q\", namespace.Name)\n\t// Dump all Cluster API related resources to artifacts before deleting them.\n\tcancelWatches := e2eCtx.Environment.Namespaces[namespace]\n\n\tdumpAllResources := func(directory ...string) {\n\t\tdumpSpecResources(ctx, e2eCtx, namespace, directory...)\n\t\tdumpOpenStack(ctx, e2eCtx, e2eCtx.Environment.BootstrapClusterProxy.GetName(), directory...)\n\t}\n\n\tdumpAllResources()\n\n\tif !e2eCtx.Settings.SkipCleanup {\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tr := recover()\n\t\t\t\tif r == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// If we fail to delete the cluster, dump all resources again to a different directory before propagating the failure\n\t\t\t\tdumpAllResources(\"deletion-failure\")\n\t\t\t\tpanic(r)\n\t\t\t}()\n\t\t\tframework.DeleteAllClustersAndWait(ctx, framework.DeleteAllClustersAndWaitInput{\n\t\t\t\tClient: e2eCtx.Environment.BootstrapClusterProxy.GetClient(),\n\t\t\t\tNamespace: namespace.Name,\n\t\t\t}, e2eCtx.E2EConfig.GetIntervals(specName, \"wait-delete-cluster\")...)\n\t\t}()\n\n\t\tLogf(\"Deleting namespace used for hosting the %q test spec\", specName)\n\t\tframework.DeleteNamespace(ctx, framework.DeleteNamespaceInput{\n\t\t\tDeleter: e2eCtx.Environment.BootstrapClusterProxy.GetClient(),\n\t\t\tName: namespace.Name,\n\t\t})\n\t}\n\tcancelWatches()\n\tdelete(e2eCtx.Environment.Namespaces, namespace)\n}", "func cleanupDeprecatedResources(c serviceCAOperator) error {\n\tklog.V(4).Infof(\"attempting removal of deprecated resources in namespace %q\", operatorclient.TargetNamespace)\n\n\t// Configmaps are no longer used to configure the controllers\n\tnamespace := operatorclient.TargetNamespace\n\tconfigMapNames := []string{\n\t\t\"service-serving-cert-signer-config\",\n\t\t\"apiservice-cabundle-injector-config\",\n\t\t\"configmap-cabundle-injector-config\",\n\t}\n\tfor _, configMapName := range configMapNames {\n\t\terr := c.corev1Client.ConfigMaps(namespace).Delete(configMapName, &metav1.DeleteOptions{})\n\t\tif err != nil && !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (pm partitionMap) cleanup() {\n\tfor ns, partitions := range pm {\n\t\tfor i := range partitions.Replicas {\n\t\t\tfor j := range partitions.Replicas[i] {\n\t\t\t\tpartitions.Replicas[i][j] = nil\n\t\t\t}\n\t\t\tpartitions.Replicas[i] = nil\n\t\t}\n\n\t\tpartitions.Replicas = nil\n\t\tpartitions.regimes = nil\n\n\t\tdelete(pm, ns)\n\t}\n}", "func CleanUp(ctx context.Context, cfg *config.Config, pipeline *pipelines.Pipeline, name names.Name) error {\n\tkubectlPath, err := cfg.Tools[config.Kubectl].Resolve()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := proc.GracefulCommandContext(ctx, kubectlPath, \"delete\",\n\t\t\"all\",\n\t\t\"-l\", k8s.StackLabel+\"=\"+name.DNSName(),\n\t)\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"could not delete k8s resources: %v\", err)\n\t}\n\treturn nil\n}", "func (h *HealthCheck) cleanup() {\n\tif h.frameworkError != nil && h.namespace != nil {\n\t\tglog.V(4).Infof(\"Cleaning up. Deleting the binding, instance and test namespace %v\", h.namespace.Name)\n\t\th.serviceCatalogClientSet.ServicecatalogV1beta1().ServiceBindings(h.namespace.Name).Delete(h.bindingName, nil)\n\t\th.serviceCatalogClientSet.ServicecatalogV1beta1().ServiceInstances(h.namespace.Name).Delete(h.instanceName, nil)\n\t\tDeleteKubeNamespace(h.kubeClientSet, h.namespace.Name)\n\t\th.namespace = nil\n\t}\n}", "func (p *Pod) cleanupFiles(silent bool) error {\n\tfor _, ns := range p.namespaces {\n\t\tglog.V(8).Infof(\"Removing binded namespace %s\", ns.Path)\n\t\terr := namespace.Remove(ns)\n\t\tif err != nil && !silent {\n\t\t\treturn fmt.Errorf(\"could not remove namespace: %v\", err)\n\t\t}\n\t}\n\tglog.V(8).Infof(\"Removing pod base directory %s\", p.baseDir)\n\terr := os.RemoveAll(p.baseDir)\n\tif err != nil && !silent {\n\t\treturn fmt.Errorf(\"could not cleanup pod: %v\", err)\n\t}\n\tglog.V(8).Infof(\"Removing pod log directory %s\", p.GetLogDirectory())\n\terr = os.RemoveAll(p.GetLogDirectory())\n\tif err != nil && !silent {\n\t\treturn fmt.Errorf(\"could not remove log directory: %v\", err)\n\t}\n\treturn nil\n}", "func (t *Tester) Cleanup() {\n\tfmt.Println(\"Cleaning up\")\n\tfmt.Printf(\"Functions to be cleaned: %v\\n\", t.functions)\n\tfor _, name := range t.functions {\n\t\tcmd := exec.Command(\"dispatch\", \"delete\", \"function\", name)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Unable to delete function %v. %v\\n\", name, err)\n\t\t\tlog.Println(\"Can't delete function\")\n\t\t}\n\t}\n\tfmt.Printf(\"Apis to be cleaned: %v\\n\", t.apis)\n\tfor _, name := range t.apis {\n\t\tcmd := exec.Command(\"dispatch\", \"delete\", \"api\", name)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Unable to delete function %v. %v\\n\", name, err)\n\t\t\tlog.Println(\"Can't delete function\")\n\t\t}\n\t}\n\n}", "func CleanUpPods(client kubernetes.Interface) {\n\tnamespaces := getNamespaces(client)\n\tfor _, namespace := range namespaces {\n\t\tpodsClient := client.CoreV1().Pods(namespace)\n\t\tpodList, err := podsClient.List(\n\t\t\tcontext.TODO(),\n\t\t\tk8sapi.ListOptions{LabelSelector: getAppLabelSelectorString()},\n\t\t)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, pod := range podList.Items {\n\t\t\tlogs.InfoLogger.Printf(\n\t\t\t\t\"Deleting pod \\\"%s\\\" in namespace \\\"%s\\\"\\n\",\n\t\t\t\tpod.Name,\n\t\t\t\tpod.Namespace,\n\t\t\t)\n\t\t\tpodsClient.Delete(context.TODO(), pod.ObjectMeta.Name, k8sapi.DeleteOptions{})\n\t\t}\n\t}\n}", "func (f *HelmConfiguration) Cleanup() {\n\tif len(f.Folder) > 0 {\n\t\tos.RemoveAll(f.Folder)\n\t}\n}", "func CleanupServiceResources(ctx context.Context, c clientset.Interface, loadBalancerName, region, zone string) {\n\tframework.TestContext.CloudConfig.Provider.CleanupServiceResources(ctx, c, loadBalancerName, region, zone)\n}", "func (r *runner) cleanOldPods() error {\n\tpodsPath := filepath.Join(kurmaPath, string(kurmaPathPods))\n\tfis, err := ioutil.ReadDir(podsPath)\n\tif err != nil {\n\t\tr.log.Errorf(\"failed to check for existing pods: %v\", err)\n\t\treturn nil\n\t}\n\n\tfor _, fi := range fis {\n\t\tif err := os.RemoveAll(filepath.Join(podsPath, fi.Name())); err != nil {\n\t\t\tr.log.Errorf(\"failed to cleanup existing pods: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func Clean(c Config) {\n\n\tSetup(&c)\n\tContainers, _ := model.DockerContainerList()\n\n\tfor _, Container := range Containers {\n\t\ttarget := false\n\t\tif l := Container.Labels[\"pygmy.enable\"]; l == \"true\" || l == \"1\" {\n\t\t\ttarget = true\n\t\t}\n\t\tif l := Container.Labels[\"pygmy\"]; l == \"pygmy\" {\n\t\t\ttarget = true\n\t\t}\n\n\t\tif target {\n\t\t\terr := model.DockerKill(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully killed %v.\\n\", Container.Names[0])\n\t\t\t}\n\n\t\t\terr = model.DockerRemove(Container.ID)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"Successfully removed %v.\\n\", Container.Names[0])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, network := range c.Networks {\n\t\tmodel.DockerNetworkRemove(&network)\n\t\tif s, _ := model.DockerNetworkStatus(&network); s {\n\t\t\tfmt.Printf(\"Successfully removed network %v\\n\", network.Name)\n\t\t} else {\n\t\t\tfmt.Printf(\"Network %v was not removed\\n\", network.Name)\n\t\t}\n\t}\n\n\tfor _, resolver := range c.Resolvers {\n\t\tresolver.Clean()\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
waitForTestToComplete waits for a fixed amount of time while checking for a test pod to complete
func (r PodTestRunner) waitForTestToComplete(ctx context.Context, p *v1.Pod) (err error) { podCheck := wait.ConditionFunc(func() (done bool, err error) { var tmp *v1.Pod tmp, err = r.Client.CoreV1().Pods(p.Namespace).Get(ctx, p.Name, metav1.GetOptions{}) if err != nil { return true, fmt.Errorf("error getting pod %s %w", p.Name, err) } if tmp.Status.Phase == v1.PodSucceeded || tmp.Status.Phase == v1.PodFailed { return true, nil } return false, nil }) err = wait.PollImmediateUntil(time.Duration(1*time.Second), podCheck, ctx.Done()) return err }
[ "func (r PodTestRunner) waitForTestToComplete(ctx context.Context, p *v1.Pod) (err error) {\n\n\tpodCheck := wait.ConditionFunc(func() (done bool, err error) {\n\t\tvar tmp *v1.Pod\n\t\ttmp, err = r.Client.CoreV1().Pods(p.Namespace).Get(ctx, p.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn true, fmt.Errorf(\"error getting pod %s %w\", p.Name, err)\n\t\t}\n\t\tfor _, s := range tmp.Status.ContainerStatuses {\n\t\t\tif s.Name == \"scorecard-test\" {\n\t\t\t\tif s.State.Terminated != nil {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false, nil\n\t})\n\n\terr = wait.PollImmediateUntil(1*time.Second, podCheck, ctx.Done())\n\treturn err\n\n}", "func (o Scorecard) waitForTestsToComplete(tests []Test) (err error) {\n\twaitTimeInSeconds := int(o.WaitTime.Seconds())\n\tfor elapsedSeconds := 0; elapsedSeconds < waitTimeInSeconds; elapsedSeconds++ {\n\t\tallPodsCompleted := true\n\t\tfor _, test := range tests {\n\t\t\tp := test.TestPod\n\t\t\tvar tmp *v1.Pod\n\t\t\ttmp, err = o.Client.CoreV1().Pods(p.Namespace).Get(context.TODO(), p.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting pod %s %w\", p.Name, err)\n\t\t\t}\n\t\t\tif tmp.Status.Phase != v1.PodSucceeded {\n\t\t\t\tallPodsCompleted = false\n\t\t\t}\n\n\t\t}\n\t\tif allPodsCompleted {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn fmt.Errorf(\"error - wait time of %d seconds has been exceeded\", o.WaitTime)\n\n}", "func waitForPodSuccess(c *client.Client, podName string, contName string, tryFor time.Duration) error {\n\ttrySecs := int(tryFor.Seconds())\n\tfor i := 0; i <= trySecs; i += 5 {\n\t\tif i > 0 {\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t\tpod, err := c.Pods(api.NamespaceDefault).Get(podName)\n\t\tif err != nil {\n\t\t\tLogf(\"Get pod failed, ignoring for 5s: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// Cannot use pod.Status.Phase == api.PodSucceeded/api.PodFailed due to #2632\n\t\tci, ok := pod.Status.Info[contName]\n\t\tif !ok {\n\t\t\tLogf(\"No Status.Info for container %s in pod %s yet\", contName, podName)\n\t\t} else {\n\t\t\tif ci.State.Termination != nil {\n\t\t\t\tif ci.State.Termination.ExitCode == 0 {\n\t\t\t\t\tBy(\"Saw pod success\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\tLogf(\"Saw pod failure: %+v\", ci.State.Termination)\n\t\t\t\t}\n\t\t\t\tLogf(\"Waiting for pod %q status to be success or failure\", podName)\n\t\t\t} else {\n\t\t\t\tLogf(\"Nil State.Termination for container %s in pod %s so far\", contName, podName)\n\t\t\t}\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Gave up waiting for pod %q status to be success or failure after %d seconds\", podName, trySecs)\n}", "func waitForPodSuccess(c *client.Client, podName string, contName string) bool {\n\tfor i := 0; i < 10; i++ {\n\t\tif i > 0 {\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t\tpod, err := c.Pods(api.NamespaceDefault).Get(podName)\n\t\tif err != nil {\n\t\t\tglog.Warningf(\"Get pod failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// Cannot use pod.Status.Phase == api.PodSucceeded/api.PodFailed due to #2632\n\t\tci, ok := pod.Status.Info[contName]\n\t\tif !ok {\n\t\t\tglog.Infof(\"No Status.Info for container %s in pod %s yet\", contName, podName)\n\t\t} else {\n\t\t\tif ci.State.Termination != nil {\n\t\t\t\tif ci.State.Termination.ExitCode == 0 {\n\t\t\t\t\tglog.Infof(\"Saw pod success\")\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\tglog.Infof(\"Saw pod failure: %+v\", ci.State.Termination)\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Waiting for pod %q status to be success or failure\", podName)\n\t\t\t} else {\n\t\t\t\tglog.Infof(\"Nil State.Termination for container %s in pod %s so far\", contName, podName)\n\t\t\t}\n\t\t}\n\t}\n\tglog.Warningf(\"Gave up waiting for pod %q status to be success or failure\", podName)\n\treturn false\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal int) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\tguardPods, err := cs.CoreV1Interface.Pods(\"openshift-etcd\").List(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: guardPodsLabelSelectorString,\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Printf(\" error listing etcd guard pods: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tnumGuardPods := len(guardPods.Items)\n\t\tif numGuardPods == 0 {\n\t\t\tfmt.Println(\" no guard pods found\")\n\t\t\treturn false, nil\n\t\t}\n\t\tnumReadyPods := countReadyPods(guardPods.Items)\n\t\tif numReadyPods == expectedTotal {\n\t\t\tfmt.Printf(\" %d ready etcd guard pods found! \\n\", numReadyPods)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *volumeReactor) waitTest(test controllerTest) error {\n\t// start with 10 ms, multiply by 2 each step, 10 steps = 10.23 seconds\n\tbackoff := wait.Backoff{\n\t\tDuration: 10 * time.Millisecond,\n\t\tJitter: 0,\n\t\tFactor: 2,\n\t\tSteps: 10,\n\t}\n\terr := wait.ExponentialBackoff(backoff, func() (done bool, err error) {\n\t\t// Finish all operations that are in progress\n\t\tr.ctrl.runningOperations.WaitForCompletion()\n\n\t\t// Return 'true' if the reactor reached the expected state\n\t\terr1 := r.checkClaims(test.expectedClaims)\n\t\terr2 := r.checkVolumes(test.expectedVolumes)\n\t\tif err1 == nil && err2 == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn err\n}", "func (r *volumeReactor) waitTest(test controllerTest) error {\n\t// start with 10 ms, multiply by 2 each step, 10 steps = 10.23 seconds\n\tbackoff := wait.Backoff{\n\t\tDuration: 10 * time.Millisecond,\n\t\tJitter: 0,\n\t\tFactor: 2,\n\t\tSteps: 10,\n\t}\n\terr := wait.ExponentialBackoff(backoff, func() (done bool, err error) {\n\t\t// Finish all operations that are in progress\n\t\tr.ctrl.runningOperations.WaitForCompletion()\n\n\t\t// Return 'true' if the reactor reached the expected state\n\t\terr1 := r.CheckClaims(test.expectedClaims)\n\t\terr2 := r.CheckVolumes(test.expectedVolumes)\n\t\tif err1 == nil && err2 == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn err\n}", "func waitForFailure(f *framework.Framework, name string, timeout time.Duration) {\n\tgomega.Expect(e2epod.WaitForPodCondition(f.ClientSet, f.Namespace.Name, name, fmt.Sprintf(\"%s or %s\", v1.PodSucceeded, v1.PodFailed), timeout,\n\t\tfunc(pod *v1.Pod) (bool, error) {\n\t\t\tswitch pod.Status.Phase {\n\t\t\tcase v1.PodFailed:\n\t\t\t\treturn true, nil\n\t\t\tcase v1.PodSucceeded:\n\t\t\t\treturn true, fmt.Errorf(\"pod %q successed with reason: %q, message: %q\", name, pod.Status.Reason, pod.Status.Message)\n\t\t\tdefault:\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t},\n\t)).To(gomega.Succeed(), \"wait for pod %q to fail\", name)\n}", "func (t *JobUpgradeTest) Test(f *framework.Framework, done <-chan struct{}, upgrade UpgradeType) {\n\t<-done\n\tBy(\"Ensuring active pods == parallelism\")\n\trunning, err := framework.CheckForAllJobPodsRunning(f.ClientSet, t.namespace, t.job.Name, 2)\n\tExpect(err).NotTo(HaveOccurred())\n\tExpect(running).To(BeTrue())\n}", "func (td *OsmTestData) WaitForPodsRunningReady(ns string, timeout time.Duration, nExpectedRunningPods int, labelSelector *metav1.LabelSelector) error {\n\ttd.T.Logf(\"Wait up to %v for %d pods ready in ns [%s]...\", timeout, nExpectedRunningPods, ns)\n\n\tlistOpts := metav1.ListOptions{\n\t\tFieldSelector: \"status.phase=Running\",\n\t}\n\n\tif labelSelector != nil {\n\t\tlabelMap, _ := metav1.LabelSelectorAsMap(labelSelector)\n\t\tlistOpts.LabelSelector = labels.SelectorFromSet(labelMap).String()\n\t}\n\n\tfor start := time.Now(); time.Since(start) < timeout; time.Sleep(2 * time.Second) {\n\t\tpods, err := td.Client.CoreV1().Pods(ns).List(context.TODO(), listOpts)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to list pods\")\n\t\t}\n\n\t\tif len(pods.Items) < nExpectedRunningPods {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tnReadyPods := 0\n\t\tfor _, pod := range pods.Items {\n\t\t\tfor _, cond := range pod.Status.Conditions {\n\t\t\t\tif cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\t\tnReadyPods++\n\t\t\t\t\tif nReadyPods == nExpectedRunningPods {\n\t\t\t\t\t\ttd.T.Logf(\"Finished waiting for NS [%s].\", ns)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tpods, err := td.Client.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list pods\")\n\t}\n\ttd.T.Log(\"Pod Statuses in namespace\", ns)\n\tfor _, pod := range pods.Items {\n\t\tstatus, _ := json.MarshalIndent(pod.Status, \"\", \" \")\n\t\ttd.T.Logf(\"Pod %s:\\n%s\", pod.Name, status)\n\t}\n\n\treturn fmt.Errorf(\"not all pods were Running & Ready in NS %s after %v\", ns, timeout)\n}", "func waitForCompletion(sensor SensorInterface, i2c *i2c.I2C) (timeout bool, err error) {\n\tfor i := 0; i < 10; i++ {\n\t\tflag, err := sensor.IsBusy(i2c)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif flag == false {\n\t\t\treturn false, nil\n\t\t}\n\t\ttime.Sleep(5 * time.Millisecond)\n\t}\n\treturn true, nil\n}", "func waitForPodSuccessTimeout(k8sClientset *kubernetes.Clientset, podName, namespace string, interval, timeout time.Duration) error {\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\tpod, err := k8sClientset.CoreV1().Pods(namespace).Get(context.Background(), podName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// Cannot get pod yet, retry.\n\t\t\treturn false, err\n\t\t}\n\t\tif pod.Status.Phase == v1.PodSucceeded {\n\t\t\treturn true, nil\n\t\t}\n\t\tif pod.Status.Phase == v1.PodFailed {\n\t\t\treturn true, fmt.Errorf(\"pod %s completed with failed status: %+v\", podName, pod.Status)\n\t\t}\n\t\t// None of above, retry.\n\t\treturn false, nil\n\t})\n}", "func waitForPodsToBeInTerminatingPhase(sshClientConfig *ssh.ClientConfig, svcMasterIP string,\n\tpodName string, namespace string, timeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get pod %s --kubeconfig %s -n %s --no-headers|awk '{print $3}'\",\n\t\t\tpodName, kubeConfigPath, namespace)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIP)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\t\tcmd)\n\t\tif err != nil || cmdResult.Code != 0 {\n\t\t\tfssh.LogResult(cmdResult)\n\t\t\treturn false, fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\t\tcmd, svcMasterIP, err)\n\t\t}\n\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tframework.Logf(\"stdout %s\", cmdResult.Stdout)\n\t\tpodPhase := strings.TrimSpace(cmdResult.Stdout)\n\t\tif podPhase == \"Terminating\" {\n\t\t\tframework.Logf(\"Pod %s is in terminating state\", podName)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func waitForApiServerToBeUp(svcMasterIp string, sshClientConfig *ssh.ClientConfig,\n\ttimeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get ns,sc --kubeconfig %s\",\n\t\t\tkubeConfigPath)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIp)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIp,\n\t\t\tcmd)\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err == nil {\n\t\t\tframework.Logf(\"Apiserver is fully up\")\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func (agent *AgentCommandRunner) waitForReadyTimeout(timeout time.Duration) error {\n\tinterval := 100 * time.Millisecond\n\tmaxRetries := timeout.Milliseconds() / interval.Milliseconds()\n\terr := backoff.Retry(func() error {\n\t\t_, err := agent.executeAgentCmdWithError([]string{\"status\"})\n\t\tif err != nil {\n\t\t\treturn errors.New(\"agent not ready\")\n\t\t}\n\t\treturn nil\n\t}, backoff.WithMaxRetries(backoff.NewConstantBackOff(interval), uint64(maxRetries)))\n\treturn err\n}", "func waitForDeploymentComplete(name, ns string, c kubernetes.Interface, t int) error {\n\tvar (\n\t\tdeployment *apps.Deployment\n\t\treason string\n\t\terr error\n\t)\n\ttimeout := time.Duration(t) * time.Minute\n\terr = wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tdeployment, err = c.AppsV1().Deployments(ns).Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// TODO need to check rolling update\n\n\t\t// When the deployment status and its underlying resources reach the\n\t\t// desired state, we're done\n\t\tif deployment.Status.Replicas == deployment.Status.ReadyReplicas {\n\t\t\treturn true, nil\n\t\t}\n\t\te2elog.Logf(\"deployment status: expected replica count %d running replica count %d\", deployment.Status.Replicas, deployment.Status.ReadyReplicas)\n\t\treason = fmt.Sprintf(\"deployment status: %#v\", deployment.Status.String())\n\t\treturn false, nil\n\t})\n\n\tif errors.Is(err, wait.ErrWaitTimeout) {\n\t\terr = fmt.Errorf(\"%s\", reason)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for deployment %q status to match expectation: %w\", name, err)\n\t}\n\treturn nil\n}", "func waitForDeploymentComplete(name, ns string, c clientset.Interface, t int) error {\n\tvar (\n\t\tdeployment *apps.Deployment\n\t\treason string\n\t\terr error\n\t)\n\ttimeout := time.Duration(t) * time.Minute\n\terr = wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tdeployment, err = c.AppsV1().Deployments(ns).Get(name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// TODO need to check rolling update\n\n\t\t// When the deployment status and its underlying resources reach the\n\t\t// desired state, we're done\n\t\tif deployment.Status.Replicas == deployment.Status.ReadyReplicas {\n\t\t\treturn true, nil\n\t\t}\n\n\t\treason = fmt.Sprintf(\"deployment status: %#v\", deployment.Status)\n\t\tframework.Logf(reason)\n\n\t\treturn false, nil\n\t})\n\n\tif err == wait.ErrWaitTimeout {\n\t\terr = fmt.Errorf(\"%s\", reason)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error waiting for deployment %q status to match expectation: %v\", name, err)\n\t}\n\treturn nil\n}", "func waitForRunning(client *clientv3.Client, pod string, ctx context.Context, modRev int64) {\n\twatcher := clientv3.NewWatcher(client)\n\trch := watcher.Watch(ctx, pod, clientv3.WithRev(modRev))\n\tconst runningPhase = \"Running\"\n\tfor wresp := range rch {\n\t\tfor _, ev := range wresp.Events {\n\t\t\tjq := utils.GetJsonqQuery(ev.Kv.Value)\n\t\t\tif phase, _ := jq.String(\"status\", \"phase\"); phase == runningPhase {\n\t\t\t\twatcher.Close()\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *HumioClusterReconciler) waitForNewPod(ctx context.Context, hnp *HumioNodePool, previousPodList []corev1.Pod, expectedPod *corev1.Pod) error {\n\t// We must check only pods that were running prior to the new pod being created, and we must only include pods that\n\t// were running the same revision as the newly created pod. This is because there may be pods under the previous\n\t// revision that were still terminating when the new pod was created\n\tvar expectedPodCount int\n\tfor _, pod := range previousPodList {\n\t\tif pod.Annotations[podHashAnnotation] == expectedPod.Annotations[podHashAnnotation] {\n\t\t\texpectedPodCount++\n\t\t}\n\t}\n\t// This will account for the newly created pod\n\texpectedPodCount++\n\n\tfor i := 0; i < waitForPodTimeoutSeconds; i++ {\n\t\tvar podsMatchingRevisionCount int\n\t\tlatestPodList, err := kubernetes.ListPods(ctx, r, hnp.GetNamespace(), hnp.GetNodePoolLabels())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, pod := range latestPodList {\n\t\t\tif pod.Annotations[podHashAnnotation] == expectedPod.Annotations[podHashAnnotation] {\n\t\t\t\tpodsMatchingRevisionCount++\n\t\t\t}\n\t\t}\n\t\tr.Log.Info(fmt.Sprintf(\"validating new pod was created. expected pod count %d, current pod count %d\", expectedPodCount, podsMatchingRevisionCount))\n\t\tif podsMatchingRevisionCount >= expectedPodCount {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(time.Second * 1)\n\t}\n\treturn fmt.Errorf(\"timed out waiting to validate new pod was created\")\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DelayDuration returns delay duration in a form of time.Duration.
func (o *Options) DelayDuration() time.Duration { return time.Second * time.Duration(o.Delay) }
[ "func (d *Delay) TimeDuration() time.Duration {\n\treturn time.Duration(d.Duration*1000) * time.Millisecond\n}", "func (m Task) GetDelayDuration() time.Duration {\n\treturn time.Duration(m.Metadata.Options.DelayDuration)\n}", "func (r Delay) Length() time.Duration { return time.Duration(r) * time.Millisecond }", "func (b *Backoff) Duration() time.Duration {\n\tbase := b.Min + b.delta\n\tpause := base\n\tif b.Jitter { // Add a number in the range [0, pause).\n\t\tpause += time.Duration(rand.Int63n(int64(pause)))\n\t}\n\n\tnextPause := time.Duration(float64(base) * b.Factor)\n\tif nextPause > b.Max || nextPause < b.Min { // Multiplication could overflow.\n\t\tnextPause = b.Max\n\t}\n\tb.delta = nextPause - b.Min\n\n\treturn pause\n}", "func (clus *Cluster) GetCaseDelayDuration() time.Duration {\n\treturn time.Duration(clus.Tester.CaseDelayMs) * time.Millisecond\n}", "func (timeout *Timeout) Duration() time.Duration {\n\treturn timeout.d\n}", "func (d duration) Duration() time.Duration {\n\treturn time.Duration(d)\n}", "func (o ApplicationStatusOperationStateOperationRetryBackoffOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationRetryBackoff) *string { return v.Duration }).(pulumi.StringPtrOutput)\n}", "func (b *ConstantBackoff) Duration() time.Duration {\n\tb.retry++\n\treturn time.Duration(b.Time) * b.TimeUnit\n}", "func Delay(n *NetOp, statusCode int, pass int, duration time.Duration) time.Duration {\n\tm := fmt.Sprintf(\"Delay: HTTP error %v on %v. Sleeping %v seconds, pass %d of %d.\",\n\t\tstatusCode, n.Endpoint, duration.Seconds(), pass, MaxWaitIterations)\n\tlog.Println(m)\n\tn.Println(m)\n\ttime.Sleep(duration)\n\tduration = duration * Multiplier\n\treturn duration\n}", "func Duration(d time.Duration) WaiterFunc {\n\treturn func(uint, error) time.Duration {\n\t\treturn d\n\t}\n}", "func Duration(d *duration.Duration) time.Duration {\n\tans, err := ptypes.Duration(d)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ans\n}", "func (t *FixedInterval) GetDelay() time.Duration {\n\treturn t.delay\n}", "func DDuration(t *time.Duration, def time.Duration) time.Duration {\n\tif t == nil {\n\t\treturn def\n\t}\n\treturn *t\n}", "func GetDuration(name string) time.Duration { return Conf.GetDuration(name) }", "func (e *Execution) Delay() time.Duration {\n\treturn e.ReceivedTime.Sub(e.ExecDate)\n}", "func (t *RandomInterval) GetDelay() time.Duration {\n\tt.delay = time.Duration(rand.Int63n(t.maxDelay-t.minDelay) + t.minDelay)\n\treturn t.delay\n}", "func (o UpdateConfigurationOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v UpdateConfiguration) *string { return v.Duration }).(pulumi.StringPtrOutput)\n}", "func retryAfterDuration(t string) model.Duration {\n\tparsedDuration, err := time.Parse(http.TimeFormat, t)\n\tif err == nil {\n\t\ts := time.Until(parsedDuration).Seconds()\n\t\treturn model.Duration(s) * model.Duration(time.Second)\n\t}\n\t// The duration can be in seconds.\n\td, err := strconv.Atoi(t)\n\tif err != nil {\n\t\treturn defaultBackoff\n\t}\n\treturn model.Duration(d) * model.Duration(time.Second)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context packs job context (job, id) into binary payload. Not used in the sqs, MessageAttributes used instead
func (i *Item) Context() ([]byte, error) { ctx, err := json.Marshal( struct { ID string `json:"id"` Job string `json:"job"` Headers map[string][]string `json:"headers"` Pipeline string `json:"pipeline"` }{ID: i.Ident, Job: i.Job, Headers: i.Headers, Pipeline: i.Options.Pipeline}, ) if err != nil { return nil, err } return ctx, nil }
[ "func AggregateTokenContextToBytes(context TokenContext) []byte {\n\th := sha256.New()\n\tif len(context.AdditionalContext) != 0 {\n\t\t// leave for backward compatibility when used zones\n\t\th.Write([]byte(`zone`))\n\t\th.Write(context.AdditionalContext)\n\t} else {\n\t\th.Write([]byte(`client`))\n\t\th.Write(context.ClientID)\n\t}\n\treturn h.Sum(nil)\n}", "func (j *JobInterchange) Raw() []byte { return j.Job }", "func (c *encdecContext) marshal() ([]byte, error) {\n\tvar b cryptobyte.Builder\n\tb.AddUint16(uint16(c.suite.kemID))\n\tb.AddUint16(uint16(c.suite.kdfID))\n\tb.AddUint16(uint16(c.suite.aeadID))\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.exporterSecret)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.key)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.baseNonce)\n\t})\n\tb.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(c.sequenceNumber)\n\t})\n\treturn b.Bytes()\n}", "func (c *JobHandler) JobCtx(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tjobID := chi.URLParam(r, \"jobID\")\n\t\tmid, _ := strconv.ParseUint(jobID, 10, 64)\n\t\tjob, err := c.JobService.GetJobByID(mid)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(404), 404)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(r.Context(), keyJobID, job)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (j *Job) Context() context.Context {\n\treturn j.tomb.Context(nil)\n}", "func (bj BatchJob) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tif bj.LivyInfo != nil {\n\t\tobjectMap[\"livyInfo\"] = bj.LivyInfo\n\t}\n\tif bj.Name != nil {\n\t\tobjectMap[\"name\"] = bj.Name\n\t}\n\tif bj.WorkspaceName != nil {\n\t\tobjectMap[\"workspaceName\"] = bj.WorkspaceName\n\t}\n\tif bj.SparkPoolName != nil {\n\t\tobjectMap[\"sparkPoolName\"] = bj.SparkPoolName\n\t}\n\tif bj.SubmitterName != nil {\n\t\tobjectMap[\"submitterName\"] = bj.SubmitterName\n\t}\n\tif bj.SubmitterID != nil {\n\t\tobjectMap[\"submitterId\"] = bj.SubmitterID\n\t}\n\tif bj.ArtifactID != nil {\n\t\tobjectMap[\"artifactId\"] = bj.ArtifactID\n\t}\n\tif bj.JobType != \"\" {\n\t\tobjectMap[\"jobType\"] = bj.JobType\n\t}\n\tif bj.Result != \"\" {\n\t\tobjectMap[\"result\"] = bj.Result\n\t}\n\tif bj.Scheduler != nil {\n\t\tobjectMap[\"schedulerInfo\"] = bj.Scheduler\n\t}\n\tif bj.Plugin != nil {\n\t\tobjectMap[\"pluginInfo\"] = bj.Plugin\n\t}\n\tif bj.Errors != nil {\n\t\tobjectMap[\"errorInfo\"] = bj.Errors\n\t}\n\tif bj.Tags != nil {\n\t\tobjectMap[\"tags\"] = bj.Tags\n\t}\n\tif bj.ID != nil {\n\t\tobjectMap[\"id\"] = bj.ID\n\t}\n\tif bj.AppID != nil {\n\t\tobjectMap[\"appId\"] = bj.AppID\n\t}\n\tif bj.AppInfo != nil {\n\t\tobjectMap[\"appInfo\"] = bj.AppInfo\n\t}\n\tif bj.State != nil {\n\t\tobjectMap[\"state\"] = bj.State\n\t}\n\tif bj.LogLines != nil {\n\t\tobjectMap[\"log\"] = bj.LogLines\n\t}\n\treturn json.Marshal(objectMap)\n}", "func (c Context) JobID() string {\n\treturn c.Current().JobID\n}", "func (j *Job) Encode(payload interface{}) error {\n\tvar err error\n\tj.raw, err = encode(msgpackContentType, &payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func EmbedContext(ctx context.Context) (context.Context, error) {\n\tj, ok := ctx.(journey.Ctx)\n\tif !ok {\n\t\treturn ctx, nil\n\t}\n\tdata, err := journey.MarshalGob(j)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to marshal Context\")\n\t}\n\tmd := metadata.MD{}\n\tmd[contextMD] = append(md[contextMD], string(data))\n\treturn metadata.NewOutgoingContext(ctx, md), nil\n}", "func (job Job) Bytes() (data []byte) {\n data, _ = json.Marshal(job)\n return\n}", "func encodeGetJobPostByIDResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.GetJobPostByIDResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.JobPost.ToProto(), nil\n\t}\n\treturn nil, err\n}", "func SerializeCtx(ctx context.Context, opts ...SerializeOpts) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\te := gob.NewEncoder(buf)\n\n\ts := contextData{\n\t\tValues: make(map[interface{}]interface{}),\n\t\tHasCancel: false,\n\t\tDeadline: time.Time{},\n\t}\n\n\tserialized := buildMap(ctx, s)\n\n\t// if options were passed\n\tif len(opts) > 0 {\n\t\t// override cancel/deadline\n\t\tif !opts[0].RetainCancel {\n\t\t\tserialized.HasCancel = false\n\t\t}\n\t\tif !opts[0].RetainDeadline {\n\t\t\tserialized.HasDeadline = false\n\t\t}\n\t\t// ignore functions to allow serialization to pass\n\t\tif opts[0].IgnoreFunctions {\n\t\t\tfor key, val := range serialized.Values {\n\t\t\t\tif reflect.TypeOf(key).Kind() == reflect.Func || reflect.TypeOf(val).Kind() == reflect.Func {\n\t\t\t\t\tdelete(serialized.Values, key)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Encoding the map\n\terr := e.Encode(serialized)\n\treturn buf.Bytes(), err\n}", "func encodeCreateJobPostResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.CreateJobPostResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.JobPost.ToProto(), nil\n\t}\n\treturn nil, err\n}", "func (_obj *DataService) InsertMessageWithContext(tarsCtx context.Context, msg *Message, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = msg.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"insertMessage\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func RecreateContextWithTimeout(t time.Duration, bs []byte) (context.Context, error) {\n\tuid := string(bs)\n\tvar userdata []byte\n\tvar err error\n\tif strings.HasPrefix(uid, SERSTRPREFIX) {\n\t\ts := string(bs[len(SERSTRPREFIX):])\n\t\tuserdata, err = base64.StdEncoding.DecodeString(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if strings.HasPrefix(uid, SERBINPREFIX) {\n\t\tuserdata = bs[len(SERBINPREFIX):]\n\t} else {\n\t\treturn nil, fmt.Errorf(\"invalid serialised context prefix (%s)\", uid)\n\t}\n\n\tmd := &rc.InMetadata{}\n\t//\tau := &auth.User{}\n\terr = proto.Unmarshal(userdata, md)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif md.User != nil && !common.VerifySignature(md.User) {\n\t\treturn nil, fmt.Errorf(\"[go-easyops] no context (User signature invalid)\")\n\t}\n\tif md.Service != nil && !common.VerifySignature(md.Service) {\n\t\treturn nil, fmt.Errorf(\"[go-easyops] no context (Service signature invalid)\")\n\t}\n\tctx, err := contextForMetaWithTimeout(t, md)\n\treturn ctx, err\n}", "func encodeUpdateJobPostResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.UpdateJobPostResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.JobPost.ToProto(), nil\n\t}\n\treturn nil, err\n}", "func GenerateEmbeddableSpanContext() string {\n\t// should not be exported, purpose of this span is to retrieve OC compliant SpanContext\n\t_, tempSpan := trace.StartSpan(context.Background(), \"\")\n\ttempSpanContext := tempSpan.SpanContext()\n\n\trawContextBytes := propagation.Binary(tempSpanContext)\n\tencodedContext := base64.StdEncoding.EncodeToString(rawContextBytes)\n\n\treturn encodedContext\n}", "func (c *QueryContext) Marshal() []byte {\n\tbuf := bufPool.Get().(*bytes.Buffer)\n\tdefer bufPool.Put(buf)\n\tbuf.Reset()\n\tl := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(l, uint32(len(c.Query)))\n\tbuf.Write(l)\n\tbuf.Write(c.Query)\n\n\tbinary.BigEndian.PutUint32(l, uint32(len(c.User)))\n\tbuf.Write(l)\n\tbuf.Write(c.User)\n\n\tbinary.BigEndian.PutUint32(l, uint32(len(c.Client)))\n\tbuf.Write(l)\n\tbuf.Write(c.Client)\n\n\tbinary.BigEndian.PutUint32(l, uint32(len(c.Database)))\n\tbuf.Write(l)\n\tbuf.Write(c.Database)\n\n\tt, _ := c.Time.MarshalBinary()\n\tbuf.Write(t)\n\treturn buf.Bytes()\n}", "func (m *IncomingContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"observedParticipantId\", m.GetObservedParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"onBehalfOf\", m.GetOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"sourceParticipantId\", m.GetSourceParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"transferor\", m.GetTransferor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert is file convert command
func Convert(c *cli.Context) { var wg sync.WaitGroup for _, path := range c.Args() { wg.Add(1) go func(p string) { defer wg.Done() writeFile(p) }(path) } wg.Wait() }
[ "func convertFile(path string, convBootstrap convArray, convAddresses convAddrs) error {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a temp file to write the output to on success\n\tout, err := atomicfile.New(path, 0600)\n\tif err != nil {\n\t\tin.Close()\n\t\treturn err\n\t}\n\n\terr = convert(in, out, convBootstrap, convAddresses)\n\n\tin.Close()\n\n\tif err != nil {\n\t\t// There was an error so abort writing the output and clean up temp file\n\t\tout.Abort()\n\t} else {\n\t\t// Write the output and clean up temp file\n\t\tout.Close()\n\t}\n\n\treturn err\n}", "func Convert(filename, destExt string) error {\n\tsrcFile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\tswitch destExt {\n\tcase \"png\":\n\t\terr := convertToPNG(filename, srcFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"jpeg\", \"jpg\":\n\t\terr := convertToJPEG(filename, srcFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"gif\":\n\t\terr := convertToGIF(filename, srcFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func convert(c *cli.Context) error {\n\tif isPipe() {\n\n\t\tvar annotatedSequence AnnotatedSequence\n\n\t\t// logic for determining input format, then parses accordingly.\n\t\tif c.String(\"i\") == \"json\" {\n\t\t\tjson.Unmarshal([]byte(stdinToString(os.Stdin)), &annotatedSequence)\n\t\t} else if c.String(\"i\") == \"gbk\" || c.String(\"i\") == \"gb\" {\n\t\t\tannotatedSequence = ParseGbk(stdinToString(os.Stdin))\n\t\t} else if c.String(\"i\") == \"gff\" {\n\t\t\tannotatedSequence = ParseGff(stdinToString(os.Stdin))\n\t\t}\n\n\t\tvar output []byte\n\n\t\t// logic for chosing output format, then builds string to be output.\n\t\tif c.String(\"o\") == \"json\" {\n\t\t\toutput, _ = json.MarshalIndent(annotatedSequence, \"\", \" \")\n\t\t} else if c.String(\"o\") == \"gff\" {\n\t\t\toutput = BuildGff(annotatedSequence)\n\t\t}\n\n\t\t// output to stdout\n\t\tfmt.Print(string(output))\n\n\t\t//\n\t} else {\n\n\t\tvar matches []string\n\n\t\t//take all args and get their pattern matches.\n\t\tfor argIndex := 0; argIndex < c.Args().Len(); argIndex++ {\n\t\t\tmatch, _ := filepath.Glob(c.Args().Get(argIndex))\n\t\t\tmatches = append(matches, match...)\n\t\t}\n\n\t\t//filtering pattern matches for duplicates.\n\t\tmatches = uniqueNonEmptyElementsOf(matches)\n\n\t\t// TODO write basic check to see if input flag or all paths have accepted file extensions.\n\n\t\t// TODO write basic check for reduduncy. I.E converting gff to gff, etc.\n\n\t\t// declaring wait group outside loop\n\t\tvar wg sync.WaitGroup\n\n\t\t// concurrently iterate through each pattern match, read the file, output to new format.\n\t\tfor _, match := range matches {\n\n\t\t\t// incrementing wait group for Go routine\n\t\t\twg.Add(1)\n\n\t\t\t// executing Go routine.\n\t\t\tgo func(match string) {\n\t\t\t\textension := filepath.Ext(match)\n\t\t\t\tvar annotatedSequence AnnotatedSequence\n\n\t\t\t\t// determining which reader to use and parse into AnnotatedSequence struct.\n\t\t\t\tif extension == \".gff\" || c.String(\"i\") == \"gff\" {\n\t\t\t\t\tannotatedSequence = ReadGff(match)\n\t\t\t\t} else if extension == \".gbk\" || extension == \".gb\" || c.String(\"i\") == \"gbk\" || c.String(\"i\") == \"gb\" {\n\t\t\t\t\tannotatedSequence = ReadGbk(match)\n\t\t\t\t} else if extension == \".json\" || c.String(\"i\") == \"json\" {\n\t\t\t\t\tannotatedSequence = ReadJSON(match)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO put default error handling here.\n\t\t\t\t}\n\n\t\t\t\t// determining output format and name, then writing out to name.\n\t\t\t\toutputPath := match[0 : len(match)-len(extension)]\n\t\t\t\tif c.String(\"o\") == \"json\" {\n\t\t\t\t\tWriteJSON(annotatedSequence, outputPath+\".json\")\n\t\t\t\t} else if c.String(\"o\") == \"gff\" {\n\t\t\t\t\tWriteGff(annotatedSequence, outputPath+\".gff\")\n\t\t\t\t}\n\n\t\t\t\t// decrementing wait group.\n\t\t\t\twg.Done()\n\n\t\t\t}(match) // passing match to Go routine anonymous function.\n\n\t\t\t// TODO add delete flag with confirmation.\n\n\t\t}\n\n\t\t// waiting outside for loop for Go routines so they can run concurrently.\n\t\twg.Wait()\n\t}\n\n\treturn nil\n}", "func convertFile(path string, overwrite bool, importPath string, protocPath string) error {\n\tif filepath.Ext(path) != \".proto\" {\n\t\treturn fmt.Errorf(\"convert requires a .proto file\")\n\t}\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to read file %q: %v\", path, err)\n\t}\n\tdefer file.Close()\n\tfilename := filepath.Base(path)\n\tfileToWrite := strings.Replace(filename, \".proto\", \".gunk\", 1)\n\tfullpath := filepath.Join(filepath.Dir(path), fileToWrite)\n\tif _, err := os.Stat(fullpath); !os.IsNotExist(err) && !overwrite {\n\t\treturn fmt.Errorf(\"path already exists %q, use --overwrite\", fullpath)\n\t}\n\tvar b bytes.Buffer\n\tif err := loader.ConvertFromProto(&b, file, filename, importPath, protocPath); err != nil {\n\t\treturn err\n\t}\n\tresult, err := format.Source(b.Bytes())\n\tif err != nil {\n\t\t// Also print the source being formatted, since the go/format\n\t\t// error often points at a specific error in one of its lines.\n\t\tfmt.Fprintln(os.Stderr, b.String())\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(fullpath, result, 0o644); err != nil {\n\t\treturn fmt.Errorf(\"unable to write to file %q: %v\", fullpath, err)\n\t}\n\treturn nil\n}", "func Convert(source, target string) error {\n\tss, err := sources(source)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"looking for sources in %s\", source)\n\t}\n\tfor _, s := range ss {\n\t\tt := filepath.Join(target, chext(s, \".json\"))\n\t\tlog.Printf(\"Transforming %s to %s\", s, t)\n\t\terr := transform(s, t)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"transforming %s\", s)\n\t\t}\n\t}\n\treturn nil\n}", "func convertRunCmd(cmd *cobra.Command, args []string) error {\n\tnoindent := viper.GetBool(\"noindent\")\n\n\tif len(args) == 0 {\n\t\traw, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error reading file\")\n\t\t}\n\t\toutput, err := jsonify.Converter(raw, noindent)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error converting input\")\n\t\t}\n\t\tfmt.Printf(\"%s\", output)\n\t\treturn nil\n\t}\n\n\tfor _, filepath := range args {\n\t\traw, err := ioutil.ReadFile(filepath)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error reading file\")\n\t\t}\n\t\toutput, err := jsonify.Converter(raw, noindent)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error converting input\")\n\t\t}\n\t\tfmt.Printf(\"%s\", output)\n\t}\n\n\treturn nil\n}", "func Convert(ctx context.Context, filePath string) error {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\timgRef, err := vips.LoadImage(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := vips.Webpsave(imgRef.Image(), OutFilePath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InputFileConverter(input string, output string) (string, error) {\n\n\tif (input == \"\") {\n\t\treturn \"\", errors.New(\"no input file name\")\n\t}\n\tif (output == \"\") {\n\t\treturn \"\", errors.New(\"no output file name\")\n\t}\n\tdat, err := os.Open(input)\n\tif (err != nil) {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"unable to open file: %v\", input))\n\t}\n\tdefer dat.Close()\n\treader := csv.NewReader(dat)\n\treader.Comma = '\\t'\n\treader.FieldsPerRecord = -1\n\tcsvData, err := reader.ReadAll()\n\tif err != nil {\n\t\tfmt.Println(\"unable to read file\")\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tvar oneRecord types.Record\n\tvar allRecords []types.Record\n\tfor _, each := range csvData {\n\t\toneRecord.Title = each[titleColumn]\n\t\toneRecord.IarchiveID = each[iarchiveColumn]\n\t\toneRecord.Oclc = each[oclcColumn]\n\t\tallRecords = append(allRecords, oneRecord)\n\t}\n\tstart := fmt.Sprintf(\"Processing %v records.\", len(allRecords))\n\tfmt.Println(start)\n\tjsondata, err := json.Marshal(allRecords) // convert to JSON\n\tif err != nil {\n\t\tfmt.Println(\"error marshalling records\")\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tjsonFile, err := os.Create(output)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer jsonFile.Close()\n\tjsonFile.Write(jsondata)\n\tjsonFile.Close()\n\tmessage := fmt.Sprintf(\"Written to json file: %v\", string(output))\n\treturn message, nil\n}", "func Convert(image string, format formatFlag, outfile string, flags ...convertFlag) error {\n\tcmd := exec.Command(hdiutilPath, \"convert\", image)\n\tcmd.Args = append(cmd.Args, format.formatFlag()...)\n\tcmd.Args = append(cmd.Args, outfile)\n\tif len(flags) > 0 {\n\t\tfor _, flag := range flags {\n\t\t\tcmd.Args = append(cmd.Args, flag.convertFlag()...)\n\t\t}\n\t}\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (spirv *SPIRVCross) Convert(path, variant string, shader []byte, target, version string) (string, error) {\n\tbase := spirv.WorkDir.Path(filepath.Base(path), variant)\n\n\tif err := spirv.WorkDir.WriteFile(base, shader); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to write shader to disk: %w\", err)\n\t}\n\n\tvar cmd *exec.Cmd\n\tswitch target {\n\tcase \"glsl\":\n\t\tcmd = exec.Command(spirv.Bin,\n\t\t\t\"--no-es\",\n\t\t\t\"--version\", version,\n\t\t)\n\tcase \"es\":\n\t\tcmd = exec.Command(spirv.Bin,\n\t\t\t\"--es\",\n\t\t\t\"--version\", version,\n\t\t)\n\tcase \"hlsl\":\n\t\tcmd = exec.Command(spirv.Bin,\n\t\t\t\"--hlsl\",\n\t\t\t\"--shader-model\", version,\n\t\t)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unknown target %q\", target)\n\t}\n\tcmd.Args = append(cmd.Args, \"--no-420pack-extension\", base)\n\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s\\nfailed to run %v: %w\", out, cmd.Args, err)\n\t}\n\ts := string(out)\n\tif target != \"hlsl\" {\n\t\t// Strip Windows \\r in line endings.\n\t\ts = unixLineEnding(s)\n\t}\n\n\treturn s, nil\n}", "func convertFile(filename string) (media map[string]struct{}, err error) {\n\tsrc, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot read file \" + filename + \"\\n\" + err.Error())\n\t}\n\tname := filepath.Base(filename)\n\text := \".md\"\n\tbasename := base(name) // strip \".go\"\n\toutname := filepath.Join(*outDir, basename) + ext\n\tmd, media, err := convert(string(src))\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error converting \" + filename + \"\\n\" + err.Error())\n\t}\n\terr = createPath(*outDir)\n\tif err != nil {\n\t\treturn nil, err // The error message from createPath is chatty enough.\n\t}\n\terr = ioutil.WriteFile(outname, []byte(md), 0644) // -rw-r--r--\n\tif err != nil {\n\t\treturn nil, errors.New(\"Cannot write file \" + outname + \" \\n\" + err.Error())\n\t}\n\treturn media, nil\n}", "func (c *ConvImg) Convert() error {\n\tfiles, err := findImages(c.Path, c.From, log.New(os.Stdout, \"convimg\",1))\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch c.To {\n\tcase \"png\":\n\t\tfmt.Printf(\"%v\", files)\n\t\terr = convertToPngs(files)\n\tcase \"jpg\":\n\t\terr = convertToJpgs(files)\n\tcase \"gif\":\n\t\terr = convertToGifs(files)\n\tdefault:\n\t\treturn errors.New(\"invalid extension\")\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"%v\", err)\n\t}\n\treturn nil\n}", "func FileConvertCodepage(fileName string, fromCP, toCP IDCodePage) error {\n\tswitch {\n\tcase fromCP == toCP:\n\t\treturn nil\n\tcase (fromCP != CP1251) && (fromCP != CP866):\n\t\treturn nil\n\tcase (toCP != CP1251) && (toCP != CP866):\n\t\treturn nil\n\t}\n\tiFile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer iFile.Close()\n\n\t//TODO need using system tmp folder\n\ttmpFileName := fileName + \"~\"\n\toFile, err := os.Create(tmpFileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer oFile.Close()\n\n\ts := \"\"\n\tiScanner := bufio.NewScanner(iFile)\n\tfor i := 0; iScanner.Scan(); i++ {\n\t\ts = iScanner.Text()\n\t\ts, err = StrConvertCodepage(s, fromCP, toCP)\n\t\tif err != nil {\n\t\t\toFile.Close()\n\t\t\tos.Remove(tmpFileName)\n\t\t\treturn fmt.Errorf(\"code page convert error on file '%s': %v\", fileName, err)\n\t\t}\n\t\tfmt.Fprintf(oFile, \"%s\\n\", s)\n\t}\n\toFile.Close()\n\tiFile.Close()\n\treturn os.Rename(tmpFileName, fileName)\n}", "func convert2Aster( filename string, audioformat string ) string{\n\n\tresult, err := exec.Command( \"sox\", workDir+filename+\".wav\", \"-q\", \"-r\", codecs[ audioformat ].rate, \"-t\", \"raw\", workDir+filename+\".\"+codecs[ audioformat ].codec ).Output()\n\n\tif err != nil {\n\t\tlog.Fatalf(\"error transcoding with sox: %v\\n\", err)\n\t}else{\n\t\tos.Remove(workDir+filename+\".mp3\")\n\t\tos.Remove(workDir+filename+\".wav\")\n\t}\n\tif debug == true{\n\t\tlog.Println(result)\n\t}\n\treturn filename\n}", "func (c *Client) ConvertFile(filename string, width uint) (string, error) {\n\timage, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn c.ConvertBytes(image, width)\n}", "func (sfs *SoundFileInfoService) PerformSoundFileConversions(sourcePath string) (error, string, string) {\n\tfileBaseName := filepath.Base(sourcePath)\n\tfileName := strings.TrimSuffix(fileBaseName, filepath.Ext(fileBaseName))\n\n\t// create new destination path\n\tdestinationPath := \"/tmp/\"\n\n\twavDestinationPath := destinationPath + fileName + \".wav\"\n\tpcmaDestinationPath := destinationPath + fileName + \".PCMU\"\n\n\tlogrus.Infoln(\".wav destination path : \" + wavDestinationPath + \"\\n\")\n\n\t// generate .wav file\n\tcommand := fmt.Sprintf(\"ffmpeg -i %s -acodec pcm_s16le -ac 1 -ar 8000 %s >/dev/null 2>&1\", sourcePath, wavDestinationPath)\n\n\tlogrus.Infoln(\".wav conversion command : \" + command)\n\n\tout, error1 := exec.Command(\"sh\", \"-c\", command).Output()\n\tif error1 != nil {\n\t\tlogrus.Errorln(\"Error converting file to .wav : \")\n\t\tlogrus.Errorln(error1.Error())\n\t\tlogrus.Infoln(\"\\n\")\n\t\treturn errors.New(\"Error converting file to .wav\"), \"\", \"\"\n\t}\n\n\tfmt.Printf(\"%s\\n\\n\", out)\n\n\t// generate .pcma file\n\tfsPCMA := fmt.Sprintf(\"sox %s -t raw -r 8k -b 8 -c 1 -e u-law %s\", wavDestinationPath, pcmaDestinationPath)\n\tlogrus.Infoln(\"pcma command : \" + fsPCMA + \"\\n\")\n\tfsPCMAO, error2 := exec.Command(\"sh\", \"-c\", fsPCMA).Output()\n\tif error2 != nil {\n\t\tcmlutils.DeleteFile(wavDestinationPath)\n\t\tlogrus.Errorln(\"Error converting file to .pcma\")\n\t\tlogrus.Errorln(error2.Error())\n\t\treturn errors.New(\"Error converting file to .PCMA\"), \"\", \"\"\n\t}\n\tfmt.Printf(\"%s\\n\\n\", fsPCMAO)\n\n\treturn nil, wavDestinationPath, pcmaDestinationPath\n}", "func (engine UNO) Convert(ctx context.Context, logger *zap.Logger, format, inputPath, outputPath string) error {\n\terr := engine.unoAPI.PDF(ctx, logger, inputPath, outputPath, uno.Options{\n\t\tPDFformat: format,\n\t})\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif errors.Is(err, uno.ErrInvalidPDFformat) {\n\t\treturn fmt.Errorf(\"convert PDF to '%s' with unoconv: %w\", format, gotenberg.ErrPDFFormatNotAvailable)\n\t}\n\n\treturn fmt.Errorf(\"convert PDF to '%s' with unoconv: %w\", format, err)\n}", "func TestConvert(t *testing.T) {\n\tif *convert == \"\" {\n\t\treturn\n\t}\n\tconversions := map[string]string{\n\t\t\"object\": \"json.RawMessage\",\n\t\t\"list<thing>\": \"[]Thing\",\n\t\t\"boolean\": \"bool\",\n\t\t\"long\": \"int64\",\n\t}\n\n\tdata, err := ioutil.ReadFile(*convert)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tfor _, line := range lines {\n\t\tl := bytes.TrimSpace(line)\n\t\tif len(l) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttokens := bytes.Split(l, []byte(\"\\t\"))\n\t\tname := snaker.SnakeToCamel(string(bytes.Title(tokens[1])))\n\t\tif name == \"Id\" {\n\t\t\tname = \"ID\"\n\t\t}\n\t\tt := string(bytes.ToLower(tokens[0]))\n\t\tconverted, ok := conversions[t]\n\t\tif !ok {\n\t\t\tconverted = t\n\t\t}\n\t\tfmt.Printf(\"\\t%s %s `json:\\\"%s\\\"`\\n\", name, converted, string(tokens[1]))\n\t}\n}", "func (w *Walker) convert(path string, info os.FileInfo) (*fspb.File, error) {\n\tpath = filepath.Clean(path)\n\n\tf := &fspb.File{\n\t\tVersion: fileVersion,\n\t\tPath: path,\n\t}\n\n\tif info == nil {\n\t\treturn f, nil\n\t}\n\n\tvar shaSum string\n\t// Only build the hash sum if requested and if it is not a directory.\n\tif w.wantHashing(path) && !info.IsDir() && info.Size() <= w.pol.MaxHashFileSize {\n\t\tvar err error\n\t\tshaSum, err = sha256sum(path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"unable to build hash for %s: %s\", path, err)\n\t\t} else {\n\t\t\tf.Fingerprint = []*fspb.Fingerprint{\n\t\t\t\t{\n\t\t\t\t\tMethod: fspb.Fingerprint_SHA256,\n\t\t\t\t\tValue: shaSum,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\tmts, _ := ptypes.TimestampProto(info.ModTime()) // ignoring the error and using default\n\tf.Info = &fspb.FileInfo{\n\t\tName: info.Name(),\n\t\tSize: info.Size(),\n\t\tMode: uint32(info.Mode()),\n\t\tModified: mts,\n\t\tIsDir: info.IsDir(),\n\t}\n\n\tvar err error\n\tif f.Stat, err = fsstat.ToStat(info); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check the first parameter, true if it wants only a Context check if the handler needs a Context , has the first parameter as type of Context it's usefuly in NewRoute inside route.go
func hasContextParam(handlerType reflect.Type) bool { //if the handler doesn't take arguments, false if handlerType.NumIn() == 0 { return false } //if the first argument is not a pointer, false p1 := handlerType.In(0) if p1.Kind() != reflect.Ptr { return false } //but if the first argument is a context, true if p1.Elem() == contextType { return true } return false }
[ "func requiresContext(handlerType reflect.Type) bool {\n\t//if the method doesn't take arguments, no\n\tif handlerType.NumIn() == 0 {\n\t\treturn false\n\t}\n\n\t//if the first argument is not a pointer, no\n\ta0 := handlerType.In(0)\n\tif a0.Kind() != reflect.Ptr {\n\t\treturn false\n\t}\n\t//if the first argument is a context, yes\n\tif a0.Elem() == contextType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func hasContextAndRenderer(handlerType reflect.Type) bool {\n\n\t//first check if we have pass 2 arguments\n\tif handlerType.NumIn() < 2 {\n\t\treturn false\n\t}\n\n\tfirstParamIsContext := hasContextParam(handlerType)\n\n\t//the first argument/parameter is always context if exists otherwise it's only Renderer or ResponseWriter,Request.\n\tif firstParamIsContext == false {\n\t\treturn false\n\t}\n\n\tp2 := handlerType.In(1)\n\tif p2.Kind() != reflect.Ptr {\n\t\treturn false\n\t}\n\t//but if the first argument is a context, true\n\tif p2.Elem() == rendererType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func RequestContext(ctx context.Context) (events.APIGatewayProxyRequestContext, bool) {\n\tc, ok := ctx.Value(contextKey).(events.APIGatewayProxyRequestContext)\n\treturn c, ok\n}", "func (o *TelemetryDruidScanRequestAllOf) HasContext() bool {\n\tif o != nil && o.Context != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Router) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func ContextHandler(rootCtx context.Context) martini.Handler {\n\treturn func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\tc.Map(withReq(rootCtx, req))\n\t}\n}", "func ContextService(ctx context.Context) (s *Service) {\n\tif d, ok := ctx.Value(contextHandlerDetailsKey).(*handlerDetails); ok {\n\t\ts = d.s\n\t}\n\treturn\n}", "func TestContextIsAccessibleWithGo17Context(t *testing.T) {\n\tsuccHand := func(w http.ResponseWriter, r *http.Request) {\n\t\tr = r.WithContext(context.WithValue(r.Context(), \"dummykey\", \"dummyval\"))\n\t\ttoken := Token(r)\n\t\tif token == \"\" {\n\t\t\tt.Errorf(\"Token is inaccessible in the success handler\")\n\t\t}\n\t}\n\n\thand := New()\n\tchain := alice.New(hand.Handler).Then(http.HandlerFunc(succHand))\n\n\t// we need a request that passes. Let's just use a safe method for that.\n\treq := dummyGet()\n\twriter := httptest.NewRecorder()\n\n\tchain.ServeHTTP(writer, req)\n}", "func (o *ShortenerAPI) Context() *middleware.Context {\n\tif o.context == nil {\n\t\to.context = middleware.NewRoutableContext(o.spec, o, nil)\n\t}\n\n\treturn o.context\n}", "func TestAllowContext(t *testing.T) {\n\ttt := lt.New(t)\n\tappCtx := tt.NewAppCtx(\"test-http\")\n\tappCtx.Config().Request.AllowContext = true\n\n\t// Build handler\n\th := http.NewServer()\n\tvar gotContext journey.Ctx\n\th.HandleFunc(\"/test\", http.GET, func(\n\t\tctx journey.Ctx, w http.ResponseWriter, r *http.Request,\n\t) {\n\t\tctx.Trace(\"http.test\", \"Test endpoint called\")\n\t\tgotContext = ctx\n\t\tw.Head(http.StatusOK)\n\t})\n\n\taddr := startServer(appCtx, h)\n\n\t// Prepare context\n\tctx := journey.New(appCtx)\n\tctx.Trace(\"prepare\", \"Prepare context\")\n\tctx.Store(\"lang\", \"en_GB\")\n\tctx.Store(\"ip\", \"10.0.0.21\")\n\tctx.Store(\"flag\", 3)\n\n\t// Send request\n\tclient := http.Client{}\n\tres, err := client.Get(ctx, fmt.Sprintf(\"http://%s/test\", addr))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif http.StatusOK != res.StatusCode {\n\t\tt.Errorf(\"expect to get status %d, but got %d\", http.StatusOK, res.StatusCode)\n\t}\n\n\t// Compare\n\tif ctx.UUID() == gotContext.UUID() {\n\t\tt.Error(\"expect contexts to be different\")\n\t}\n\tctx.RangeValues(func(key, expect interface{}) bool {\n\t\tv := gotContext.Load(key)\n\t\tif v != nil {\n\t\t\tt.Errorf(\"expect key %s to NOT be present\", key)\n\t\t}\n\t\treturn false\n\t})\n}", "func hasRendererParam(handlerType reflect.Type) bool {\n\t//if the handler doesn't take arguments, false\n\tif handlerType.NumIn() == 0 {\n\t\treturn false\n\t}\n\n\t//if the first argument is not a pointer, false\n\tp1 := handlerType.In(0)\n\tif p1.Kind() != reflect.Ptr {\n\t\treturn false\n\t}\n\t//but if the first argument is a renderer, true\n\tif p1.Elem() == rendererType {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ContextDI() MiddlewareFunc {\n\treturn func(b *Bubble) error {\n\t\tfor idx, argT := range b.ArgumentTypes {\n\t\t\tif contextType.AssignableTo(argT) {\n\t\t\t\tb.Arguments[idx] = reflect.ValueOf(b.Context)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treturn b.Next()\n\t}\n}", "func (r *router) handle(ctx *Context) {\n\tn, params := r.getRoute(ctx.Method, ctx.Pattern)\n\n\tif n != nil { // Found it, start excution\n\t\t// Store wild params\n\t\tctx.Params = params\n\t\t// Use concrete or wild pattern (node pattern in trie tree)\n\t\t// instead of concrete pattern (context pattern from request)\n\t\tkey := ctx.Method + \"-\" + n.pattern\n\t\t// Excute handler last\n\t\tctx.middlewares = append(ctx.middlewares, r.handlers[key])\n\t} else { // Not found, report error\n\t\tctx.Fail(http.StatusNotFound, \"Status Not Found: \"+ctx.Pattern)\n\t}\n\n\t// Switch to context to control excution order\n\tctx.Next()\n}", "func (o *TingtingAPI) Context() *middleware.Context {\n\tif o.context == nil {\n\t\to.context = middleware.NewRoutableContext(o.spec, o, nil)\n\t}\n\n\treturn o.context\n}", "func (m *FalconxHTTPRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (ri *RestInvoker) ContextDo(ctx context.Context, req *rest.Request, options ...InvocationOption) (*rest.Response, error) {\n\topts := getOpts(string(req.GetRequest().Host()), options...)\n\topts.Protocol = common.ProtocolRest\n\tif len(opts.Filters) == 0 {\n\t\topts.Filters = ri.opts.Filters\n\t}\n\tif string(req.GetRequest().URI().Scheme()) != \"cse\" {\n\t\treturn nil, fmt.Errorf(\"Scheme invalid: %s, only support cse://\", req.GetRequest().URI().Scheme())\n\t}\n\tif req.GetHeader(\"Content-Type\") == \"\" {\n\t\treq.SetHeader(\"Content-Type\", \"application/json\")\n\t}\n\tnewReq := req.Copy()\n\tdefer newReq.Close()\n\tresp := rest.NewResponse()\n\tnewReq.SetHeader(common.HeaderSourceName, config.SelfServiceName)\n\tinv := invocation.CreateInvocation()\n\twrapInvocationWithOpts(inv, opts)\n\tinv.AppID = config.GlobalDefinition.AppID\n\tinv.MicroServiceName = string(req.GetRequest().Host())\n\tinv.Args = newReq\n\tinv.Reply = resp\n\tinv.Ctx = ctx\n\tinv.URLPathFormat = req.Req.URI().String()\n\tinv.MethodType = req.GetMethod()\n\tc, err := handler.GetChain(common.Consumer, ri.opts.ChainName)\n\tif err != nil {\n\t\tlager.Logger.Errorf(err, \"Handler chain init err.\")\n\t\treturn nil, err\n\t}\n\tc.Next(inv, func(ir *invocation.InvocationResponse) error {\n\t\terr = ir.Err\n\t\treturn err\n\t})\n\treturn resp, err\n}", "func (route *Route) DoesMatchContext(c *Context) bool {\n\n\t// by default, we match\n\tvar match bool = true\n\tif len(route.MatcherFuncs) > 0 {\n\n\t\t// there are some matcher functions, so don't automatically\n\t\t// match by default - let the matchers decide\n\t\tmatch = false\n\n\t\t// loop through the matcher functions\n\t\tfor _, f := range route.MatcherFuncs {\n\t\t\t// modify 'match' based on the result of the matcher function\n\t\t\tswitch f(c) {\n\t\t\tcase NoMatch:\n\t\t\t\tmatch = false\n\t\t\tcase Match:\n\t\t\t\tmatch = true\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// return the result\n\treturn match\n\n}", "func (m HTTPMethod) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func CheckHeaderValueAndForwardWithRequestContext(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\taccessToken := req.Header.Get(common.FlorenceHeaderKey)\n\t\tif accessToken != \"\" {\n\t\t\treq = addUserAccessTokenToRequestContext(accessToken, req)\n\t\t}\n\n\t\th.ServeHTTP(w, req)\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }